Skip to main content

basecamp_sdk/services/
recordings.rs

1//! Recordings: the generated wire methods plus
2//! [`RecordingsService::summarize`](RecordingsService::summarize), the SPEC §18 composite
3//! that resolves an event pointer into a compact projection of the recording it names.
4//!
5//! [`RecordingSummary`] exists for consumers that must decide something about a recording
6//! without paying for its full payload: an agent connector's admission step, an MCP tool
7//! answering "what is this?".
8//!
9//! The SDK has no untyped recording read (BC3 has no such route), so the type is the
10//! routing key: `comment.created` reads a comment, `card.created` reads a card, and so on —
11//! one typed read per type. Chat lines are the exception, because their read needs the
12//! Campfire id and the pointer does not carry it; `summarize` discovers the Campfire first
13//! (see [`campfire_index`](crate::services::campfire_index)).
14//!
15//! This is hand-written composition over the generated services. It makes no wire request
16//! of its own, and it mints no operation identity: hooks see the constituent reads under
17//! their own names (SPEC §18 rule 3).
18
19pub use crate::generated::services::recordings::{ListRecordingsParams, RecordingsService};
20
21use std::fmt;
22
23use serde::{Deserialize, Serialize};
24
25use crate::client::AccountClient;
26use crate::error::{Error, ErrorCode};
27use crate::generated::types::{
28    CampfireLine, Person, RecordingBucket, RecordingParent, TodoBucket, TodoParent,
29};
30use crate::mentions::mentioned_person_ids;
31use crate::services::campfire_index::{MAX_CAMPFIRE_CANDIDATES, SourceRead, is_listing_overflow};
32use crate::types::DateTime;
33
34/// A pointer at one recording, the way an account event feed row carries it.
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct RecordingRef {
37    /// The project the recording lives in. Required: it scopes the Campfire discovery for
38    /// chat lines, and the read is checked against it so a pointer from one project can
39    /// never resolve to a recording in another.
40    pub bucket_id: i64,
41
42    /// The recording's id.
43    pub recording_id: i64,
44
45    /// The account event feed type that named the recording — `comment.created`,
46    /// `card.assignment_changed`, `chat.line.created`. The segment before the action names
47    /// the recording type. Used when `recording_type` is absent.
48    pub event_type: Option<String>,
49
50    /// The recording's own type as BC3 spells it — `Comment`, `Kanban::Card`,
51    /// `Chat::Lines::Text`. When set it takes precedence over `event_type`, being the more
52    /// exact of the two.
53    pub recording_type: Option<String>,
54}
55
56impl RecordingRef {
57    /// A pointer from an event feed type — `comment.created` and friends.
58    pub fn from_event(bucket_id: i64, recording_id: i64, event_type: impl Into<String>) -> Self {
59        RecordingRef {
60            bucket_id,
61            recording_id,
62            event_type: Some(event_type.into()),
63            recording_type: None,
64        }
65    }
66
67    /// A pointer from a BC3 recording type — `Comment`, `Kanban::Card` and friends.
68    pub fn from_recording_type(
69        bucket_id: i64,
70        recording_id: i64,
71        recording_type: impl Into<String>,
72    ) -> Self {
73        RecordingRef {
74            bucket_id,
75            recording_id,
76            event_type: None,
77            recording_type: Some(recording_type.into()),
78        }
79    }
80
81    /// The routing key the pointer is read by: the recording type when it carries one, the
82    /// event type otherwise.
83    fn key(&self) -> &str {
84        let recording_type = self.recording_type.as_deref().unwrap_or_default().trim();
85        if recording_type.is_empty() {
86            self.event_type.as_deref().unwrap_or_default().trim()
87        } else {
88            recording_type
89        }
90    }
91}
92
93/// The projection [`RecordingsService::summarize`] returns. Fields a type does not have are
94/// empty: a comment has no assignees, a vault no content.
95#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
96#[non_exhaustive]
97pub struct RecordingSummary {
98    /// The recording's id.
99    pub id: i64,
100    /// `active`, `archived`, `trashed`.
101    pub status: String,
102    /// The recording type as BC3 spells it (`Comment`, `Kanban::Card`).
103    pub r#type: String,
104    /// The recording's title.
105    pub title: String,
106    /// Where a person reads it in Basecamp.
107    pub app_url: String,
108    /// The recording this one hangs off — the commented recording for a comment, the
109    /// Campfire for a chat line, the column for a card.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub parent: Option<RecordingParent>,
112    /// The project the recording lives in.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub bucket: Option<RecordingBucket>,
115    /// Who created it.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub creator: Option<Person>,
118    /// Set for the assignable types (to-dos, cards, card steps). Always serialized, so a
119    /// server-sent `[]` reaches a JSON consumer as `[]` rather than a missing key; a type
120    /// with no assignees serializes `[]` too, since a `Vec` can't tell absent from empty.
121    #[serde(default)]
122    pub assignees: Vec<Person>,
123    /// The people [`content`](RecordingSummary::content) mentions, per
124    /// [`mentioned_person_ids`]. Always serialized, so a JSON consumer reads `[]` rather
125    /// than a missing key.
126    pub mentioned_person_ids: Vec<i64>,
127    /// The recording's rich text, in full: the comment body, the message body, a to-do's
128    /// description, a card's content, the chat line.
129    pub content: String,
130    /// When it last changed.
131    pub updated_at: DateTime,
132    /// The Campfire a chat line was found under — the reply destination for a chat trigger.
133    /// Absent for every other type.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub campfire_id: Option<i64>,
136}
137
138/// A chat line that was found under none of the Campfires the caller can currently see.
139#[derive(Debug, Clone, PartialEq, Eq)]
140#[non_exhaustive]
141pub struct UnresolvedRecording {
142    /// The bucket the pointer named.
143    pub bucket_id: i64,
144    /// The line the pointer named.
145    pub recording_id: i64,
146    /// The candidates tried, in order; empty when the bucket has no visible Campfire at all.
147    pub campfire_ids: Vec<i64>,
148    /// Whether the cached discovery sources were re-read before concluding. `false` when
149    /// every source had been read within the last
150    /// [`CAMPFIRE_INDEX_MIN_REFRESH`](crate::services::campfire_index::CAMPFIRE_INDEX_MIN_REFRESH),
151    /// so a Campfire created in that window was not seen: the conclusion stands on data up
152    /// to that old, and a retry after the floor sees the current sources.
153    pub refreshed: bool,
154    /// Candidates from the cache that the refreshed sources no longer list — Campfires the
155    /// caller could see when the cache filled and cannot now. Set only when `refreshed`.
156    pub stale_campfire_ids: Vec<i64>,
157}
158
159/// Why [`RecordingsService::summarize`] could not answer, when the reason is the
160/// composite's own rather than a read's.
161///
162/// It is chained as the cause of the [`Error`] the call returns, so a consumer matches on
163/// the identity rather than parsing a message: `RecordingSummaryError::of(&error)`. Every
164/// other failure — a 403 on a candidate, a 404 on the typed read, a transport error — is
165/// returned as that read's own [`Error`], with no cause of this kind.
166#[derive(Debug, Clone, PartialEq, Eq)]
167#[non_exhaustive]
168pub enum RecordingSummaryError {
169    /// The event type names no recording type — `boost.created`, whose recording is the
170    /// boost's target and whose type the feed row does not carry. A consumer resolves those
171    /// from its own record of what it posted, not through `summarize`.
172    NoRecordingType {
173        /// The routing key that was refused.
174        key: String,
175    },
176
177    /// Neither the event type nor the recording type names a type in the routing table.
178    UnknownRecordingType {
179        /// The routing key that was refused.
180        key: String,
181    },
182
183    /// A chat line was found under none of the Campfires the caller can currently see.
184    ///
185    /// It is distinct from a failed read (any non-404 answer is returned as itself) and
186    /// from discovery that could not finish ([`Self::CampfireDiscoveryIncomplete`]): every
187    /// candidate answered 404. It is *not* distinct from lost visibility — BC3 answers 404
188    /// for a Campfire the caller may not see, too — so a consumer marks the record blocked
189    /// and retries on its own schedule; see
190    /// [`UnresolvedRecording::stale_campfire_ids`].
191    Unresolved(UnresolvedRecording),
192
193    /// Discovery could not be carried to a conclusion — the Campfire listing overflowed
194    /// [`MAX_CAMPFIRE_LISTING`](crate::services::campfire_index::MAX_CAMPFIRE_LISTING), or
195    /// a bucket has more visible Campfires than
196    /// [`MAX_CAMPFIRE_CANDIDATES`]. Distinct from [`Self::Unresolved`]: candidates were
197    /// left unsearched, so nothing can be reported absent.
198    CampfireDiscoveryIncomplete {
199        /// The bucket the pointer named.
200        bucket_id: i64,
201        /// The line the pointer named.
202        recording_id: i64,
203        /// Why discovery stopped short.
204        reason: String,
205    },
206
207    /// The recording the read returned lives in a different bucket from the one the pointer
208    /// named.
209    BucketMismatch {
210        /// The bucket the pointer named.
211        bucket_id: i64,
212        /// The recording the pointer named.
213        recording_id: i64,
214        /// The bucket the read returned.
215        found_in: i64,
216    },
217}
218
219impl fmt::Display for RecordingSummaryError {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        match self {
222            RecordingSummaryError::NoRecordingType { key } => {
223                write!(f, "event type names no recording type: {key:?}")
224            }
225            RecordingSummaryError::UnknownRecordingType { key } => {
226                write!(f, "no typed read for recording type: {key:?}")
227            }
228            RecordingSummaryError::Unresolved(unresolved) => write!(
229                f,
230                "chat line found under no visible campfire: line {} in bucket {} (tried {} campfires)",
231                unresolved.recording_id,
232                unresolved.bucket_id,
233                unresolved.campfire_ids.len()
234            ),
235            RecordingSummaryError::CampfireDiscoveryIncomplete {
236                bucket_id,
237                recording_id,
238                reason,
239            } => write!(
240                f,
241                "campfire discovery incomplete: line {recording_id} in bucket {bucket_id}: {reason}"
242            ),
243            RecordingSummaryError::BucketMismatch {
244                bucket_id,
245                recording_id,
246                found_in,
247            } => write!(
248                f,
249                "recording is not in the requested bucket: recording {recording_id} is in bucket {found_in}, not {bucket_id}"
250            ),
251        }
252    }
253}
254
255impl std::error::Error for RecordingSummaryError {}
256
257impl RecordingSummaryError {
258    /// The composite's own reason for an [`Error`], when it has one. A read that failed on
259    /// its own terms — a 403, a 404, a transport error — answers `None`, and is classified
260    /// by [`Error::code`] like any other SDK failure.
261    ///
262    /// The whole cause chain is searched, not just its first link, so the verdict survives
263    /// being re-wrapped on its way out — which is what Go's `errors.Is` gives the reference
264    /// implementation, and what makes this a contract a consumer can rely on rather than one
265    /// a single [`Error::with_source`] elsewhere would quietly break.
266    pub fn of(error: &Error) -> Option<&RecordingSummaryError> {
267        error.find_source::<RecordingSummaryError>()
268    }
269
270    /// The taxonomy member this reason is reported under.
271    ///
272    /// Routing refusals are `usage`: the pointer names no read, and nothing was sent.
273    /// "Unresolved" is `not_found`: every visible candidate answered 404, so the recording
274    /// the pointer names is not where it was looked for.
275    ///
276    /// A bucket mismatch is `usage`, settled across every port on [card 41] after this port
277    /// shipped `not_found` where Python, Ruby, Kotlin and TypeScript shipped `usage` — exit
278    /// 2 against exit 1 for the same condition. `not_found` says the recording is not there,
279    /// which is false: the read FOUND it, in another bucket, and returned it, so nothing is
280    /// absent. What failed is the caller's pointer, which named a bucket the recording is
281    /// not in, and that is what `usage` means everywhere else in the taxonomy. The majority
282    /// agreed, but the argument is what settles it.
283    ///
284    /// [card 41]: https://app.basecamp.com/2914079/buckets/48699913/card_tables/cards/10308966794
285    ///
286    /// Incomplete discovery is `usage`, settled across every port on [card 40] after the
287    /// merged ports shipped two different answers — this one said `api_error`, Kotlin said
288    /// `usage`, and a caller got exit 7 from one SDK and exit 1 from another for the same
289    /// condition. `usage` is one of only THREE coarse codes no HTTP response can produce:
290    /// [`ErrorCode::from_status`] yields `auth_required`, `forbidden`, `not_found`,
291    /// `rate_limit`, `validation`, `limit_exceeded` and `api_error`, and `network` and
292    /// `ambiguous` are equally unreachable from a status. `usage` is the one of those three
293    /// that also describes a call the SDK declined to complete, which is why it and not the
294    /// other two. A verdict the composite reached on its own therefore can never be read
295    /// back as a constituent read's own answer. It is explicitly not `not_found`, because nothing left unsearched
296    /// may be reported absent. Retryability is a separate field and is unchanged: the
297    /// [`Error`] built from this carries `retryable = false`, because both reasons are
298    /// deterministic for the same account state and a retry loop would re-run the identical
299    /// search forever.
300    ///
301    /// [card 40]: https://app.basecamp.com/2914079/buckets/48699913/card_tables/cards/10308122086
302    fn code(&self) -> ErrorCode {
303        match self {
304            RecordingSummaryError::NoRecordingType { .. }
305            | RecordingSummaryError::UnknownRecordingType { .. }
306            | RecordingSummaryError::BucketMismatch { .. }
307            | RecordingSummaryError::CampfireDiscoveryIncomplete { .. } => ErrorCode::Usage,
308            RecordingSummaryError::Unresolved(_) => ErrorCode::NotFound,
309        }
310    }
311}
312
313impl From<RecordingSummaryError> for Error {
314    fn from(reason: RecordingSummaryError) -> Error {
315        Error::new(reason.code(), reason.to_string()).with_source(reason)
316    }
317}
318
319/// Which typed read serves a [`RecordingRef`].
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321enum Kind {
322    Comment,
323    Message,
324    Todo,
325    Card,
326    ChatLine,
327    Document,
328    Upload,
329    ScheduleEntry,
330    Question,
331    QuestionAnswer,
332    Todolist,
333    Vault,
334    Forward,
335    ClientApproval,
336    ClientCorrespondence,
337    GoogleDocument,
338    CloudFile,
339    CardStep,
340    Questionnaire,
341    Schedule,
342    Todoset,
343    MessageBoard,
344    CardTable,
345    CardColumn,
346    Inbox,
347    Campfire,
348}
349
350/// The subject of an account event feed type — everything before its final `.` — and the
351/// read it names. This is the feed's catalog (bc3 `Event::EventType`) minus `boost`, which
352/// names no recording type and is refused explicitly rather than left to fall through as
353/// unknown.
354const EVENT_SUBJECTS: &[(&str, Kind)] = &[
355    ("comment", Kind::Comment),
356    ("message", Kind::Message),
357    ("todo", Kind::Todo),
358    ("card", Kind::Card),
359    ("chat.line", Kind::ChatLine),
360];
361
362/// BC3's recording type strings and the read each names. It is the routing contract, and it
363/// is a DELIBERATE set, not an exhaustive one: the recording types the account event feed's
364/// trigger matrix names (comment, message, to-do, card, chat line), plus the content and
365/// tool recordings a consumer reasoning about those is likely to hold an id for. Chat lines
366/// are matched by prefix (`Chat::Lines::Text`, `::RichText`, `::Code`, `::Upload`,
367/// `::Integration` all read through the same route); everything else exactly.
368///
369/// A type outside this set is [`RecordingSummaryError::UnknownRecordingType`] by design,
370/// whether or not the SDK has an id-only read for it — `Timesheet::Entry` and
371/// `Gauge::Needle` do, and are not routed; `Client::Reply` and `Forward::Reply` cannot be,
372/// since their reads need a parent id the pointer does not carry. Widening the set is a
373/// product decision, not a gap: add the type here, its projection in `read_summary`, a
374/// routing row in this module's tests, and a case in
375/// `conformance/tests/recording_summary.json`, the fixture every SDK implements.
376const RECORDING_TYPES: &[(&str, Kind)] = &[
377    ("Chat::Transcript", Kind::Campfire),
378    ("Client::Approval", Kind::ClientApproval),
379    ("Client::Correspondence", Kind::ClientCorrespondence),
380    ("CloudFile", Kind::CloudFile),
381    ("Comment", Kind::Comment),
382    ("Document", Kind::Document),
383    ("GoogleDocument", Kind::GoogleDocument),
384    ("Inbox", Kind::Inbox),
385    ("Inbox::Forward", Kind::Forward),
386    ("Kanban::Board", Kind::CardTable),
387    ("Kanban::Card", Kind::Card),
388    ("Kanban::Column", Kind::CardColumn),
389    ("Kanban::Step", Kind::CardStep),
390    ("Message", Kind::Message),
391    ("Message::Board", Kind::MessageBoard),
392    ("Question", Kind::Question),
393    ("Question::Answer", Kind::QuestionAnswer),
394    ("Questionnaire", Kind::Questionnaire),
395    ("Schedule", Kind::Schedule),
396    ("Schedule::Entry", Kind::ScheduleEntry),
397    ("Todo", Kind::Todo),
398    ("Todolist", Kind::Todolist),
399    ("Todoset", Kind::Todoset),
400    ("Upload", Kind::Upload),
401    ("Vault", Kind::Vault),
402];
403
404/// Every `Chat::Lines::*` subtype reads through the one Campfire-line route.
405const CHAT_LINE_TYPE_PREFIX: &str = "Chat::Lines::";
406
407/// The recording types [`RecordingsService::summarize`] routes by
408/// [`RecordingRef::recording_type`], sorted, with the `Chat::Lines` subtypes represented by
409/// their shared prefix (`Chat::Lines::*`). The set is deliberate rather than exhaustive —
410/// see the routing table — and any other type is
411/// [`RecordingSummaryError::UnknownRecordingType`] by design.
412pub fn summarizable_recording_types() -> Vec<String> {
413    let mut types: Vec<String> = RECORDING_TYPES
414        .iter()
415        .map(|(name, _)| (*name).to_string())
416        .chain(std::iter::once(format!("{CHAT_LINE_TYPE_PREFIX}*")))
417        .collect();
418    types.sort();
419    types
420}
421
422/// The account event feed subjects [`RecordingsService::summarize`] routes by
423/// [`RecordingRef::event_type`] — an event type is `<subject>.<action>`, and any action on a
424/// listed subject routes to that subject's read — sorted. `boost` is absent on purpose:
425/// [`RecordingSummaryError::NoRecordingType`].
426pub fn summarizable_event_types() -> Vec<String> {
427    let mut subjects: Vec<String> = EVENT_SUBJECTS
428        .iter()
429        .map(|(subject, _)| format!("{subject}.*"))
430        .collect();
431    subjects.sort();
432    subjects
433}
434
435/// Whether a chat line subtype carries rich text — the two that declare
436/// `rich_text_attribute :content` in BC3, and so the only two whose content can hold a
437/// mention. A `Text` line's content is HTML-escaped on the way out
438/// (`content_helper.rb`, `format_chat_line_with`), a `Code` line's is served verbatim — a
439/// snippet that happens to contain a `bc-attachment` tag — and an `Upload` line has no
440/// content.
441fn chat_line_is_rich_text(line_type: &str) -> bool {
442    matches!(
443        line_type,
444        "Chat::Lines::RichText" | "Chat::Lines::Integration"
445    )
446}
447
448/// Picks the read for a pointer. The recording type wins when set.
449fn route(reference: &RecordingRef) -> Result<Kind, RecordingSummaryError> {
450    let unknown = || RecordingSummaryError::UnknownRecordingType {
451        key: reference.key().to_string(),
452    };
453    let recording_type = reference
454        .recording_type
455        .as_deref()
456        .unwrap_or_default()
457        .trim();
458    if !recording_type.is_empty() {
459        if recording_type.starts_with(CHAT_LINE_TYPE_PREFIX) {
460            return Ok(Kind::ChatLine);
461        }
462        return lookup(RECORDING_TYPES, recording_type).ok_or_else(unknown);
463    }
464    let event_type = reference.event_type.as_deref().unwrap_or_default().trim();
465    // A feed type is "<subject>.<action>"; the subject names the recording type. A string
466    // with no action is not a feed type and is not routed.
467    let Some(index) = event_type.rfind('.') else {
468        return Err(unknown());
469    };
470    if index == 0 || index == event_type.len() - 1 {
471        return Err(unknown());
472    }
473    let subject = &event_type[..index];
474    if subject == "boost" {
475        return Err(RecordingSummaryError::NoRecordingType {
476            key: event_type.to_string(),
477        });
478    }
479    lookup(EVENT_SUBJECTS, subject).ok_or_else(unknown)
480}
481
482fn lookup(table: &[(&str, Kind)], key: &str) -> Option<Kind> {
483    table
484        .iter()
485        .find(|(name, _)| *name == key)
486        .map(|(_, kind)| *kind)
487}
488
489impl RecordingsService<'_> {
490    /// Resolves a recording pointer into a [`RecordingSummary`] through the typed read its
491    /// type names. See [`RecordingRef`] for the routing inputs and the module docs for the
492    /// design.
493    ///
494    /// # Errors
495    ///
496    /// A routing failure before any request; the read's own [`Error`] otherwise — a 404 is
497    /// `not_found`, as from the typed read itself; for chat lines,
498    /// [`RecordingSummaryError::Unresolved`] when every visible Campfire answered 404, which
499    /// is distinct from a read that failed (any non-404 from a candidate is returned as that
500    /// error, and the loop stops there) and from
501    /// [`RecordingSummaryError::CampfireDiscoveryIncomplete`] (candidates were left
502    /// unsearched); [`RecordingSummaryError::BucketMismatch`] when the read returned a
503    /// recording from another bucket. Match the composite's own reasons with
504    /// [`RecordingSummaryError::of`].
505    pub async fn summarize(&self, reference: &RecordingRef) -> Result<RecordingSummary, Error> {
506        if reference.bucket_id <= 0 || reference.recording_id <= 0 {
507            return Err(Error::usage("bucket id and recording id are required"));
508        }
509        let kind = route(reference)?;
510        let summary = read_summary(self.client(), reference, kind).await?;
511        if let Some(bucket) = &summary.bucket
512            && bucket.id != 0
513            && bucket.id != reference.bucket_id
514        {
515            return Err(RecordingSummaryError::BucketMismatch {
516                bucket_id: reference.bucket_id,
517                recording_id: reference.recording_id,
518                found_in: bucket.id,
519            }
520            .into());
521        }
522        Ok(summary)
523    }
524}
525
526/// The recording fields every read shares, plus what its own shape adds, before the
527/// mentions are read off the content.
528struct Projected {
529    id: i64,
530    status: String,
531    r#type: String,
532    title: String,
533    app_url: String,
534    updated_at: DateTime,
535    parent: Option<RecordingParent>,
536    bucket: Option<RecordingBucket>,
537    creator: Option<Person>,
538    assignees: Vec<Person>,
539    content: String,
540}
541
542impl Projected {
543    fn new(
544        id: i64,
545        status: String,
546        r#type: String,
547        title: String,
548        app_url: String,
549        updated_at: DateTime,
550    ) -> Projected {
551        Projected {
552            id,
553            status,
554            r#type,
555            title,
556            app_url,
557            updated_at,
558            parent: None,
559            bucket: None,
560            creator: None,
561            assignees: Vec::new(),
562            content: String::new(),
563        }
564    }
565
566    fn parent(mut self, parent: RecordingParent) -> Projected {
567        self.parent = Some(parent);
568        self
569    }
570
571    fn maybe_parent(mut self, parent: Option<RecordingParent>) -> Projected {
572        self.parent = parent;
573        self
574    }
575
576    fn todo_parent(self, parent: TodoParent) -> Projected {
577        self.parent(RecordingParent {
578            id: parent.id,
579            title: parent.title,
580            r#type: parent.r#type,
581            url: parent.url,
582            app_url: parent.app_url,
583            bucket: None,
584        })
585    }
586
587    fn bucket(mut self, bucket: RecordingBucket) -> Projected {
588        self.bucket = Some(bucket);
589        self
590    }
591
592    fn todo_bucket(self, bucket: TodoBucket) -> Projected {
593        self.bucket(RecordingBucket {
594            id: bucket.id,
595            name: bucket.name,
596            r#type: bucket.r#type,
597        })
598    }
599
600    fn creator(mut self, creator: Person) -> Projected {
601        self.creator = Some(creator);
602        self
603    }
604
605    fn assignees(mut self, assignees: Option<Vec<Person>>) -> Projected {
606        self.assignees = assignees.unwrap_or_default();
607        self
608    }
609
610    fn content(mut self, content: impl Into<String>) -> Projected {
611        self.content = content.into();
612        self
613    }
614}
615
616impl From<Projected> for RecordingSummary {
617    fn from(projected: Projected) -> RecordingSummary {
618        RecordingSummary {
619            id: projected.id,
620            status: projected.status,
621            r#type: projected.r#type,
622            title: projected.title,
623            app_url: projected.app_url,
624            parent: projected.parent,
625            bucket: projected.bucket,
626            creator: projected.creator,
627            assignees: projected.assignees,
628            mentioned_person_ids: mentioned_person_ids(&projected.content),
629            content: projected.content,
630            updated_at: projected.updated_at,
631            campfire_id: None,
632        }
633    }
634}
635
636/// The first of the candidates that is not empty, as a `String`.
637fn first_non_empty(primary: String, fallback: Option<String>) -> String {
638    if primary.is_empty() {
639        fallback.unwrap_or_default()
640    } else {
641        primary
642    }
643}
644
645/// Performs the one typed read a kind names and projects it.
646///
647/// One arm per routed type, spelled out: the projection differs per shape — which member
648/// carries the rich text, which carries the human title — and a table could not say that.
649#[allow(clippy::too_many_lines)]
650async fn read_summary(
651    account: &AccountClient,
652    reference: &RecordingRef,
653    kind: Kind,
654) -> Result<RecordingSummary, Error> {
655    let id = reference.recording_id;
656    let projected = match kind {
657        Kind::Comment => {
658            let comment = account.comments().get(id).await?;
659            Projected::new(
660                comment.id,
661                comment.status,
662                comment.r#type,
663                comment.title,
664                comment.app_url,
665                comment.updated_at,
666            )
667            .parent(comment.parent)
668            .todo_bucket(comment.bucket)
669            .creator(comment.creator)
670            .content(comment.content)
671        }
672        Kind::Message => {
673            let message = account.messages().get(id).await?;
674            Projected::new(
675                message.id,
676                message.status,
677                message.r#type,
678                first_non_empty(message.title, Some(message.subject)),
679                message.app_url,
680                message.updated_at,
681            )
682            .parent(message.parent)
683            .todo_bucket(message.bucket)
684            .creator(message.creator)
685            .content(message.content)
686        }
687        Kind::Todo => {
688            // A to-do's `content` is its plain title; the rich text — where mentions live —
689            // is the description.
690            let todo = account.todos().get(id).await?;
691            Projected::new(
692                todo.id,
693                todo.status,
694                todo.r#type,
695                first_non_empty(todo.title, Some(todo.content)),
696                todo.app_url,
697                todo.updated_at,
698            )
699            .todo_parent(todo.parent)
700            .todo_bucket(todo.bucket)
701            .creator(todo.creator)
702            .assignees(todo.assignees)
703            .content(todo.description.unwrap_or_default())
704        }
705        Kind::Card => {
706            let card = account.cards().get(id).await?;
707            Projected::new(
708                card.id,
709                card.status,
710                card.r#type,
711                card.title,
712                card.app_url,
713                card.updated_at,
714            )
715            .parent(card.parent)
716            .todo_bucket(card.bucket)
717            .creator(card.creator)
718            .assignees(card.assignees)
719            .content(first_non_empty(
720                card.content.unwrap_or_default(),
721                card.description,
722            ))
723        }
724        Kind::ChatLine => return chat_line_summary(account, reference).await,
725        Kind::Document => {
726            let document = account.documents().get(id).await?;
727            Projected::new(
728                document.id,
729                document.status,
730                document.r#type,
731                document.title,
732                document.app_url,
733                document.updated_at,
734            )
735            .parent(document.parent)
736            .todo_bucket(document.bucket)
737            .creator(document.creator)
738            .content(document.content.unwrap_or_default())
739        }
740        Kind::Upload => {
741            let upload = account.uploads().get(id).await?;
742            Projected::new(
743                upload.id,
744                upload.status,
745                upload.r#type,
746                first_non_empty(upload.title, upload.filename),
747                upload.app_url,
748                upload.updated_at,
749            )
750            .parent(upload.parent)
751            .todo_bucket(upload.bucket)
752            .creator(upload.creator)
753            .content(upload.description.unwrap_or_default())
754        }
755        Kind::ScheduleEntry => {
756            let entry = account.schedules().get_entry(id).await?;
757            Projected::new(
758                entry.id,
759                entry.status,
760                entry.r#type,
761                first_non_empty(entry.title, Some(entry.summary)),
762                entry.app_url,
763                entry.updated_at,
764            )
765            .parent(entry.parent)
766            .todo_bucket(entry.bucket)
767            .creator(entry.creator)
768            .content(entry.description.unwrap_or_default())
769        }
770        Kind::Question => {
771            let question = account.checkins().get_question(id).await?;
772            Projected::new(
773                question.id,
774                question.status,
775                question.r#type,
776                question.title,
777                question.app_url,
778                question.updated_at,
779            )
780            .parent(question.parent)
781            .bucket(question.bucket)
782            .creator(question.creator)
783        }
784        Kind::QuestionAnswer => {
785            let answer = account.checkins().get_answer(id).await?;
786            Projected::new(
787                answer.id,
788                answer.status,
789                answer.r#type,
790                answer.title,
791                answer.app_url,
792                answer.updated_at,
793            )
794            .parent(answer.parent)
795            .bucket(answer.bucket)
796            .creator(answer.creator)
797            .content(answer.content)
798        }
799        Kind::Todolist => {
800            let todolist = account.todolists().get(id).await?;
801            Projected::new(
802                todolist.id,
803                todolist.status,
804                todolist.r#type,
805                first_non_empty(todolist.title, Some(todolist.name)),
806                todolist.app_url,
807                todolist.updated_at,
808            )
809            .todo_parent(todolist.parent)
810            .todo_bucket(todolist.bucket)
811            .creator(todolist.creator)
812            .content(todolist.description)
813        }
814        Kind::Vault => {
815            let vault = account.vaults().get(id).await?;
816            Projected::new(
817                vault.id,
818                vault.status,
819                vault.r#type,
820                vault.title,
821                vault.app_url,
822                vault.updated_at,
823            )
824            .maybe_parent(vault.parent)
825            .todo_bucket(vault.bucket)
826            .creator(vault.creator)
827        }
828        Kind::Forward => {
829            let forward = account.forwards().get(id).await?;
830            Projected::new(
831                forward.id,
832                forward.status,
833                forward.r#type,
834                first_non_empty(forward.title, Some(forward.subject)),
835                forward.app_url,
836                forward.updated_at,
837            )
838            .parent(forward.parent)
839            .todo_bucket(forward.bucket)
840            .creator(forward.creator)
841            .content(forward.content.unwrap_or_default())
842        }
843        Kind::ClientApproval => {
844            let approval = account.client_approvals().get(id).await?;
845            Projected::new(
846                approval.id,
847                approval.status,
848                approval.r#type,
849                first_non_empty(approval.title, approval.subject),
850                approval.app_url,
851                approval.updated_at,
852            )
853            .parent(approval.parent)
854            .bucket(approval.bucket)
855            .creator(approval.creator)
856            .content(approval.content.unwrap_or_default())
857        }
858        Kind::ClientCorrespondence => {
859            let correspondence = account.client_correspondences().get(id).await?;
860            Projected::new(
861                correspondence.id,
862                correspondence.status,
863                correspondence.r#type,
864                first_non_empty(correspondence.title, Some(correspondence.subject)),
865                correspondence.app_url,
866                correspondence.updated_at,
867            )
868            .parent(correspondence.parent)
869            .bucket(correspondence.bucket)
870            .creator(correspondence.creator)
871            .content(correspondence.content.unwrap_or_default())
872        }
873        Kind::GoogleDocument => {
874            let document = account.google_documents().google_document(id).await?;
875            Projected::new(
876                document.id,
877                document.status,
878                document.r#type,
879                document.title,
880                document.app_url,
881                document.updated_at,
882            )
883            .parent(document.parent)
884            .todo_bucket(document.bucket)
885            .creator(document.creator)
886            .content(document.description.unwrap_or_default())
887        }
888        Kind::CloudFile => {
889            let file = account.cloud_files().cloud_file(id).await?;
890            Projected::new(
891                file.id,
892                file.status,
893                file.r#type,
894                file.title,
895                file.app_url,
896                file.updated_at,
897            )
898            .parent(file.parent)
899            .todo_bucket(file.bucket)
900            .creator(file.creator)
901            .content(file.description.unwrap_or_default())
902        }
903        Kind::CardStep => {
904            let step = account.card_steps().get(id).await?;
905            Projected::new(
906                step.id,
907                step.status,
908                step.r#type,
909                step.title,
910                step.app_url,
911                step.updated_at,
912            )
913            .parent(step.parent)
914            .todo_bucket(step.bucket)
915            .creator(step.creator)
916            .assignees(step.assignees)
917        }
918        Kind::Questionnaire => {
919            let questionnaire = account.checkins().get_questionnaire(id).await?;
920            Projected::new(
921                questionnaire.id,
922                questionnaire.status,
923                questionnaire.r#type,
924                first_non_empty(questionnaire.title, Some(questionnaire.name)),
925                questionnaire.app_url,
926                questionnaire.updated_at,
927            )
928            .bucket(questionnaire.bucket)
929            .creator(questionnaire.creator)
930        }
931        Kind::Schedule => {
932            let schedule = account.schedules().get(id).await?;
933            Projected::new(
934                schedule.id,
935                schedule.status,
936                schedule.r#type,
937                schedule.title,
938                schedule.app_url,
939                schedule.updated_at,
940            )
941            .todo_bucket(schedule.bucket)
942            .creator(schedule.creator)
943        }
944        Kind::Todoset => {
945            let todoset = account.todosets().get(id).await?;
946            Projected::new(
947                todoset.id,
948                todoset.status,
949                todoset.r#type,
950                first_non_empty(todoset.title, Some(todoset.name)),
951                todoset.app_url,
952                todoset.updated_at,
953            )
954            .todo_bucket(todoset.bucket)
955            .creator(todoset.creator)
956        }
957        Kind::MessageBoard => {
958            let board = account.message_boards().get(id).await?;
959            Projected::new(
960                board.id,
961                board.status,
962                board.r#type,
963                board.title,
964                board.app_url,
965                board.updated_at,
966            )
967            .todo_bucket(board.bucket)
968            .creator(board.creator)
969        }
970        Kind::CardTable => {
971            let table = account.card_tables().get(id).await?;
972            Projected::new(
973                table.id,
974                table.status,
975                table.r#type,
976                table.title,
977                table.app_url,
978                table.updated_at,
979            )
980            .todo_bucket(table.bucket)
981            .creator(table.creator)
982        }
983        Kind::CardColumn => {
984            let column = account.card_columns().get(id).await?;
985            Projected::new(
986                column.id,
987                column.status,
988                column.r#type,
989                column.title,
990                column.app_url,
991                column.updated_at,
992            )
993            .parent(column.parent)
994            .todo_bucket(column.bucket)
995            .creator(column.creator)
996            .content(column.description.unwrap_or_default())
997        }
998        Kind::Inbox => {
999            let inbox = account.forwards().get_inbox(id).await?;
1000            Projected::new(
1001                inbox.id,
1002                inbox.status,
1003                inbox.r#type,
1004                inbox.title,
1005                inbox.app_url,
1006                inbox.updated_at,
1007            )
1008            .todo_bucket(inbox.bucket)
1009            .creator(inbox.creator)
1010        }
1011        Kind::Campfire => {
1012            let campfire = account.campfires().get(id).await?;
1013            Projected::new(
1014                campfire.id,
1015                campfire.status,
1016                campfire.r#type,
1017                campfire.title,
1018                campfire.app_url,
1019                campfire.updated_at,
1020            )
1021            .todo_bucket(campfire.bucket)
1022            .creator(campfire.creator)
1023        }
1024    };
1025    Ok(projected.into())
1026}
1027
1028/// Discovers the Campfire a chat line lives in, reads the line under it, and projects it.
1029async fn chat_line_summary(
1030    account: &AccountClient,
1031    reference: &RecordingRef,
1032) -> Result<RecordingSummary, Error> {
1033    let (line, campfire_id) =
1034        resolve_chat_line(account, reference.bucket_id, reference.recording_id).await?;
1035    let rich_text = chat_line_is_rich_text(&line.r#type);
1036    let mut summary: RecordingSummary = Projected::new(
1037        line.id,
1038        line.status,
1039        line.r#type,
1040        line.title,
1041        line.app_url,
1042        line.updated_at,
1043    )
1044    .parent(line.parent)
1045    .todo_bucket(line.bucket)
1046    .creator(line.creator)
1047    .content(line.content.unwrap_or_default())
1048    .into();
1049    if !rich_text {
1050        // A plain-text or code line's content is text BC3 never read as markup, so a
1051        // literal "<bc-attachment>" in it mentions nobody.
1052        summary.mentioned_person_ids.clear();
1053    }
1054    summary.campfire_id = Some(campfire_id);
1055    Ok(summary)
1056}
1057
1058/// One `summarize` call's discovery state: which candidates have answered "not here", how
1059/// many more this call may try, and whether any were left untried for want of budget.
1060struct ChatLineSearch<'a> {
1061    account: &'a AccountClient,
1062    line_id: i64,
1063    tried: Vec<i64>,
1064    budget: usize,
1065    skipped: bool,
1066}
1067
1068impl ChatLineSearch<'_> {
1069    /// Reads the line under each candidate not yet tried. Answers the line and its Campfire
1070    /// on a hit; on a miss it answers `None` with no error and records the candidates in
1071    /// `tried`. Any answer but 404 is returned as is.
1072    async fn try_candidates(
1073        &mut self,
1074        candidates: &[i64],
1075    ) -> Result<Option<(CampfireLine, i64)>, Error> {
1076        for campfire_id in candidates {
1077            if self.tried.contains(campfire_id) {
1078                continue;
1079            }
1080            if self.budget == 0 {
1081                self.skipped = true;
1082                return Ok(None);
1083            }
1084            self.budget -= 1;
1085            match self
1086                .account
1087                .campfires()
1088                .get_line(*campfire_id, self.line_id)
1089                .await
1090            {
1091                Ok(line) => return Ok(Some((line, *campfire_id))),
1092                Err(error) if error.code() == ErrorCode::NotFound => self.tried.push(*campfire_id),
1093                Err(error) => return Err(error),
1094            }
1095        }
1096        Ok(None)
1097    }
1098}
1099
1100/// Finds the Campfire a line lives in and reads it.
1101///
1102/// Two failure shapes are kept apart on purpose. A candidate that answers anything but 404 —
1103/// 401, 403, 5xx, a transport error — stops the loop and is returned as that error: the read
1104/// failed, and trying the next Campfire would only hide it. A 404 means "not here", so the
1105/// loop moves on. Only when every candidate said "not here" is the line
1106/// [`RecordingSummaryError::Unresolved`] — and before concluding that, the cached sources
1107/// are refreshed (subject to a floor) so a Campfire created after the cache filled is tried
1108/// too. Discovery that could not be completed — a listing cut off at its cap, a bucket with
1109/// more candidates than the budget — is
1110/// [`RecordingSummaryError::CampfireDiscoveryIncomplete`], never "unresolved": nothing
1111/// unsearched is ever reported absent.
1112///
1113/// What HTTP cannot tell apart: BC3 answers 404 both for a line that is not in a Campfire
1114/// and for a Campfire the caller may no longer see. "Unresolved" therefore means "under no
1115/// Campfire the caller can currently see", and the error reports the cached candidates that
1116/// the refreshed sources no longer list
1117/// ([`UnresolvedRecording::stale_campfire_ids`]) so a consumer can see when visibility, not
1118/// existence, is what changed.
1119async fn resolve_chat_line(
1120    account: &AccountClient,
1121    bucket_id: i64,
1122    line_id: i64,
1123) -> Result<(CampfireLine, i64), Error> {
1124    let index = account.campfire_index();
1125    let mut search = ChatLineSearch {
1126        account,
1127        line_id,
1128        tried: Vec::new(),
1129        budget: MAX_CAMPFIRE_CANDIDATES,
1130        skipped: false,
1131    };
1132    let incomplete = |reason: String| -> Error {
1133        RecordingSummaryError::CampfireDiscoveryIncomplete {
1134            bucket_id,
1135            recording_id: line_id,
1136            reason,
1137        }
1138        .into()
1139    };
1140    let over_budget =
1141        || format!("more than {MAX_CAMPFIRE_CANDIDATES} visible campfires in the bucket");
1142
1143    // Pass 1: what the sources already hold — the dock (read if it must be), then the
1144    // listing only if it is cached. A listing fetch is the expensive, slow request, and it
1145    // is not made until the dock — including its refresh — has had its say, so a listing
1146    // that is down, over its cap, or stalled on a deadline never stands between a project's
1147    // line and the one project read that finds it.
1148    let mut dock = index.dock_campfires(account, bucket_id, false).await?;
1149    if let Some(found) = search.try_candidates(&dock.ids).await? {
1150        return Ok(found);
1151    }
1152    let listed = index.cached_listed_campfires(account.account_id(), bucket_id);
1153    if let Some(listed) = &listed
1154        && let Some(found) = search.try_candidates(&listed.ids).await?
1155    {
1156        return Ok(found);
1157    }
1158
1159    // Pass 2: re-read the dock if it was served from cache (the floor may decline), then
1160    // fetch or refresh the listing. Whatever comes back is the current snapshot of that
1161    // source, whoever loaded it — another caller may have populated or refreshed it in the
1162    // meantime — so it always replaces the pass-1 one; "refreshed" is whether a source the
1163    // conclusion had consulted is now newer than when it was consulted.
1164    //
1165    // A spent budget stops both, and the two sources part company on WHY. A source already
1166    // consulted cannot hand this call a candidate it may try, so its refresh is skipped and
1167    // the conclusion stands on what was seen (`refreshed` stays false) — paying for that
1168    // request would buy nothing, and a failure on it would replace a settled `incomplete`
1169    // with a transient error a consumer retries forever. A source NEVER consulted is a
1170    // different verdict: candidates may exist there unsearched, so running out of budget
1171    // before reaching it makes the answer incomplete rather than unresolved.
1172    //
1173    // `skipped` alone cannot express that, which is what the earlier shape got wrong. It is
1174    // set only when a candidate is OBSERVED and cannot be tried, so a source holding
1175    // exactly `MAX_CAMPFIRE_CANDIDATES` candidates that all answer 404 leaves the budget at
1176    // zero with `skipped` still false. And concluding `incomplete` on a spent budget alone
1177    // is equally wrong in the other direction: a bucket whose candidates were all searched
1178    // is not incomplete. The budget gates the re-reads; `skipped` still decides the final
1179    // verdict.
1180    let mut refreshed = false;
1181    if search.budget > 0 && dock.cached {
1182        let again = index.dock_campfires(account, bucket_id, true).await?;
1183        if newer_than(&again, &dock) {
1184            refreshed = true;
1185        }
1186        dock = again;
1187        if let Some(found) = search.try_candidates(&dock.ids).await? {
1188            return Ok(found);
1189        }
1190    }
1191    // Seeded from what pass 1 consulted, not empty: on the budget-spent path the listing is
1192    // not re-read, and the stale filter below has to compare against the snapshot the
1193    // conclusion actually used. Starting empty reports every listing-only candidate as one
1194    // the caller has LOST VISIBILITY of, when nothing changed.
1195    let mut listed_ids = listed
1196        .as_ref()
1197        .map(|listed| listed.ids.clone())
1198        .unwrap_or_default();
1199    if search.budget == 0 {
1200        if listed.is_none() {
1201            return Err(incomplete(format!(
1202                "the candidate budget of {MAX_CAMPFIRE_CANDIDATES} was spent before the account listing was consulted"
1203            )));
1204        }
1205    } else {
1206        let again = index
1207            .listed_campfires(account, bucket_id, listed.is_some())
1208            .await
1209            .map_err(|error| {
1210                if is_listing_overflow(&error) {
1211                    incomplete(error.to_string())
1212                } else {
1213                    error
1214                }
1215            })?;
1216        if let Some(previous) = &listed
1217            && newer_than(&again, previous)
1218        {
1219            refreshed = true;
1220        }
1221        listed_ids = again.ids;
1222        if let Some(found) = search.try_candidates(&listed_ids).await? {
1223            return Ok(found);
1224        }
1225    }
1226    if search.skipped {
1227        return Err(incomplete(over_budget()));
1228    }
1229
1230    let mut unresolved = UnresolvedRecording {
1231        bucket_id,
1232        recording_id: line_id,
1233        campfire_ids: search.tried.clone(),
1234        refreshed,
1235        stale_campfire_ids: Vec::new(),
1236    };
1237    if refreshed {
1238        unresolved.stale_campfire_ids = search
1239            .tried
1240            .iter()
1241            .copied()
1242            .filter(|id| !dock.ids.contains(id) && !listed_ids.contains(id))
1243            .collect();
1244    }
1245    Err(RecordingSummaryError::Unresolved(unresolved).into())
1246}
1247
1248/// Whether a re-read of a source answered something newer than the snapshot the conclusion
1249/// had already consulted — a fresh load, or a snapshot another caller published in the
1250/// meantime.
1251fn newer_than(again: &SourceRead, previous: &SourceRead) -> bool {
1252    !again.cached || again.fetched > previous.fetched
1253}
1254
1255#[cfg(test)]
1256mod tests {
1257    use super::*;
1258
1259    fn kind_of(reference: &RecordingRef) -> Result<Kind, RecordingSummaryError> {
1260        route(reference)
1261    }
1262
1263    #[test]
1264    fn a_server_sent_empty_assignee_list_serializes_as_an_empty_list() {
1265        let summary = RecordingSummary::default();
1266        assert!(summary.assignees.is_empty());
1267        let json = serde_json::to_value(&summary).unwrap();
1268        assert_eq!(json["assignees"], serde_json::json!([]), "{json}");
1269    }
1270
1271    #[test]
1272    fn a_recording_type_routes_and_wins_over_the_event_type() {
1273        let reference = RecordingRef {
1274            bucket_id: 1,
1275            recording_id: 2,
1276            event_type: Some("comment.created".to_string()),
1277            recording_type: Some("Kanban::Card".to_string()),
1278        };
1279        assert_eq!(kind_of(&reference), Ok(Kind::Card));
1280    }
1281
1282    #[test]
1283    fn every_chat_line_subtype_reads_through_the_one_route() {
1284        for subtype in [
1285            "Chat::Lines::Text",
1286            "Chat::Lines::RichText",
1287            "Chat::Lines::Code",
1288            "Chat::Lines::Upload",
1289            "Chat::Lines::Integration",
1290        ] {
1291            assert_eq!(
1292                kind_of(&RecordingRef::from_recording_type(1, 2, subtype)),
1293                Ok(Kind::ChatLine),
1294                "{subtype}"
1295            );
1296        }
1297    }
1298
1299    #[test]
1300    fn every_feed_subject_routes_whatever_the_action_is() {
1301        for event in [
1302            "comment.created",
1303            "message.updated",
1304            "todo.assignment_changed",
1305            "card.moved",
1306            "chat.line.created",
1307        ] {
1308            assert!(
1309                kind_of(&RecordingRef::from_event(1, 2, event)).is_ok(),
1310                "{event}"
1311            );
1312        }
1313    }
1314
1315    #[test]
1316    fn boost_is_refused_as_naming_no_recording_type() {
1317        let refused = kind_of(&RecordingRef::from_event(1, 2, "boost.created"));
1318        assert!(matches!(
1319            refused,
1320            Err(RecordingSummaryError::NoRecordingType { .. })
1321        ));
1322        let error: Error = refused.unwrap_err().into();
1323        assert_eq!(error.code(), ErrorCode::Usage);
1324        assert!(error.to_string().contains("names no recording type"));
1325        assert!(matches!(
1326            RecordingSummaryError::of(&error),
1327            Some(RecordingSummaryError::NoRecordingType { .. })
1328        ));
1329    }
1330
1331    #[test]
1332    fn an_unrouted_type_or_a_malformed_event_type_is_unknown() {
1333        for reference in [
1334            RecordingRef::from_recording_type(1, 2, "Timesheet::Entry"),
1335            RecordingRef::from_recording_type(1, 2, "Client::Reply"),
1336            RecordingRef::from_event(1, 2, "comment"),
1337            RecordingRef::from_event(1, 2, "comment."),
1338            RecordingRef::from_event(1, 2, ".created"),
1339            RecordingRef::from_event(1, 2, "unheard_of.created"),
1340            RecordingRef::default(),
1341        ] {
1342            assert!(
1343                matches!(
1344                    kind_of(&reference),
1345                    Err(RecordingSummaryError::UnknownRecordingType { .. })
1346                ),
1347                "{reference:?}"
1348            );
1349        }
1350    }
1351
1352    #[test]
1353    fn the_documented_sets_are_the_routed_ones() {
1354        let types = summarizable_recording_types();
1355        assert_eq!(types.len(), RECORDING_TYPES.len() + 1);
1356        assert!(types.contains(&"Chat::Lines::*".to_string()));
1357        assert!(types.windows(2).all(|pair| pair[0] <= pair[1]), "sorted");
1358        for (name, _) in RECORDING_TYPES {
1359            assert!(types.contains(&(*name).to_string()), "{name}");
1360            assert!(
1361                kind_of(&RecordingRef::from_recording_type(1, 2, *name)).is_ok(),
1362                "{name}"
1363            );
1364        }
1365        let events = summarizable_event_types();
1366        assert_eq!(events.len(), EVENT_SUBJECTS.len());
1367        assert!(!events.iter().any(|subject| subject.starts_with("boost")));
1368        assert!(events.windows(2).all(|pair| pair[0] <= pair[1]), "sorted");
1369    }
1370
1371    #[test]
1372    fn only_the_two_rich_text_line_subtypes_can_carry_a_mention() {
1373        assert!(chat_line_is_rich_text("Chat::Lines::RichText"));
1374        assert!(chat_line_is_rich_text("Chat::Lines::Integration"));
1375        assert!(!chat_line_is_rich_text("Chat::Lines::Text"));
1376        assert!(!chat_line_is_rich_text("Chat::Lines::Code"));
1377        assert!(!chat_line_is_rich_text("Chat::Lines::Upload"));
1378    }
1379
1380    #[test]
1381    fn the_composites_own_reasons_carry_their_taxonomy_member() {
1382        let unresolved: Error = RecordingSummaryError::Unresolved(UnresolvedRecording {
1383            bucket_id: 1,
1384            recording_id: 2,
1385            campfire_ids: vec![3, 4],
1386            refreshed: true,
1387            stale_campfire_ids: vec![3],
1388        })
1389        .into();
1390        assert_eq!(unresolved.code(), ErrorCode::NotFound);
1391        assert!(
1392            unresolved
1393                .to_string()
1394                .contains("found under no visible campfire")
1395        );
1396
1397        let incomplete: Error = RecordingSummaryError::CampfireDiscoveryIncomplete {
1398            bucket_id: 1,
1399            recording_id: 2,
1400            reason: "too many".to_string(),
1401        }
1402        .into();
1403        // `usage`, settled on card 40: the one coarse code no HTTP response can
1404        // produce, so this verdict can never be read back as a constituent read's
1405        // own answer. Non-retryable, which is the other half of that decision and
1406        // the half a code change could otherwise carry away with it.
1407        assert_eq!(incomplete.code(), ErrorCode::Usage);
1408        assert!(!incomplete.is_retryable());
1409        // Never not_found: nothing left unsearched may be reported absent.
1410        assert_ne!(incomplete.code(), unresolved.code());
1411
1412        let mismatch: Error = RecordingSummaryError::BucketMismatch {
1413            bucket_id: 1,
1414            recording_id: 2,
1415            found_in: 9,
1416        }
1417        .into();
1418        // `usage`, settled on card 41: the read found the recording, in another
1419        // bucket, and returned it -- what failed is the caller's pointer.
1420        assert_eq!(mismatch.code(), ErrorCode::Usage);
1421        assert!(!mismatch.is_retryable());
1422        assert!(matches!(
1423            RecordingSummaryError::of(&mismatch),
1424            Some(RecordingSummaryError::BucketMismatch { found_in: 9, .. })
1425        ));
1426    }
1427
1428    #[test]
1429    fn a_plain_read_failure_carries_no_composite_reason() {
1430        let forbidden = Error::new(ErrorCode::Forbidden, "nope").with_status(403);
1431        assert!(RecordingSummaryError::of(&forbidden).is_none());
1432    }
1433
1434    #[test]
1435    fn a_verdict_survives_being_wrapped_on_its_way_out() {
1436        let verdict: Error = RecordingSummaryError::BucketMismatch {
1437            bucket_id: 1,
1438            recording_id: 2,
1439            found_in: 9,
1440        }
1441        .into();
1442        let wrapped = Error::new(ErrorCode::ApiError, "while admitting an event")
1443            .with_source(std::sync::Arc::new(verdict));
1444        assert!(matches!(
1445            RecordingSummaryError::of(&wrapped),
1446            Some(RecordingSummaryError::BucketMismatch { found_in: 9, .. })
1447        ));
1448    }
1449
1450    #[test]
1451    fn a_title_falls_back_only_when_the_primary_is_empty() {
1452        assert_eq!(
1453            first_non_empty("title".to_string(), Some("subject".to_string())),
1454            "title"
1455        );
1456        assert_eq!(
1457            first_non_empty(String::new(), Some("subject".to_string())),
1458            "subject"
1459        );
1460        assert_eq!(first_non_empty(String::new(), None), "");
1461    }
1462}
1463
1464/// The refresh path, which needs the floor crossed and so needs a clock a test can move.
1465/// Everything here turns on entries ageing: the rest of the discovery behaviour is driven
1466/// end-to-end in `tests/composites_recording_summary.rs`, where real time is enough.
1467///
1468/// These drive wiremock and so need the shipped transport, exactly as the OAuth unit tests
1469/// do. The no-default-features lane builds the crate WITHOUT one — that is the point of the
1470/// lane — so it skips this module rather than failing in it.
1471#[cfg(all(test, feature = "reqwest"))]
1472mod refresh_tests {
1473    use super::*;
1474    use crate::Config;
1475    use crate::client::Client;
1476    use crate::services::campfire_index::{
1477        CAMPFIRE_INDEX_MIN_REFRESH, MAX_CAMPFIRE_CANDIDATES, TestClock,
1478    };
1479    use serde_json::{Value, json};
1480    use std::sync::Arc;
1481    use std::time::Duration;
1482    use wiremock::matchers::{method, path};
1483    use wiremock::{Mock, MockServer, ResponseTemplate};
1484
1485    const BUCKET: i64 = 1_069_479_338;
1486    const LINE: i64 = 1_069_479_351;
1487    const CACHED_A: i64 = 1_069_479_340;
1488    const CACHED_B: i64 = 1_069_479_345;
1489    const APPEARED: i64 = 1_069_479_399;
1490    const OTHER_BUCKET: i64 = 2_085_958_500;
1491
1492    fn campfire(id: i64, bucket: i64) -> Value {
1493        json!({
1494            "id": id,
1495            "status": "active",
1496            "created_at": "2022-10-28T15:25:00.000Z",
1497            "updated_at": "2022-10-28T15:25:00.000Z",
1498            "title": "Campfire",
1499            "visible_to_clients": false,
1500            "inherits_status": true,
1501            "type": "Chat::Transcript",
1502            "url": "https://3.basecampapi.com/999/buckets/x/chats/x.json",
1503            "app_url": "https://3.basecamp.com/999/buckets/x/chats/x",
1504            "bucket": { "id": bucket, "name": "A project", "type": "Project" },
1505            "creator": { "id": 1, "name": "Victor Cooper" },
1506        })
1507    }
1508
1509    fn project_docking(campfire_ids: &[i64]) -> Value {
1510        let dock: Vec<Value> = campfire_ids
1511            .iter()
1512            .map(|id| {
1513                json!({ "id": id, "title": "Campfire", "name": "chat", "enabled": true, "url": "u", "app_url": "a" })
1514            })
1515            .collect();
1516        json!({
1517            "id": BUCKET,
1518            "status": "active",
1519            "created_at": "2022-10-28T15:25:00.000Z",
1520            "updated_at": "2022-10-28T15:25:00.000Z",
1521            "name": "A project",
1522            "url": "https://3.basecampapi.com/999/projects/x.json",
1523            "app_url": "https://3.basecamp.com/999/projects/x",
1524            "dock": dock,
1525        })
1526    }
1527
1528    async fn mount(server: &MockServer, route: &str, status: u16, body: &Value) {
1529        Mock::given(method("GET"))
1530            .and(path(route))
1531            .respond_with(ResponseTemplate::new(status).set_body_json(body.clone()))
1532            .mount(server)
1533            .await;
1534    }
1535
1536    /// The dock shows `docked`, the account listing shows `listed`, and every line read
1537    /// answers 404 — so the search always runs to the end and reports what it tried. The
1538    /// line routes are mounted one per candidate rather than as a catch-all, which could
1539    /// shadow the dock or the listing and decide the test by mount order.
1540    async fn scripted(server: &MockServer, docked: &[i64], listed: &[i64]) {
1541        server.reset().await;
1542        mount(
1543            server,
1544            &format!("/999/projects/{BUCKET}"),
1545            200,
1546            &project_docking(docked),
1547        )
1548        .await;
1549        let listing: Vec<Value> = listed.iter().map(|id| campfire(*id, BUCKET)).collect();
1550        mount(server, "/999/chats.json", 200, &json!(listing)).await;
1551        for id in docked.iter().chain(listed) {
1552            mount(
1553                server,
1554                &format!("/999/chats/{id}/lines/{LINE}"),
1555                404,
1556                &json!({ "error": "Record not found" }),
1557            )
1558            .await;
1559        }
1560    }
1561
1562    async fn paths(server: &MockServer) -> Vec<String> {
1563        server
1564            .received_requests()
1565            .await
1566            .unwrap_or_default()
1567            .iter()
1568            .map(|request| request.url.path().to_string())
1569            .collect()
1570    }
1571
1572    fn account_on(server: &MockServer, clock: &Arc<TestClock>) -> AccountClient {
1573        Client::builder(
1574            Config::default()
1575                .with_base_url(server.uri())
1576                .with_timeout(Duration::from_secs(86_400)),
1577        )
1578        .access_token("test-token")
1579        .campfire_clock(clock.clock())
1580        .build()
1581        .expect("client")
1582        .for_account("999")
1583    }
1584
1585    fn unresolved_from(error: &Error) -> UnresolvedRecording {
1586        match RecordingSummaryError::of(error) {
1587            Some(RecordingSummaryError::Unresolved(unresolved)) => unresolved.clone(),
1588            _ => panic!("expected an unresolved line, got {error}"),
1589        }
1590    }
1591
1592    /// Past the floor a miss re-reads both sources, and the conclusion says so: `refreshed`
1593    /// is set, and the Campfires the cache had that neither source lists any more are named
1594    /// as stale. That is the only signal a consumer has that the line went missing because
1595    /// visibility changed rather than because it never existed — a 404 per candidate cannot
1596    /// tell the two apart. Mirrors Go's `TestSummarize_ChatLineDiscovery`.
1597    #[tokio::test]
1598    async fn a_refreshed_miss_names_the_campfires_the_caller_can_no_longer_see() {
1599        let clock = TestClock::new();
1600        let server = MockServer::start().await;
1601        scripted(&server, &[CACHED_A], &[CACHED_A, CACHED_B]).await;
1602        let account = account_on(&server, &clock);
1603        let reference = RecordingRef::from_event(BUCKET, LINE, "chat.line.created");
1604
1605        // First call: both sources are read during the call, so nothing was refreshed.
1606        let first = unresolved_from(
1607            &account
1608                .recordings()
1609                .summarize(&reference)
1610                .await
1611                .unwrap_err(),
1612        );
1613        assert_eq!(first.campfire_ids, vec![CACHED_A, CACHED_B]);
1614        assert!(!first.refreshed, "sources read this very call");
1615        assert!(first.stale_campfire_ids.is_empty());
1616
1617        // Past the floor, with both sources now showing a Campfire that did not exist when
1618        // the cache filled and no longer showing either that did.
1619        clock.advance(CAMPFIRE_INDEX_MIN_REFRESH + Duration::from_secs(1));
1620        scripted(&server, &[APPEARED], &[APPEARED]).await;
1621
1622        let second = unresolved_from(
1623            &account
1624                .recordings()
1625                .summarize(&reference)
1626                .await
1627                .unwrap_err(),
1628        );
1629        assert!(
1630            second.refreshed,
1631            "the floor was past and both sources answered newer than the cache"
1632        );
1633        assert_eq!(
1634            second.campfire_ids,
1635            vec![CACHED_A, CACHED_B, APPEARED],
1636            "the cached candidates were tried first, then the one the refresh found"
1637        );
1638        assert_eq!(
1639            second.stale_campfire_ids,
1640            vec![CACHED_A, CACHED_B],
1641            "both cached Campfires are gone from the dock and the listing"
1642        );
1643    }
1644
1645    /// Refreshed by the LISTING alone. The account listing is cached per account, not per
1646    /// bucket, so the first bucket looked at pays for it and every other bucket meets it
1647    /// already warm — while its own dock is read fresh this call and so is never re-read.
1648    /// That is the one path where the listing refresh is what makes the conclusion a
1649    /// refreshed one, and the only reason to test it separately is that on every other path
1650    /// the dock re-read has already said so.
1651    ///
1652    /// Written after mutation testing: with the listing branch's `refreshed = true` removed,
1653    /// every other test here still passed.
1654    #[tokio::test]
1655    async fn a_second_bucket_meets_a_warm_listing_and_is_refreshed_by_it_alone() {
1656        let clock = TestClock::new();
1657        let server = MockServer::start().await;
1658        // Neither bucket is a project, so the dock answers "no dock" and the listing is the
1659        // only source. It shows one Campfire in each bucket.
1660        for bucket in [BUCKET, OTHER_BUCKET] {
1661            mount(
1662                &server,
1663                &format!("/999/projects/{bucket}"),
1664                404,
1665                &json!({ "error": "Record not found" }),
1666            )
1667            .await;
1668        }
1669        for id in [CACHED_A, CACHED_B] {
1670            mount(
1671                &server,
1672                &format!("/999/chats/{id}/lines/{LINE}"),
1673                404,
1674                &json!({ "error": "Record not found" }),
1675            )
1676            .await;
1677        }
1678        mount(
1679            &server,
1680            "/999/chats.json",
1681            200,
1682            &json!([campfire(CACHED_A, BUCKET), campfire(CACHED_B, OTHER_BUCKET)]),
1683        )
1684        .await;
1685        let account = account_on(&server, &clock);
1686
1687        // The first bucket pays for the listing.
1688        let first = unresolved_from(
1689            &account
1690                .recordings()
1691                .summarize(&RecordingRef::from_event(BUCKET, LINE, "chat.line.created"))
1692                .await
1693                .unwrap_err(),
1694        );
1695        assert_eq!(first.campfire_ids, vec![CACHED_A]);
1696        assert!(!first.refreshed, "the listing was read during that call");
1697
1698        // Past the floor, and the listing no longer shows the second bucket's Campfire.
1699        clock.advance(CAMPFIRE_INDEX_MIN_REFRESH + Duration::from_secs(1));
1700        server.reset().await;
1701        for bucket in [BUCKET, OTHER_BUCKET] {
1702            mount(
1703                &server,
1704                &format!("/999/projects/{bucket}"),
1705                404,
1706                &json!({ "error": "Record not found" }),
1707            )
1708            .await;
1709        }
1710        mount(
1711            &server,
1712            &format!("/999/chats/{CACHED_B}/lines/{LINE}"),
1713            404,
1714            &json!({ "error": "Record not found" }),
1715        )
1716        .await;
1717        mount(
1718            &server,
1719            "/999/chats.json",
1720            200,
1721            &json!([campfire(CACHED_A, BUCKET)]),
1722        )
1723        .await;
1724
1725        let second = unresolved_from(
1726            &account
1727                .recordings()
1728                .summarize(&RecordingRef::from_event(
1729                    OTHER_BUCKET,
1730                    LINE,
1731                    "chat.line.created",
1732                ))
1733                .await
1734                .unwrap_err(),
1735        );
1736        assert_eq!(second.bucket_id, OTHER_BUCKET);
1737        assert_eq!(
1738            second.campfire_ids,
1739            vec![CACHED_B],
1740            "the warm listing supplied the candidate"
1741        );
1742        assert!(
1743            second.refreshed,
1744            "this bucket's dock was read fresh and never re-read, so only the listing \
1745             refresh can have said the conclusion rests on newer data"
1746        );
1747        assert_eq!(
1748            second.stale_campfire_ids,
1749            vec![CACHED_B],
1750            "the refreshed listing no longer shows it: visibility changed"
1751        );
1752    }
1753
1754    /// The stale list is measured against what the conclusion ACTUALLY consulted, and on
1755    /// this path the listing is never re-read: the dock refresh spends the last of the
1756    /// budget, so refreshing the listing could hand this call no candidate it may try and
1757    /// is skipped. The cached listing's Campfires are therefore still visible as far as
1758    /// this call knows, and naming them stale would tell a consumer visibility changed when
1759    /// nothing did. That is the whole reason the listing snapshot is carried forward
1760    /// instead of starting empty.
1761    ///
1762    /// Written after mutation testing showed the other two tests here pass with the
1763    /// snapshot dropped: they take the branch that overwrites it.
1764    #[tokio::test]
1765    async fn a_refresh_that_spends_the_budget_measures_stale_against_the_listing_it_read() {
1766        let clock = TestClock::new();
1767        let server = MockServer::start().await;
1768        // Pass 1 costs two candidates, leaving the rest of the budget for the dock refresh.
1769        let appeared: Vec<i64> = (0..i64::try_from(MAX_CAMPFIRE_CANDIDATES).unwrap() - 2)
1770            .map(|index| 9_000_000 + index)
1771            .collect();
1772        scripted(&server, &[CACHED_A], &[CACHED_A, CACHED_B]).await;
1773        let account = account_on(&server, &clock);
1774        let reference = RecordingRef::from_event(BUCKET, LINE, "chat.line.created");
1775        account
1776            .recordings()
1777            .summarize(&reference)
1778            .await
1779            .unwrap_err();
1780
1781        clock.advance(CAMPFIRE_INDEX_MIN_REFRESH + Duration::from_secs(1));
1782        // The dock now holds exactly the remaining budget, and the listing still holds what
1783        // pass 1 saw. Only the dock is re-read; the listing snapshot is the cached one.
1784        scripted(&server, &appeared, &[CACHED_A, CACHED_B]).await;
1785        let before = paths(&server).await.len();
1786
1787        let unresolved = unresolved_from(
1788            &account
1789                .recordings()
1790                .summarize(&reference)
1791                .await
1792                .unwrap_err(),
1793        );
1794        assert!(
1795            unresolved.refreshed,
1796            "the dock re-read answered newer than the cache"
1797        );
1798        let mut expected = vec![CACHED_A, CACHED_B];
1799        expected.extend(&appeared);
1800        assert_eq!(unresolved.campfire_ids, expected);
1801        assert!(
1802            unresolved.stale_campfire_ids.is_empty(),
1803            "the cached listing still lists both, so neither has been lost from view: {:?}",
1804            unresolved.stale_campfire_ids
1805        );
1806        let after = paths(&server).await;
1807        assert!(
1808            !after[before..].iter().any(|path| path == "/999/chats.json"),
1809            "a listing refresh that could admit no candidate was not paid for"
1810        );
1811    }
1812
1813    /// The stale list is what the conclusion ACTUALLY consulted minus what the refresh
1814    /// shows, so a candidate the refreshed listing still lists is not stale — even though
1815    /// the dock (which never had it) does not name it either.
1816    #[tokio::test]
1817    async fn a_candidate_the_refresh_still_lists_is_not_stale() {
1818        let clock = TestClock::new();
1819        let server = MockServer::start().await;
1820        scripted(&server, &[CACHED_A], &[CACHED_A, CACHED_B]).await;
1821        let account = account_on(&server, &clock);
1822        let reference = RecordingRef::from_event(BUCKET, LINE, "chat.line.created");
1823        account
1824            .recordings()
1825            .summarize(&reference)
1826            .await
1827            .unwrap_err();
1828
1829        clock.advance(CAMPFIRE_INDEX_MIN_REFRESH + Duration::from_secs(1));
1830        scripted(&server, &[APPEARED], &[CACHED_B]).await;
1831
1832        let second = unresolved_from(
1833            &account
1834                .recordings()
1835                .summarize(&reference)
1836                .await
1837                .unwrap_err(),
1838        );
1839        assert!(second.refreshed);
1840        assert_eq!(
1841            second.stale_campfire_ids,
1842            vec![CACHED_A],
1843            "CACHED_B is still listed, so only the dropped dock Campfire is stale"
1844        );
1845    }
1846}