basecamp-sdk 0.38.0

Official client for Basecamp - https://basecamp.com
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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
//! Campfire discovery for chat lines: the two sources
//! [`RecordingsService::summarize`](crate::services::recordings::RecordingsService::summarize)
//! consults to find the Campfire a line lives in, and the bounded, TTL'd cache they are
//! read through.
//!
//! A `chat.line.created` row carries the line's id and bucket, not its Campfire, and the
//! line read is `GET /chats/{campfireId}/lines/{lineId}`. Candidates come from two sources,
//! tried in order and each cached [`CAMPFIRE_INDEX_TTL`]:
//!
//! 1. The bucket's own Campfire. For a project, its dock's `chat` tool: one project read per
//!    bucket, and the answer for every line posted in a project. For a bucket that is not a
//!    project (the project read answers 404), the Ping read, since a ping's bucket (its type
//!    and wire path are "Circle") holds one Campfire, named by the Ping's `room_url`. Cached
//!    per bucket.
//! 2. The account-wide Campfire listing (BC3 has no per-bucket one), filtered to the
//!    bucket, for buckets that are neither or whose own Campfire did not hold the line. BC3
//!    lists only dock-positioned Campfires there, so a ping's is never in it. Cached per
//!    account, so a burst of lines costs one listing.
//!
//! The index lives on the client every [`AccountClient`] is derived from, and a client is
//! bound to one credential, so entries are never shared across authorization contexts —
//! and every key carries the account id besides. Expired snapshots are swept at each load
//! and each cache is bounded (a fixed entry count, oldest out first), so the index
//! holds at most the buckets and accounts consulted within the last TTL, and never more
//! than the bound, whatever the client has seen.

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

use futures_util::FutureExt;
use futures_util::future::{BoxFuture, WeakShared};

use crate::client::AccountClient;
use crate::error::{Error, ErrorCode};
use crate::generated::services::campfires::ListCampfiresParams;
use crate::generated::types::DockItem;

/// How long a cached discovery source — a bucket's own Campfire, the account's Campfire
/// listing — is reused before it is read again.
pub const CAMPFIRE_INDEX_TTL: Duration = Duration::from_secs(10 * 60);

/// Bounds the refresh-on-miss: a line found under no candidate re-reads the cached sources,
/// but not more often than this per source, so a run of unresolvable lines cannot turn into
/// a listing per line.
/// [`UnresolvedRecording::refreshed`](crate::services::recordings::UnresolvedRecording::refreshed)
/// says whether the floor applied.
pub const CAMPFIRE_INDEX_MIN_REFRESH: Duration = Duration::from_secs(30);

/// How many Campfires one
/// [`summarize`](crate::services::recordings::RecordingsService::summarize) call tries,
/// across both sources and the refresh. A project or a Ping has one Campfire; a bucket
/// past this bound is not a shape BC3 produces, and the call reports
/// [`RecordingSummaryError::CampfireDiscoveryIncomplete`](crate::services::recordings::RecordingSummaryError::CampfireDiscoveryIncomplete)
/// rather than calling the rest absent.
pub const MAX_CAMPFIRE_CANDIDATES: usize = 50;

/// Caps the account-wide Campfire listing the fallback source reads. A listing that
/// overflows it is not cached and the call reports incomplete discovery: the bucket's own
/// Campfire covers every project and every ping, so the listing only ever serves the
/// leftover, and an account with more
/// Campfires than this should not pay a full walk per ten minutes for it.
pub const MAX_CAMPFIRE_LISTING: usize = 1000;

/// Bounds each discovery cache's entry count. The bucket cache holds one snapshot per bucket
/// consulted within the TTL: a connector listening across every project an agent can see
/// touches hundreds of buckets, not thousands, and a snapshot is a handful of ids, so 1024
/// is generous headroom at a few hundred KB, and the bound exists so that a process alive
/// for weeks can never grow past it whatever it sees. When the bound is reached the
/// oldest-fetched entries go first, deterministically.
const CAMPFIRE_INDEX_MAX_ITEMS: usize = 1024;

/// The dock tool whose id is the project's Campfire.
const CHAT_DOCK_TOOL: &str = "chat";

/// The id of the Campfire a Ping's `room_url` names: a path ending in `/chats/{digits}`,
/// with or without `.json`. The URL is a bucket-scoped one, which the route table does not
/// carry for `GetCampfire`, so the shape is read here.
fn campfire_id_from_room_url(room_url: &str) -> Option<i64> {
    let path = match url::Url::parse(room_url) {
        Ok(parsed) if !parsed.cannot_be_a_base() => parsed.path().to_string(),
        _ => room_url
            .split(['?', '#'])
            .next()
            .unwrap_or_default()
            .to_string(),
    };
    let last = path.strip_suffix(".json").unwrap_or(&path);
    let (head, id) = last.rsplit_once('/')?;
    if !head.ends_with("/chats") && head != "chats" {
        return None;
    }
    if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    id.parse().ok().filter(|id| *id != 0)
}

/// A reader of the current instant, so a test can move time without sleeping.
pub(crate) type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;

/// What a cache read hands back: the value, when it was fetched, and whether it predated
/// the call (as opposed to being loaded during it, by this caller or by one it waited on).
/// The fetch time is what lets a caller tell a snapshot it already consulted from a newer
/// one, whoever loaded it.
pub(crate) struct Hit<V> {
    pub(crate) value: Arc<V>,
    pub(crate) fetched: Instant,
    pub(crate) cached: bool,
}

struct Entry<V> {
    value: Arc<V>,
    fetched: Instant,
    /// Publication order: the tie-breaker when fetch times are equal, so eviction is total
    /// rather than whatever the map happens to visit first.
    seq: u64,
}

type Loaded<V> = Result<(Arc<V>, Instant), Arc<Error>>;
/// How the map REMEMBERS a load without owning it; see [`CacheState::inflight`]. The
/// owning handle is the `Shared` each caller holds while it waits.
type PendingSlot<V> = WeakShared<BoxFuture<'static, Loaded<V>>>;

/// One load's registration: the weak handle, and the identity that says WHOSE it is.
struct Registration<V> {
    id: u64,
    slot: PendingSlot<V>,
}

struct CacheState<K, V> {
    seq: u64,
    /// Hands out a distinct identity to each load, so a publication can prove the
    /// registration it is about to retire is its own.
    loads: u64,
    entries: HashMap<K, Entry<V>>,
    /// The loads under way, held WEAKLY.
    ///
    /// A load captures the client it reads through, and that client owns this cache, so a
    /// map that owned the load would close a cycle no `Weak` on the publication handle can
    /// open: cache → slot → load → `AccountClient` → client → cache. Dropping every client
    /// handle would then free nothing — not the credentials, not the connection pool, not
    /// this index — for the life of the process, and no sweep would ever run again to
    /// notice, because nothing is left to call in.
    ///
    /// Holding the load weakly means the callers own it and it lives exactly as long as
    /// somebody is waiting on it. A slot whose load every caller dropped upgrades to
    /// `None`, and the next caller starts a fresh one.
    inflight: HashMap<K, Registration<V>>,
}

/// A per-key cache with single-flight loading: concurrent callers for one key wait on the
/// one load in progress rather than loading again, a failed load leaves the previous value
/// in place, and a refresh is honoured only once the value is older than a floor.
///
/// The load runs as a shared future, so a caller dropped mid-load — an operation deadline
/// shorter than the listing's round trip — leaves the load for whoever is still waiting on
/// it rather than abandoning the key in flight.
pub(crate) struct TtlCache<K, V> {
    state: Mutex<CacheState<K, V>>,
    clock: Clock,
    ttl: Duration,
    floor: Duration,
    max_items: usize,
}

impl<K, V> TtlCache<K, V>
where
    K: Eq + Hash + Clone + Send + Sync + 'static,
    V: Send + Sync + 'static,
{
    fn new(clock: Clock, ttl: Duration, floor: Duration, max_items: usize) -> TtlCache<K, V> {
        TtlCache {
            state: Mutex::new(CacheState {
                seq: 0,
                loads: 0,
                entries: HashMap::new(),
                inflight: HashMap::new(),
            }),
            clock,
            ttl,
            floor,
            max_items,
        }
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, CacheState<K, V>> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// The value for `key`, loading it when absent or older than the TTL — or, with
    /// `refresh` set, older than the floor.
    pub(crate) async fn get<F, Fut>(
        self: &Arc<Self>,
        key: &K,
        refresh: bool,
        load: F,
    ) -> Result<Hit<V>, Error>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<V, Error>> + Send + 'static,
    {
        let pending = {
            let mut state = self.lock();
            if let Some(entry) = state.entries.get(key) {
                let age = (self.clock)().saturating_duration_since(entry.fetched);
                if age < self.ttl && (!refresh || age < self.floor) {
                    return Ok(Hit {
                        value: Arc::clone(&entry.value),
                        fetched: entry.fetched,
                        cached: true,
                    });
                }
            }
            if let Some(pending) = state
                .inflight
                .get(key)
                .and_then(|registered| registered.slot.upgrade())
            {
                pending
            } else {
                Self::sweep_inflight_locked(&mut state);
                // WEAK, not strong: the map holds the future and the future reaches back
                // for the map, so an owning handle would close a reference cycle that keeps
                // this cache — and the client behind it — alive for the life of the process.
                state.loads += 1;
                let load_id = state.loads;
                let cache = Arc::downgrade(self);
                let owned = key.clone();
                let loading = load();
                let pending = async move {
                    // A loader that panics — a hook, a token provider — is turned into a
                    // failure rather than allowed to escape, so publication still runs and
                    // the key is still released. Without that the key would stay in flight
                    // and the shared future would be poisoned for everyone holding it.
                    let outcome = match AssertUnwindSafe(loading).catch_unwind().await {
                        Ok(result) => result.map_err(Arc::new),
                        Err(_) => Err(Arc::new(Error::new(
                            ErrorCode::ApiError,
                            "campfire discovery source panicked while loading",
                        ))),
                    };
                    // The cache outliving the load is the ordinary case; a load outliving
                    // the cache answers its waiters and caches nothing.
                    match cache.upgrade() {
                        Some(cache) => cache.publish(&owned, load_id, outcome),
                        None => outcome.map(|value| (Arc::new(value), Instant::now())),
                    }
                }
                .boxed()
                .shared();
                // `downgrade` answers `None` only for a future that has already completed,
                // which a freshly built one has not.
                if let Some(slot) = pending.downgrade() {
                    state
                        .inflight
                        .insert(key.clone(), Registration { id: load_id, slot });
                }
                pending
            }
        };
        match pending.await {
            // The load this call waited on is this call's load: its value is fresh, not
            // something that predated the call — and it is read off the load's own result,
            // so a sweep or the bound evicting the entry in the meantime cannot take it
            // from this waiter.
            Ok((value, fetched)) => Ok(Hit {
                value,
                fetched,
                cached: false,
            }),
            // EVERY failure here is the load's own, and is shared: N waiters never re-run
            // one failed load N times.
            //
            // Go re-loads for a waiter in one case — a load that failed under the LOADING
            // caller's own cancelled context — and that case does not exist here. Nothing
            // caller-scoped reaches into this load: it captures a cloned `AccountClient`,
            // and the operation deadline is created inside `send`, when the load runs. So a
            // `deadline_exceeded` out of a discovery read is the load's own deadline,
            // started when the load started, exactly as much "the load's own failure" as a
            // transport timeout is — and retrying it per waiter would be request
            // amplification wearing recovery's clothes.
            //
            // The condition Go's `callerDone` is really about — the starting caller going
            // away — is not a failure in Rust at all: dropping a future suspends the load
            // rather than killing it, and the next holder to poll the shared future resumes
            // it. There is nothing to recover from, which is why there is nothing here.
            //
            // The projection carries everything a caller classifies on — code, hint, status,
            // the flags — with the shared original chained as the cause.
            Err(error) => Err(project(&error)),
        }
    }

    /// The cached value for `key` when one is within the TTL, without loading. It lets a
    /// caller consult what a source already holds before deciding whether to pay for a
    /// fetch of it.
    pub(crate) fn peek(&self, key: &K) -> Option<Hit<V>> {
        let state = self.lock();
        let entry = state.entries.get(key)?;
        ((self.clock)().saturating_duration_since(entry.fetched) < self.ttl).then(|| Hit {
            value: Arc::clone(&entry.value),
            fetched: entry.fetched,
            cached: true,
        })
    }

    fn publish(&self, key: &K, load_id: u64, outcome: Result<V, Arc<Error>>) -> Loaded<V> {
        let mut state = self.lock();
        // Retire the registration only when it is THIS load's. Evicting by key alone would
        // let a publication from one load drop a newer load's registration while that load
        // was still running, and the single-flight guarantee with it — two concurrent
        // account-wide listings under one key, which for the listing is the bare account id
        // and so is process-wide. Rust makes this unreachable on its own (an abandoned
        // future never runs the rest of its body, so there is no publication without a
        // registration), but that is a property of the whole design; this makes it a
        // property of these three lines.
        if state
            .inflight
            .get(key)
            .is_some_and(|registered| registered.id == load_id)
        {
            state.inflight.remove(key);
        }
        // A failed load leaves the previous value in place: the next caller past the TTL
        // tries again rather than finding the key empty.
        let value = Arc::new(outcome?);
        let fetched = (self.clock)();
        Self::sweep_inflight_locked(&mut state);
        self.sweep_locked(&mut state, fetched);
        self.make_room_locked(&mut state, key);
        state.seq += 1;
        let seq = state.seq;
        state.entries.insert(
            key.clone(),
            Entry {
                value: Arc::clone(&value),
                fetched,
                seq,
            },
        );
        Ok((value, fetched))
    }

    /// Reaps the slots whose load is gone.
    ///
    /// The map holds loads weakly, so a load every caller dropped is already destroyed and
    /// its slot is an empty handle; a completed load's slot is empty too. Neither costs
    /// anything but a map entry, and the map's own bound counts published entries rather
    /// than in-flight ones — so without this a run of cancelled calls on distinct buckets
    /// would grow it without limit. A slot that still upgrades is a live load somebody is
    /// waiting on, and is left alone.
    fn sweep_inflight_locked(state: &mut CacheState<K, V>) {
        state
            .inflight
            .retain(|_, registered| registered.slot.upgrade().is_some());
    }

    /// Drops every entry past its TTL. It runs at each publication — the one moment the
    /// cache does work proportional to a miss anyway — so a long-lived client that has seen
    /// many buckets keeps a snapshot for at most a TTL past its last use plus the interval
    /// to the next load on any key, rather than for its lifetime.
    fn sweep_locked(&self, state: &mut CacheState<K, V>, now: Instant) {
        state
            .entries
            .retain(|_, entry| now.saturating_duration_since(entry.fetched) < self.ttl);
    }

    /// Evicts the oldest-fetched entries until the one about to be stored for `key` fits
    /// under `max_items` — oldest by fetch time, and by publication order among equals, so
    /// the choice is total rather than whatever map iteration happens to visit first.
    /// Oldest-first is also the right order: the entry nearest its TTL is the one least
    /// worth keeping.
    fn make_room_locked(&self, state: &mut CacheState<K, V>, key: &K) {
        if self.max_items == 0 || state.entries.contains_key(key) {
            return; // an overwrite takes no new room
        }
        while state.entries.len() >= self.max_items {
            let oldest = state
                .entries
                .iter()
                .min_by_key(|(_, entry)| (entry.fetched, entry.seq))
                .map(|(key, _)| key.clone());
            match oldest {
                Some(oldest) => {
                    state.entries.remove(&oldest);
                }
                None => break,
            }
        }
    }
}

/// The key a dock snapshot is cached under: one bucket, in one account.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct BucketKey {
    pub(crate) account_id: String,
    pub(crate) bucket_id: i64,
}

/// One consultation of a discovery source: the candidate ids it holds for the bucket, when
/// that snapshot was fetched, and whether it predated the call.
pub(crate) struct SourceRead {
    pub(crate) ids: Vec<i64>,
    pub(crate) fetched: Instant,
    pub(crate) cached: bool,
}

/// The two discovery sources.
pub(crate) struct CampfireIndex {
    docks: Arc<TtlCache<BucketKey, Vec<i64>>>,
    listings: Arc<TtlCache<String, HashMap<i64, Vec<i64>>>>,
}

impl std::fmt::Debug for CampfireIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CampfireIndex").finish_non_exhaustive()
    }
}

impl CampfireIndex {
    pub(crate) fn new() -> CampfireIndex {
        CampfireIndex::with_clock(Arc::new(Instant::now))
    }

    pub(crate) fn with_clock(clock: Clock) -> CampfireIndex {
        CampfireIndex {
            docks: Arc::new(TtlCache::new(
                Arc::clone(&clock),
                CAMPFIRE_INDEX_TTL,
                CAMPFIRE_INDEX_MIN_REFRESH,
                CAMPFIRE_INDEX_MAX_ITEMS,
            )),
            listings: Arc::new(TtlCache::new(
                clock,
                CAMPFIRE_INDEX_TTL,
                CAMPFIRE_INDEX_MIN_REFRESH,
                CAMPFIRE_INDEX_MAX_ITEMS,
            )),
        }
    }

    /// The bucket's own Campfire ids: a project's dock `chat` tools or, for a bucket that is
    /// not a project, the Ping's Campfire. A bucket that is neither (404 on both reads)
    /// has none; any other failure of either read is returned.
    pub(crate) async fn dock_campfires(
        &self,
        account: &AccountClient,
        bucket_id: i64,
        refresh: bool,
    ) -> Result<SourceRead, Error> {
        let key = BucketKey {
            account_id: account.account_id().to_string(),
            bucket_id,
        };
        let reader = account.clone();
        let hit = self
            .docks
            .get(&key, refresh, move || async move {
                match reader.projects().get(bucket_id).await {
                    Ok(project) => Ok(project
                        .dock
                        .unwrap_or_default()
                        .iter()
                        .filter(|item: &&DockItem| item.name == CHAT_DOCK_TOOL && item.id != 0)
                        .map(|item| item.id)
                        .collect()),
                    Err(error) if error.code() == ErrorCode::NotFound => {
                        match reader.pings().get(bucket_id).await {
                            Ok(ping) => Ok(campfire_id_from_room_url(&ping.room_url)
                                .into_iter()
                                .collect()),
                            Err(error) if error.code() == ErrorCode::NotFound => Ok(Vec::new()),
                            Err(error) => Err(error),
                        }
                    }
                    Err(error) => Err(error),
                }
            })
            .await?;
        Ok(SourceRead {
            ids: hit.value.as_ref().clone(),
            fetched: hit.fetched,
            cached: hit.cached,
        })
    }

    /// The Campfire ids the cached account-wide listing shows in a bucket, without
    /// fetching: `None` when the listing is not cached or has expired.
    pub(crate) fn cached_listed_campfires(
        &self,
        account_id: &str,
        bucket_id: i64,
    ) -> Option<SourceRead> {
        let hit = self.listings.peek(&account_id.to_string())?;
        Some(SourceRead {
            ids: hit.value.get(&bucket_id).cloned().unwrap_or_default(),
            fetched: hit.fetched,
            cached: true,
        })
    }

    /// The Campfire ids the account-wide listing shows in a bucket. A listing that
    /// overflows [`MAX_CAMPFIRE_LISTING`] is not cached, and is reported by the caller as
    /// incomplete discovery rather than as an answer.
    pub(crate) async fn listed_campfires(
        &self,
        account: &AccountClient,
        bucket_id: i64,
        refresh: bool,
    ) -> Result<SourceRead, Error> {
        let key = account.account_id().to_string();
        let reader = account.clone();
        let hit = self
            .listings
            .get(&key, refresh, move || async move {
                let first = reader
                    .campfires()
                    .list(&ListCampfiresParams::default())
                    .await?;
                let listed = reader
                    .collect_all(first, Some(MAX_CAMPFIRE_LISTING))
                    .await?;
                if listed.meta.truncated {
                    return Err(listing_overflow());
                }
                let mut by_bucket: HashMap<i64, Vec<i64>> = HashMap::new();
                for campfire in listed.items {
                    if campfire.bucket.id == 0 {
                        continue;
                    }
                    by_bucket
                        .entry(campfire.bucket.id)
                        .or_default()
                        .push(campfire.id);
                }
                Ok(by_bucket)
            })
            .await?;
        Ok(SourceRead {
            ids: hit.value.get(&bucket_id).cloned().unwrap_or_default(),
            fetched: hit.fetched,
            cached: hit.cached,
        })
    }
}

/// The load error for a listing past its cap, which the caller turns into an incomplete
/// discovery verdict. SPEC §6's taxonomy has no member for "the SDK's own bound was
/// reached", so the identity rides as a cause.
///
/// It is a private TYPE on purpose. A marker in any string-valued member would be forgeable
/// off the wire, and `hint` is both the tempting place and the worst one: a token endpoint
/// fills it from its own `error_description` (see `oauth::token`), and a 401 inside the
/// listing load triggers a refresh through exactly that path — so an authorization server
/// that named this string could have its own failure reported as a campfire-discovery
/// verdict, swallowing an auth error. Nothing off the wire can forge a Rust type.
#[derive(Debug)]
struct ListingOverflow;

impl std::fmt::Display for ListingOverflow {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "campfire listing exceeds {MAX_CAMPFIRE_LISTING}")
    }
}

impl std::error::Error for ListingOverflow {}

/// One failed load, projected for each caller waiting on it. `Error` is not `Clone` — its
/// cause is a boxed trait object — so the record is duplicated whole and the shared original
/// is chained back on as the cause. Nothing a caller classifies on is dropped on the way:
/// the same failure reaches the caller that started the load and the callers that waited on
/// it, timeout and deadline flags included.
fn project(error: &Arc<Error>) -> Error {
    error.duplicate().with_source(Arc::clone(error))
}

fn listing_overflow() -> Error {
    Error::new(
        ErrorCode::ApiError,
        "campfire listing is too large to cache",
    )
    .with_hint(ListingOverflow.to_string())
    .with_source(ListingOverflow)
}

/// Whether an error is the listing-overflow marker, through however many wrappers the cache
/// projected it into.
pub(crate) fn is_listing_overflow(error: &Error) -> bool {
    error.find_source::<ListingOverflow>().is_some()
}

/// A clock a test moves by hand. The TTL and the refresh floor are minutes and tens of
/// seconds wide, so no test can cross them by waiting; every test that turns on an entry's
/// age drives one of these instead. Shared with [`crate::services::recordings`], which
/// needs the floor crossed to reach the refresh path at all.
#[cfg(test)]
pub(crate) struct TestClock {
    base: Instant,
    offset: std::sync::atomic::AtomicU64,
}

#[cfg(test)]
impl TestClock {
    pub(crate) fn new() -> Arc<TestClock> {
        Arc::new(TestClock {
            base: Instant::now(),
            offset: std::sync::atomic::AtomicU64::new(0),
        })
    }

    pub(crate) fn clock(self: &Arc<Self>) -> Clock {
        let clock = Arc::clone(self);
        Arc::new(move || {
            clock.base
                + Duration::from_millis(clock.offset.load(std::sync::atomic::Ordering::SeqCst))
        })
    }

    pub(crate) fn advance(&self, by: Duration) {
        let millis = u64::try_from(by.as_millis()).unwrap_or(u64::MAX);
        self.offset
            .fetch_add(millis, std::sync::atomic::Ordering::SeqCst);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    fn cache<V: Send + Sync + 'static>(
        clock: &Arc<TestClock>,
        max_items: usize,
    ) -> Arc<TtlCache<i64, V>> {
        Arc::new(TtlCache::new(
            clock.clock(),
            CAMPFIRE_INDEX_TTL,
            CAMPFIRE_INDEX_MIN_REFRESH,
            max_items,
        ))
    }

    #[tokio::test]
    async fn a_value_inside_the_ttl_is_served_without_loading() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        for _ in 0..3 {
            let counter = Arc::clone(&loads);
            let hit = cache
                .get(&1, false, move || async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                    Ok(7)
                })
                .await
                .unwrap();
            assert_eq!(*hit.value, 7);
        }
        assert_eq!(loads.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn a_refresh_is_declined_under_the_floor_and_honoured_past_it() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        let load = || {
            let counter = Arc::clone(&loads);
            move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                Ok(1)
            }
        };
        cache.get(&1, false, load()).await.unwrap();
        clock.advance(Duration::from_secs(5));
        let under = cache.get(&1, true, load()).await.unwrap();
        assert!(under.cached, "the floor declines the refresh");
        clock.advance(CAMPFIRE_INDEX_MIN_REFRESH);
        let past = cache.get(&1, true, load()).await.unwrap();
        assert!(!past.cached, "past the floor the source is re-read");
        assert_eq!(loads.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn a_value_past_the_ttl_is_loaded_again() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        cache.get(&1, false, || async { Ok(1) }).await.unwrap();
        clock.advance(CAMPFIRE_INDEX_TTL);
        assert!(cache.peek(&1).is_none());
        let hit = cache.get(&1, false, || async { Ok(2) }).await.unwrap();
        assert_eq!(*hit.value, 2);
    }

    #[tokio::test]
    async fn a_failed_load_leaves_the_previous_value_in_place() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        cache.get(&1, false, || async { Ok(1) }).await.unwrap();
        clock.advance(CAMPFIRE_INDEX_MIN_REFRESH);
        let failed = cache
            .get(&1, true, || async { Err(Error::usage("nope")) })
            .await;
        assert!(failed.is_err());
        let still_there = cache.peek(&1).expect("the old snapshot survives");
        assert_eq!(*still_there.value, 1);
    }

    #[tokio::test]
    async fn the_bound_evicts_the_oldest_fetched_entry_first() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 2);
        cache.get(&1, false, || async { Ok(1) }).await.unwrap();
        clock.advance(Duration::from_secs(1));
        cache.get(&2, false, || async { Ok(2) }).await.unwrap();
        clock.advance(Duration::from_secs(1));
        cache.get(&3, false, || async { Ok(3) }).await.unwrap();
        assert!(cache.peek(&1).is_none(), "the oldest went first");
        assert!(cache.peek(&2).is_some());
        assert!(cache.peek(&3).is_some());
    }

    #[tokio::test]
    async fn expired_entries_are_swept_at_the_next_publication() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        cache.get(&1, false, || async { Ok(1) }).await.unwrap();
        clock.advance(CAMPFIRE_INDEX_TTL);
        cache.get(&2, false, || async { Ok(2) }).await.unwrap();
        let state = cache.lock();
        assert_eq!(state.entries.len(), 1, "the expired key was swept");
        assert!(state.entries.contains_key(&2));
    }

    #[tokio::test]
    async fn concurrent_callers_share_one_load() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let first = {
            let counter = Arc::clone(&loads);
            cache.get(&1, false, move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                let _ = held.await;
                Ok(9)
            })
        };
        let second = {
            let counter = Arc::clone(&loads);
            cache.get(&1, false, move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                Ok(0)
            })
        };
        // `join!` polls in order: the first call takes the key and parks on the gate, the
        // second finds the load in flight and parks on it, and only then is it released.
        let releaser = async {
            tokio::task::yield_now().await;
            let _ = release.send(());
        };
        let (first, second, ()) = futures_util::join!(first, second, releaser);
        assert_eq!(*first.unwrap().value, 9);
        let second = second.unwrap();
        assert_eq!(*second.value, 9, "the waiter shares the loaded value");
        assert!(
            !second.cached,
            "and reads it as fresh, not as a prior snapshot"
        );
        assert_eq!(loads.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn one_failed_load_is_one_failure_shared_by_every_waiter() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let first = {
            let counter = Arc::clone(&loads);
            cache.get(&1, false, move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                let _ = held.await;
                Err(Error::new(ErrorCode::Forbidden, "no").with_status(403))
            })
        };
        let second = {
            let counter = Arc::clone(&loads);
            cache.get(&1, false, move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                Ok(0)
            })
        };
        let releaser = async {
            tokio::task::yield_now().await;
            let _ = release.send(());
        };
        let (first, second, ()) = futures_util::join!(first, second, releaser);
        for outcome in [first, second] {
            let error = outcome.err().expect("the shared load failed");
            assert_eq!(error.code(), ErrorCode::Forbidden);
            assert_eq!(error.http_status(), Some(403));
        }
        assert_eq!(loads.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn a_load_every_caller_dropped_leaves_no_slot_behind() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let (_release, held) = tokio::sync::oneshot::channel::<()>();
        // Polled once — long enough to take the key — then dropped, as an operation
        // deadline shorter than the listing's round trip drops it.
        let abandoned = cache.get(&1, false, move || async move {
            let _ = held.await;
            Ok(1)
        });
        assert!(abandoned.now_or_never().is_none());
        assert_eq!(
            cache.lock().inflight.len(),
            1,
            "the map still holds the slot"
        );

        // The next load past the same map sweeps it: the bound counts published entries,
        // so an abandoned slot that nobody will ever finish must not accumulate.
        cache.get(&2, false, || async { Ok(2) }).await.unwrap();
        let state = cache.lock();
        assert!(!state.inflight.contains_key(&1));
        assert!(state.inflight.is_empty());
    }

    #[tokio::test]
    async fn a_live_load_is_not_swept_out_from_under_its_waiter() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let waiting = cache.get(&1, false, move || async move {
            let _ = held.await;
            Ok(1)
        });
        let other = cache.get(&2, false, || async { Ok(2) });
        let releaser = async {
            tokio::task::yield_now().await;
            let _ = release.send(());
        };
        let (waiting, other, ()) = futures_util::join!(waiting, other, releaser);
        assert_eq!(*waiting.unwrap().value, 1);
        assert_eq!(*other.unwrap().value, 2);
    }

    #[tokio::test]
    async fn a_shared_failure_reaches_every_caller_with_nothing_classifiable_lost() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let first = cache.get(&1, false, move || async move {
            let _ = held.await;
            Err(Error::network_timeout(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "the listing stalled",
            ))
            .with_status(504)
            .with_request_id("req-1"))
        });
        let second = cache.get(&1, false, || async { Ok(0) });
        let releaser = async {
            tokio::task::yield_now().await;
            let _ = release.send(());
        };
        let (first, second, ()) = futures_util::join!(first, second, releaser);
        for outcome in [first, second] {
            let error = outcome.err().expect("the shared load failed");
            // A timeout that reaches a second caller without its timeout identity is a
            // timeout that caller would handle differently (SPEC section 16).
            assert!(error.is_timeout(), "{error}");
            assert!(error.is_retryable());
            assert_eq!(error.code(), ErrorCode::Network);
            assert_eq!(error.http_status(), Some(504));
            assert_eq!(error.request_id(), Some("req-1"));
            assert!(error.hint().is_some());
        }
    }

    #[tokio::test]
    async fn a_deadline_that_ended_the_load_is_shared_and_never_re_run_per_waiter() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        // Nothing caller-scoped reaches into a load here: it captures a cloned client, and
        // the operation deadline is created inside `send`, when the load runs. So a
        // deadline that ends a discovery read is the LOAD's, exactly as much its own
        // failure as a transport timeout — and re-running it per waiter would be request
        // amplification, not recovery.
        let starter = {
            let counter = Arc::clone(&loads);
            cache.get(&1, false, move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                let _ = held.await;
                Err(Error::deadline_exceeded(Duration::from_millis(1)))
            })
        };
        let waiters: Vec<_> = (0..3)
            .map(|_| {
                let counter = Arc::clone(&loads);
                cache.get(&1, false, move || async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                    Ok(7)
                })
            })
            .collect();
        let releaser = async {
            tokio::task::yield_now().await;
            let _ = release.send(());
        };
        let (starter, waiters, ()) =
            futures_util::join!(starter, futures_util::future::join_all(waiters), releaser);
        for outcome in std::iter::once(starter).chain(waiters) {
            let error = outcome.err().expect("the shared load failed");
            assert!(error.is_deadline_exceeded(), "{error}");
        }
        assert_eq!(
            loads.load(Ordering::SeqCst),
            1,
            "one load, one failure, four callers"
        );
    }

    #[tokio::test]
    async fn a_transport_timeout_is_shared_too_and_never_re_run_per_waiter() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let starter = {
            let counter = Arc::clone(&loads);
            cache.get(&1, false, move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                let _ = held.await;
                Err(Error::network_timeout(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "stalled",
                )))
            })
        };
        let waiter = {
            let counter = Arc::clone(&loads);
            cache.get(&1, false, move || async move {
                counter.fetch_add(1, Ordering::SeqCst);
                Ok(7)
            })
        };
        let releaser = async {
            tokio::task::yield_now().await;
            let _ = release.send(());
        };
        let (starter, waiter, ()) = futures_util::join!(starter, waiter, releaser);
        assert!(starter.err().expect("the load timed out").is_timeout());
        assert!(waiter.err().expect("the waiter shares it").is_timeout());
        assert_eq!(loads.load(Ordering::SeqCst), 1, "one load, one failure");
    }

    #[tokio::test]
    async fn a_load_that_panics_releases_its_key_and_the_next_caller_is_served() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        // Expect a panic backtrace on stderr: it is caught, and that is the point.
        let panicked = cache
            .get(&1, false, || async { panic!("a hook exploded") })
            .await;
        let error = panicked
            .err()
            .expect("a panicking loader is a failure, not a hang");
        assert_eq!(error.code(), ErrorCode::ApiError);
        assert!(
            cache.lock().inflight.is_empty(),
            "publication still ran, so the key is free"
        );
        // The next caller is served rather than parked behind a dead loader forever.
        let after = cache.get(&1, false, || async { Ok(5) }).await.unwrap();
        assert_eq!(*after.value, 5);
    }

    #[tokio::test]
    async fn a_load_every_caller_abandoned_is_dropped_and_the_next_caller_is_served() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let counter = Arc::clone(&loads);
        // Polled once — long enough to take the key and start the load — then dropped.
        let abandoned = cache.get(&1, false, move || async move {
            counter.fetch_add(1, Ordering::SeqCst);
            let _ = held.await;
            Ok(11)
        });
        assert!(abandoned.now_or_never().is_none());
        let _ = release.send(());

        // The map holds loads weakly, so the last caller leaving takes the load — and the
        // client it captured — with it. This is the case Go's deferred release exists for,
        // and the answers differ: Go's waiters would park forever on a channel only the
        // dead loader could close, while here the slot is simply empty and the next caller
        // starts a fresh load rather than waiting on anything.
        assert!(
            cache
                .lock()
                .inflight
                .get(&1)
                .and_then(|registered| registered.slot.upgrade())
                .is_none(),
            "the abandoned load was dropped, not left running"
        );
        let later = cache.get(&1, false, || async { Ok(99) }).await.unwrap();
        assert_eq!(*later.value, 99);
        assert_eq!(
            loads.load(Ordering::SeqCst),
            1,
            "the abandoned load never finished"
        );
        assert!(cache.lock().inflight.is_empty());
    }

    #[tokio::test]
    async fn a_publication_retires_only_its_own_registration() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let mut live = Box::pin(cache.get(&1, false, move || async move {
            let _ = held.await;
            Ok(7)
        }));
        // One poll registers the load and parks it.
        assert!(futures_util::poll!(live.as_mut()).is_pending());
        let registered = cache.lock().inflight.get(&1).map(|entry| entry.id);
        assert!(registered.is_some(), "the live load is registered");

        // A publication carrying somebody else's identity must not retire it. Evicting by
        // key alone would drop this load's registration while it was still running, and the
        // next caller would start a second load under the same key.
        //
        // The identity used is one no load owns rather than a second live load's, because
        // two live loads under one key are unreachable by construction: a caller only
        // creates a load when `upgrade()` answers `None`, and a load with any surviving
        // handle always upgrades and is joined instead. What the guard has to reject is
        // therefore exactly this — a publication whose identity is not the registered one.
        let stale = cache.publish(&1, registered.unwrap_or_default() + 1, Ok(99));
        assert!(stale.is_ok());
        assert_eq!(
            cache.lock().inflight.get(&1).map(|entry| entry.id),
            registered,
            "the live load kept its slot"
        );

        // And the live load still finishes, still alone, and its value is what the caller
        // waiting on it receives.
        let _ = release.send(());
        assert_eq!(*live.await.unwrap().value, 7);
        assert!(
            cache.lock().inflight.is_empty(),
            "its own publication did retire it"
        );
    }

    #[tokio::test]
    async fn a_caller_still_waiting_keeps_the_load_alive_when_its_starter_leaves() {
        let clock = TestClock::new();
        let cache = cache::<i64>(&clock, 16);
        let loads = Arc::new(AtomicU64::new(0));
        let (release, held) = tokio::sync::oneshot::channel::<()>();
        let counter = Arc::clone(&loads);
        let mut starter = Box::pin(cache.get(&1, false, move || async move {
            counter.fetch_add(1, Ordering::SeqCst);
            let _ = held.await;
            Ok(11)
        }));
        assert!(futures_util::poll!(starter.as_mut()).is_pending());
        let mut second = Box::pin(cache.get(&1, false, || async { Ok(99) }));
        assert!(futures_util::poll!(second.as_mut()).is_pending());
        drop(starter); // the caller that began the load goes away

        // Weak in the map does not mean the load dies with its starter: the other caller
        // owns a handle, so the load survives and is driven to the starter's value.
        let releaser = async {
            tokio::task::yield_now().await;
            let _ = release.send(());
        };
        let (joined, ()) = futures_util::join!(second, releaser);
        assert_eq!(*joined.unwrap().value, 11);
        assert_eq!(loads.load(Ordering::SeqCst), 1, "no second load");
    }

    #[test]
    fn a_room_url_names_the_campfire_it_ends_in() {
        for (url, id) in [
            (
                "https://3.basecampapi.com/195539477/buckets/2085958600/chats/1069479600.json",
                Some(1_069_479_600),
            ),
            ("/buckets/7/chats/42", Some(42)),
            ("/chats/42.json", Some(42)),
            ("chats/42", Some(42)),
            ("https://x.test/9/buckets/7/chats/42.json?a=1#b", Some(42)),
            ("https://x.test/9/buckets/7/chats/42/lines.json", None),
            ("https://x.test/9/buckets/7/chats/42/lines/5.json", None),
            ("https://x.test/9/buckets/7/todos/42.json", None),
            ("/buckets/7/chats/", None),
            ("/buckets/7/chats/abc.json", None),
            ("/buckets/7/chats/0.json", None),
            ("/buckets/7/chats/99999999999999999999.json", None),
            ("/buckets/7/mychats/42.json", None),
            ("", None),
        ] {
            assert_eq!(campfire_id_from_room_url(url), id, "{url:?}");
        }
    }

    #[test]
    fn the_listing_overflow_marker_survives_the_cache_projection() {
        let overflow = Arc::new(listing_overflow());
        assert!(is_listing_overflow(&overflow));
        assert!(is_listing_overflow(&project(&overflow)));
        assert!(!is_listing_overflow(&Error::usage("something else")));
    }

    #[test]
    fn the_marker_cannot_be_forged_from_anything_the_wire_carries() {
        // A token endpoint fills `hint` from its own error_description, and a refresh runs
        // inside the listing load. A server that names the marker text must not be able to
        // have its own failure reported as a discovery verdict.
        let forged = Error::new(ErrorCode::AuthRequired, "invalid_grant")
            .with_hint(ListingOverflow.to_string());
        assert!(!is_listing_overflow(&forged));
        assert!(!is_listing_overflow(&project(&Arc::new(forged))));
    }
}