finance-query 3.0.0

A Rust library for querying financial data
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
//! Domain-specific query handles — non-equity asset classes.
//!
//! These types are constructable only through [`Providers`](crate::Providers)
//! factory methods — they share the same provider connections and configuration.
//!
//! Each handle maps to a [`Capability`](crate::Capability) and routes through
//! the multi-provider dispatch system, making multi-source aggregation
//! a first-class concept rather than an opt-in on Ticker/Tickers.

// ── Caching ─────────────────────────────────────────────────────────

use crate::error::Result;
use crate::utils::{CacheEntry, CacheMode, FetchGuards};
use std::collections::HashMap;
use tokio::sync::RwLock;

/// Per-handle response cache with request deduplication.
///
/// Keyed by a `String` so a handle can cache multiple variants (e.g. a
/// crypto coin priced in different `vs_currency` values); single-result
/// handles use the empty string. Caches for 60 seconds by default;
/// `.cache(ttl)` changes that window and `.no_cache()` disables it.
pub(crate) struct DomainCache<V> {
    mode: CacheMode,
    entries: RwLock<HashMap<String, CacheEntry<V>>>,
    guards: FetchGuards<String>,
}

impl<V: Clone> DomainCache<V> {
    pub(crate) fn new(mode: CacheMode) -> Self {
        Self {
            mode,
            entries: RwLock::new(HashMap::new()),
            guards: FetchGuards::default(),
        }
    }

    /// Return a fresh cached value for `key`, or run `f` to fetch it.
    /// Concurrent identical misses collapse to a single upstream call.
    pub(crate) async fn get_or_try<F, Fut>(&self, key: String, f: F) -> Result<V>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<V>>,
    {
        if !self.mode.enabled() {
            return f().await;
        }

        if let Some(entry) = self.entries.read().await.get(&key)
            && entry.is_fresh(self.mode)
        {
            return Ok(entry.value.clone());
        }

        self.guards
            .dedup(key.clone(), || async {
                if let Some(entry) = self.entries.read().await.get(&key)
                    && entry.is_fresh(self.mode)
                {
                    return Ok(entry.value.clone());
                }

                let value = f().await?;
                crate::utils::cache_insert(
                    &mut *self.entries.write().await,
                    key.clone(),
                    value.clone(),
                    self.mode,
                    crate::utils::EVICTION_THRESHOLD,
                );
                Ok(value)
            })
            .await
    }
}

// ── Macros ──────────────────────────────────────────────────────────

/// Generate a single-field domain handle struct with internal constructor,
/// a string accessor, and an optional response cache (`.cache(ttl)`).
/// Callers add fetch methods manually.
macro_rules! domain_handle {
    // Chartable variant — adds a `Chart` response cache read by `chart()`.
    // `extra:` declares further per-response caches for methods whose return
    // type differs from the handle's main one; `.cache(ttl)` covers them all.
    (
        $(#[$meta:meta])*
        pub struct $name:ident { $field:ident, $accessor:ident }
        cache: $val:ty, chart
        $(, extra: { $( $(#[$ecfg:meta])* $ecache:ident: $eval:ty ),+ $(,)? } )?
    ) => {
        $(#[$meta])*
        pub struct $name {
            $field: std::sync::Arc<str>,
            providers: std::sync::Arc<crate::providers::ProviderSet>,
            cache: crate::domains::DomainCache<$val>,
            chart_cache: crate::domains::DomainCache<crate::models::chart::Chart>,
            $($( $(#[$ecfg])* $ecache: crate::domains::DomainCache<$eval>, )+)?
        }

        impl $name {
            pub(crate) fn with_providers(
                $field: std::sync::Arc<str>,
                providers: std::sync::Arc<crate::providers::ProviderSet>,
            ) -> Self {
                Self {
                    $field,
                    providers,
                    cache: crate::domains::DomainCache::new(crate::utils::CacheMode::default()),
                    chart_cache: crate::domains::DomainCache::new(crate::utils::CacheMode::default()),
                    $($(
                        $(#[$ecfg])*
                        $ecache: crate::domains::DomainCache::new(crate::utils::CacheMode::default()),
                    )+)?
                }
            }

            /// Cache responses for `ttl` instead of the default 60 seconds,
            /// deduplicating concurrent identical requests.
            pub fn cache(mut self, ttl: std::time::Duration) -> Self {
                let mode = crate::utils::CacheMode::Ttl(ttl);
                self.cache = crate::domains::DomainCache::new(mode);
                self.chart_cache = crate::domains::DomainCache::new(mode);
                $($(
                    $(#[$ecfg])*
                    { self.$ecache = crate::domains::DomainCache::new(mode); }
                )+)?
                self
            }

            /// Cache responses for the handle's lifetime instead of the
            /// default 60 seconds.
            pub fn cache_forever(mut self) -> Self {
                let mode = crate::utils::CacheMode::Lifetime;
                self.cache = crate::domains::DomainCache::new(mode);
                self.chart_cache = crate::domains::DomainCache::new(mode);
                $($(
                    $(#[$ecfg])*
                    { self.$ecache = crate::domains::DomainCache::new(mode); }
                )+)?
                self
            }

            /// Disable caching — every call fetches fresh data.
            pub fn no_cache(mut self) -> Self {
                let mode = crate::utils::CacheMode::Off;
                self.cache = crate::domains::DomainCache::new(mode);
                self.chart_cache = crate::domains::DomainCache::new(mode);
                $($(
                    $(#[$ecfg])*
                    { self.$ecache = crate::domains::DomainCache::new(mode); }
                )+)?
                self
            }

            /// The handle's identifier string.
            pub fn $accessor(&self) -> &str {
                &self.$field
            }
        }
    };

    // Two-key chartable variant (e.g. forex pairs) — two identifier fields
    // with their own accessors instead of one shared field/accessor.
    (
        $(#[$meta:meta])*
        pub struct $name:ident {
            $(#[$meta1:meta])* $field1:ident, $accessor1:ident,
            $(#[$meta2:meta])* $field2:ident, $accessor2:ident $(,)?
        } cache: $val:ty, chart
    ) => {
        $(#[$meta])*
        pub struct $name {
            $field1: std::sync::Arc<str>,
            $field2: std::sync::Arc<str>,
            providers: std::sync::Arc<crate::providers::ProviderSet>,
            cache: crate::domains::DomainCache<$val>,
            chart_cache: crate::domains::DomainCache<crate::models::chart::Chart>,
        }

        impl $name {
            pub(crate) fn with_providers(
                $field1: std::sync::Arc<str>,
                $field2: std::sync::Arc<str>,
                providers: std::sync::Arc<crate::providers::ProviderSet>,
            ) -> Self {
                Self {
                    $field1,
                    $field2,
                    providers,
                    cache: crate::domains::DomainCache::new(crate::utils::CacheMode::default()),
                    chart_cache: crate::domains::DomainCache::new(crate::utils::CacheMode::default()),
                }
            }

            /// Cache responses for `ttl` instead of the default 60 seconds,
            /// deduplicating concurrent identical requests.
            pub fn cache(mut self, ttl: std::time::Duration) -> Self {
                let mode = crate::utils::CacheMode::Ttl(ttl);
                self.cache = crate::domains::DomainCache::new(mode);
                self.chart_cache = crate::domains::DomainCache::new(mode);
                self
            }

            /// Cache responses for the handle's lifetime instead of the
            /// default 60 seconds.
            pub fn cache_forever(mut self) -> Self {
                let mode = crate::utils::CacheMode::Lifetime;
                self.cache = crate::domains::DomainCache::new(mode);
                self.chart_cache = crate::domains::DomainCache::new(mode);
                self
            }

            /// Disable caching — every call fetches fresh data.
            pub fn no_cache(mut self) -> Self {
                let mode = crate::utils::CacheMode::Off;
                self.cache = crate::domains::DomainCache::new(mode);
                self.chart_cache = crate::domains::DomainCache::new(mode);
                self
            }

            $(#[$meta1])*
            pub fn $accessor1(&self) -> &str {
                &self.$field1
            }

            $(#[$meta2])*
            pub fn $accessor2(&self) -> &str {
                &self.$field2
            }
        }
    };

    // Non-chartable variant.
    ($(#[$meta:meta])* pub struct $name:ident { $field:ident, $accessor:ident } cache: $val:ty) => {
        $(#[$meta])*
        pub struct $name {
            $field: std::sync::Arc<str>,
            providers: std::sync::Arc<crate::providers::ProviderSet>,
            cache: crate::domains::DomainCache<$val>,
        }

        impl $name {
            pub(crate) fn with_providers(
                $field: std::sync::Arc<str>,
                providers: std::sync::Arc<crate::providers::ProviderSet>,
            ) -> Self {
                Self {
                    $field,
                    providers,
                    cache: crate::domains::DomainCache::new(crate::utils::CacheMode::default()),
                }
            }

            /// Cache responses for `ttl` instead of the default 60 seconds,
            /// deduplicating concurrent identical requests.
            pub fn cache(mut self, ttl: std::time::Duration) -> Self {
                self.cache = crate::domains::DomainCache::new(crate::utils::CacheMode::Ttl(ttl));
                self
            }

            /// Cache responses for the handle's lifetime instead of the
            /// default 60 seconds.
            pub fn cache_forever(mut self) -> Self {
                self.cache = crate::domains::DomainCache::new(crate::utils::CacheMode::Lifetime);
                self
            }

            /// Disable caching — every call fetches fresh data.
            pub fn no_cache(mut self) -> Self {
                self.cache = crate::domains::DomainCache::new(crate::utils::CacheMode::Off);
                self
            }

            /// The handle's identifier string.
            pub fn $accessor(&self) -> &str {
                &self.$field
            }
        }
    };

    // Market-wide variant — no identifier field, since these handles describe
    // the market rather than one instrument. Takes one or more named response
    // caches; `.cache(ttl)` / `.no_cache()` reset all of them together. `cfg:`
    // is a slot rather than a plain attribute because the gate has to reach the
    // generated `impl` block too, not just the struct.
    (
        $(#[$meta:meta])*
        pub struct $name:ident
        $(cfg: $cfg:meta,)?
        caches: { $($cache:ident : $val:ty),+ $(,)? }
    ) => {
        $(#[$meta])*
        $(#[cfg($cfg)])?
        pub struct $name {
            providers: std::sync::Arc<crate::providers::ProviderSet>,
            $($cache: crate::domains::DomainCache<$val>,)+
        }

        $(#[cfg($cfg)])?
        impl $name {
            pub(crate) fn with_providers(
                providers: std::sync::Arc<crate::providers::ProviderSet>,
            ) -> Self {
                Self {
                    providers,
                    $($cache: crate::domains::DomainCache::new(
                        crate::utils::CacheMode::default(),
                    ),)+
                }
            }

            /// Cache responses for `ttl` instead of the default 60 seconds,
            /// deduplicating concurrent identical requests.
            pub fn cache(mut self, ttl: std::time::Duration) -> Self {
                let mode = crate::utils::CacheMode::Ttl(ttl);
                $(self.$cache = crate::domains::DomainCache::new(mode);)+
                self
            }

            /// Cache responses for the handle's lifetime instead of the
            /// default 60 seconds.
            pub fn cache_forever(mut self) -> Self {
                let mode = crate::utils::CacheMode::Lifetime;
                $(self.$cache = crate::domains::DomainCache::new(mode);)+
                self
            }

            /// Disable caching — every call fetches fresh data.
            pub fn no_cache(mut self) -> Self {
                let mode = crate::utils::CacheMode::Off;
                $(self.$cache = crate::domains::DomainCache::new(mode);)+
                self
            }
        }
    };
}

/// Dispatch an uncached provider call. `$owned` names values cloned per
/// attempt (dispatch may try several providers); `$arg`s are the call's own
/// arguments and may borrow those clones.
#[allow(unused_macros)]
macro_rules! dispatch_via {
    (
        $self:expr, $cap:ident, $acc:ident, $op:ident, $fetch:ident,
        [$($owned:ident),* $(,)?] $(, $arg:expr)* $(,)?
    ) => {{
        $self
            .providers
            .fetch(crate::providers::Capability::$cap, move |p| {
                $(let $owned = $owned.clone();)*
                let p = p.clone();
                async move {
                    p.$acc()
                        .ok_or_else(|| p.not_supported(crate::providers::Operation::$op))?
                        .$fetch($($arg),*)
                        .await
                }
            })
            .await
    }};
}

/// Fetch via the provider dispatch — single symbol field, no extra args.
/// Routes through the handle's cache. Use inside a method body.
/// `$acc` is the `ProviderAdapter` capability accessor (e.g. `as_economic`)
/// and `$op` the [`Operation`](crate::providers::Operation) reported when a
/// routed provider lacks it.
macro_rules! fetch_via {
    ($self:expr, $field:ident, $cap:ident, $acc:ident, $op:ident, $fetch:ident, $ret:ty) => {
        fetch_via!(cache: cache, $self, $field, $cap, $acc, $op, $fetch, $ret)
    };
    (cache: $store:ident, $self:expr, $field:ident, $cap:ident, $acc:ident, $op:ident, $fetch:ident, $ret:ty) => {{
        let __sym = $self.$field.clone();
        let __providers = std::sync::Arc::clone(&$self.providers);
        $self
            .$store
            .get_or_try(String::new(), move || async move {
                __providers
                    .fetch(crate::providers::Capability::$cap, move |p| {
                        let __s = __sym.clone();
                        let p = p.clone();
                        async move {
                            p.$acc()
                                .ok_or_else(|| p.not_supported(crate::providers::Operation::$op))?
                                .$fetch(&__s)
                                .await
                        }
                    })
                    .await
            })
            .await
    }};
}

/// Fetch via the provider dispatch — two identifier fields (e.g. forex's
/// `from`/`to`), cached under the empty-string key. Use inside a method body.
#[allow(unused_macros)]
macro_rules! fetch_via_two {
    ($self:expr, $field1:ident, $field2:ident, $cap:ident, $acc:ident, $op:ident, $fetch:ident, $ret:ty) => {{
        let __a = $self.$field1.clone();
        let __b = $self.$field2.clone();
        let __providers = std::sync::Arc::clone(&$self.providers);
        $self
            .cache
            .get_or_try(String::new(), move || async move {
                __providers
                    .fetch(crate::providers::Capability::$cap, move |p| {
                        let __x = __a.clone();
                        let __y = __b.clone();
                        let p = p.clone();
                        async move {
                            p.$acc()
                                .ok_or_else(|| p.not_supported(crate::providers::Operation::$op))?
                                .$fetch(&__x, &__y)
                                .await
                        }
                    })
                    .await
            })
            .await
    }};
}

/// Fetch with one extra string argument (e.g. `vs_currency` for crypto),
/// keyed in the cache by that argument.
#[allow(unused_macros)]
macro_rules! fetch_via_with {
    ($self:expr, $field:ident, $cap:ident, $acc:ident, $op:ident, $fetch:ident, $arg:expr, $ret:ty) => {{
        let __sym = $self.$field.clone();
        let __arg = ($arg).to_string();
        let __providers = std::sync::Arc::clone(&$self.providers);
        $self
            .cache
            .get_or_try(__arg.clone(), move || async move {
                __providers
                    .fetch(crate::providers::Capability::$cap, move |p| {
                        let __s = __sym.clone();
                        let __a = __arg.clone();
                        let p = p.clone();
                        async move {
                            p.$acc()
                                .ok_or_else(|| p.not_supported(crate::providers::Operation::$op))?
                                .$fetch(&__s, &__a)
                                .await
                        }
                    })
                    .await
            })
            .await
    }};
}

/// Fetch chart candles via the `CHART` capability, keyed by `(interval, range)`.
/// `$sym` is the chart-ready symbol expression for this asset class.
#[allow(unused_macros)]
macro_rules! fetch_chart_via {
    ($self:expr, $sym:expr, $interval:expr, $range:expr) => {{
        let __sym: String = $sym;
        let __interval = $interval;
        let __range = $range;
        let __providers = std::sync::Arc::clone(&$self.providers);
        let __key = format!("{}:{}:{}", __sym, __interval, __range);
        $self
            .chart_cache
            .get_or_try(__key, move || async move {
                __providers
                    .fetch(crate::providers::Capability::CHART, move |p| {
                        let __s = __sym.clone();
                        let p = p.clone();
                        async move {
                            p.as_chart()
                                .ok_or_else(|| p.not_supported(crate::providers::Operation::Chart))?
                                .fetch_chart(&__s, __interval, __range)
                                .await
                        }
                    })
                    .await
            })
            .await
    }};
}

/// Generate `indicators()`, `indicator()`, and `risk()` for a chartable handle
/// whose `chart(interval, range)` takes no extra arguments. All three reuse the
/// cached `chart()`; `risk()` annualises with the handle's `$cal`
/// ([`TradingCalendar`](crate::risk::TradingCalendar)). Crypto is hand-written
/// (its `chart()` also takes a `vs_currency`).
#[allow(unused_macros)]
macro_rules! impl_chartable_analytics {
    ($name:ident, $cal:expr) => {
        impl $name {
            /// Compute all technical indicators from this handle's chart data.
            #[cfg(feature = "indicators")]
            pub async fn indicators(
                &self,
                interval: crate::Interval,
                range: crate::TimeRange,
            ) -> crate::error::Result<crate::indicators::IndicatorsSummary> {
                let chart = self.chart(interval, range).await?;
                Ok(crate::indicators::summary::calculate_indicators(
                    &chart.candles,
                ))
            }

            /// Compute a single technical indicator from this handle's chart data.
            #[cfg(feature = "indicators")]
            pub async fn indicator(
                &self,
                indicator: crate::indicators::Indicator,
                interval: crate::Interval,
                range: crate::TimeRange,
            ) -> crate::error::Result<crate::indicators::IndicatorResult> {
                let chart = self.chart(interval, range).await?;
                Ok(crate::indicators::compute_indicator(indicator, &chart)?)
            }

            /// Compute a risk summary (VaR, Sharpe/Sortino/Calmar, max drawdown)
            /// from this handle's chart data. Annualised with this asset class's
            /// trading calendar, so non-daily intervals scale correctly. `beta`
            /// is always `None` (no benchmark for non-equity handles).
            #[cfg(feature = "risk")]
            pub async fn risk(
                &self,
                interval: crate::Interval,
                range: crate::TimeRange,
            ) -> crate::error::Result<crate::risk::RiskSummary> {
                let chart = self.chart(interval, range).await?;
                Ok(crate::risk::compute_risk_summary_with_periods(
                    &chart.candles,
                    None,
                    crate::risk::periods_per_year(interval, $cal),
                ))
            }
        }
    };
}

// ── Modules ─────────────────────────────────────────────────────────

pub(crate) mod commodities;
pub(crate) mod crypto;
pub(crate) mod discovery;
pub(crate) mod economic;
pub(crate) mod filings;
pub(crate) mod forex;
pub(crate) mod futures;
pub(crate) mod indices;
pub(crate) mod market;
pub(crate) mod snapshot;

// ── Re-exports ──────────────────────────────────────────────────────

pub use commodities::Commodity;
pub use crypto::CryptoCoin;
pub use discovery::Discovery;
pub use economic::{EconomicCatalog, EconomicIndicator};
pub use filings::Filings;
pub use forex::ForexPair;
pub use futures::FuturesContract;
pub use indices::Index;
pub use market::Market;
pub use market::MarketCalendar;
pub use snapshot::Snapshot;

// ── Tests ───────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::FinanceError;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    fn err() -> FinanceError {
        FinanceError::NoProviderAvailable {
            operation: crate::providers::Capability::QUOTE,
            candidates: Vec::new(),
        }
    }

    #[tokio::test]
    async fn default_caches_across_calls() {
        let cache: DomainCache<u32> = DomainCache::new(CacheMode::default());
        let calls = Arc::new(AtomicUsize::new(0));
        for _ in 0..3 {
            let c = calls.clone();
            let v = cache
                .get_or_try(String::new(), move || async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    Ok::<u32, FinanceError>(42)
                })
                .await
                .unwrap();
            assert_eq!(v, 42);
        }
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn off_fetches_every_call() {
        let cache: DomainCache<u32> = DomainCache::new(CacheMode::Off);
        let calls = Arc::new(AtomicUsize::new(0));
        for _ in 0..3 {
            let c = calls.clone();
            let v = cache
                .get_or_try(String::new(), move || async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    Ok::<u32, FinanceError>(42)
                })
                .await
                .unwrap();
            assert_eq!(v, 42);
        }
        assert_eq!(calls.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn ttl_caches_within_window() {
        let cache: DomainCache<u32> = DomainCache::new(CacheMode::Ttl(Duration::from_secs(60)));
        let calls = Arc::new(AtomicUsize::new(0));
        for _ in 0..3 {
            let c = calls.clone();
            let v = cache
                .get_or_try(String::new(), move || async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    Ok::<u32, FinanceError>(7)
                })
                .await
                .unwrap();
            assert_eq!(v, 7);
        }
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn distinct_keys_cached_separately() {
        let cache: DomainCache<String> = DomainCache::new(CacheMode::Ttl(Duration::from_secs(60)));
        let calls = Arc::new(AtomicUsize::new(0));
        for key in ["usd", "eur", "usd", "eur"] {
            let c = calls.clone();
            let owned = key.to_string();
            let v = cache
                .get_or_try(key.to_string(), move || async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    Ok::<String, FinanceError>(owned)
                })
                .await
                .unwrap();
            assert_eq!(v, key);
        }
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn errors_are_not_cached() {
        let cache: DomainCache<u32> = DomainCache::new(CacheMode::Ttl(Duration::from_secs(60)));
        let calls = Arc::new(AtomicUsize::new(0));

        let c = calls.clone();
        let first = cache
            .get_or_try(String::new(), move || async move {
                c.fetch_add(1, Ordering::SeqCst);
                Err::<u32, FinanceError>(err())
            })
            .await;
        assert!(first.is_err());

        let c = calls.clone();
        let second = cache
            .get_or_try(String::new(), move || async move {
                c.fetch_add(1, Ordering::SeqCst);
                Ok::<u32, FinanceError>(5)
            })
            .await
            .unwrap();
        assert_eq!(second, 5);
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn concurrent_misses_dedup_to_one_fetch() {
        let cache: Arc<DomainCache<u32>> =
            Arc::new(DomainCache::new(CacheMode::Ttl(Duration::from_secs(60))));
        let calls = Arc::new(AtomicUsize::new(0));
        let mut handles = Vec::new();
        for _ in 0..8 {
            let cache = Arc::clone(&cache);
            let c = calls.clone();
            handles.push(tokio::spawn(async move {
                cache
                    .get_or_try(String::new(), move || async move {
                        c.fetch_add(1, Ordering::SeqCst);
                        tokio::time::sleep(Duration::from_millis(20)).await;
                        Ok::<u32, FinanceError>(1)
                    })
                    .await
                    .unwrap()
            }));
        }
        for h in handles {
            assert_eq!(h.await.unwrap(), 1);
        }
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn failed_fetches_still_dedup_for_waiters() {
        // The guard entry is dropped on the error path too, but waiters have
        // already cloned the `Arc`. Removing it unconditionally would let a
        // waiter and a fresh arrival hold two different mutexes and fetch the
        // same key at once.
        let cache: Arc<DomainCache<u32>> =
            Arc::new(DomainCache::new(CacheMode::Ttl(Duration::from_secs(60))));
        let in_flight = Arc::new(AtomicUsize::new(0));
        let overlap = Arc::new(AtomicUsize::new(0));

        let mut handles = Vec::new();
        for i in 0..8 {
            let cache = Arc::clone(&cache);
            let in_flight = Arc::clone(&in_flight);
            let overlap = Arc::clone(&overlap);
            handles.push(tokio::spawn(async move {
                cache
                    .get_or_try("k".to_string(), move || async move {
                        if in_flight.fetch_add(1, Ordering::SeqCst) > 0 {
                            overlap.fetch_add(1, Ordering::SeqCst);
                        }
                        tokio::time::sleep(Duration::from_millis(20)).await;
                        in_flight.fetch_sub(1, Ordering::SeqCst);
                        // Every attempt fails, so nothing is ever written to
                        // `entries` and each waiter runs its own fetch in turn.
                        Err::<u32, FinanceError>(FinanceError::ApiError(format!("boom {i}")))
                    })
                    .await
            }));
        }
        for h in handles {
            assert!(h.await.unwrap().is_err());
        }
        assert_eq!(
            overlap.load(Ordering::SeqCst),
            0,
            "fetches for one key overlapped; the dedup guard was dropped too early"
        );
    }

    #[tokio::test]
    async fn entries_are_bounded_under_lifetime_caching() {
        // Nothing expires under `Lifetime`, so without an eviction sweep this map
        // grows without limit for a handle queried across many keys.
        let cache: DomainCache<u32> = DomainCache::new(CacheMode::Lifetime);
        for i in 0..500u32 {
            cache
                .get_or_try(i.to_string(), || async move { Ok::<u32, FinanceError>(i) })
                .await
                .unwrap();
        }
        let len = cache.entries.read().await.len();
        assert!(
            len <= crate::utils::EVICTION_THRESHOLD,
            "domain cache grew to {len} entries"
        );
    }

    #[tokio::test]
    async fn distinct_keys_do_not_serialize() {
        let cache: Arc<DomainCache<u32>> = Arc::new(DomainCache::new(CacheMode::default()));
        let mut handles = Vec::new();
        for k in ["a", "b", "c", "d"] {
            let cache = Arc::clone(&cache);
            handles.push(tokio::spawn(async move {
                cache
                    .get_or_try(k.to_string(), || async {
                        tokio::time::sleep(Duration::from_millis(80)).await;
                        Ok::<u32, FinanceError>(1)
                    })
                    .await
                    .unwrap()
            }));
        }
        let start = tokio::time::Instant::now();
        for h in handles {
            assert_eq!(h.await.unwrap(), 1);
        }
        assert!(
            start.elapsed() < Duration::from_millis(200),
            "four distinct keys took {:?}; they are serializing",
            start.elapsed()
        );
    }
}