Skip to main content

xmtp_mls_streams/
catch_up.rs

1//! Bounded catch-up through the shared receiver and fixed processing barriers.
2
3use std::collections::{HashMap, HashSet};
4use xmtp_common::{
5    ErrorCode, RetryableError,
6    time::{Duration, Instant, now_ns},
7};
8use xmtp_db::{
9    delivery::{DeliveryScope, QueryDelivery},
10    group::{ConversationType, GroupQueryArgs},
11    incoming_envelope::{QueryIncomingEnvelope, StreamTopic},
12    prelude::*,
13};
14use xmtp_mls_engine::groups::{GroupError, context::XmtpSharedContext};
15use xmtp_mls_engine::subscriptions::barrier::{BarrierError, receive_with_welcomes_until};
16
17/// Committed catch-up observations; fixed processing predicates determine completion.
18#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
19pub struct CatchUpSummary {
20    /// Newly deliverable retained rows observed in enrolled groups during the run.
21    pub messages: u64,
22    /// Newly discovered non-virtual conversations within the enrolled scope.
23    pub conversations: u64,
24    /// Enrolled groups with a newly recorded terminal rejection.
25    pub failed: u64,
26    /// True only when every fixed processing obligation completed.
27    pub completed: bool,
28}
29
30#[derive(Debug, thiserror::Error, ErrorCode)]
31pub enum CatchUpError {
32    /// Target discovery or storage failed. May be retryable.
33    #[error(transparent)]
34    #[error_code(inherit)]
35    Group(#[from] GroupError),
36    /// Fixed targets remain unfinished. Partial committed progress is retained. May be retryable.
37    #[error("Catch-up did not complete: {summary:?}")]
38    Incomplete {
39        /// Partial progress remains committed even when the barrier fails.
40        summary: CatchUpSummary,
41        /// Every unfinished fixed-target obligation and its typed cause.
42        causes: Vec<BarrierError>,
43    },
44}
45
46impl RetryableError for CatchUpError {
47    fn is_retryable(&self) -> bool {
48        match self {
49            Self::Group(error) => error.is_retryable(),
50            Self::Incomplete { causes, .. } => causes.iter().any(RetryableError::is_retryable),
51        }
52    }
53
54    fn rate_limit_delay(&self) -> Option<xmtp_common::time::Duration> {
55        match self {
56            Self::Group(error) => error.rate_limit_delay(),
57            Self::Incomplete { causes, .. } => causes
58                .iter()
59                .filter_map(RetryableError::rate_limit_delay)
60                .max(),
61        }
62    }
63}
64
65impl From<xmtp_mls_server_config::server_configuration::BlockedConnection> for CatchUpError {
66    fn from(error: xmtp_mls_server_config::server_configuration::BlockedConnection) -> Self {
67        Self::Group(error.into())
68    }
69}
70
71/// Process fixed starting targets and only the discoveries from the enrolled Welcomes.
72pub async fn catch_up_to_live<C: XmtpSharedContext + 'static>(
73    context: &C,
74    timeout: Option<Duration>,
75) -> Result<CatchUpSummary, CatchUpError> {
76    catch_up_once(context, timeout)
77        .await
78        .map_err(|error| context.server_configuration().blocked_or(error))
79}
80
81async fn catch_up_once<C: XmtpSharedContext + 'static>(
82    context: &C,
83    timeout: Option<Duration>,
84) -> Result<CatchUpSummary, CatchUpError> {
85    // A client with a blocked connection sends no topic or credential to the backend.
86    context
87        .server_configuration()
88        .check()
89        .map_err(GroupError::from)?;
90    let timeout = timeout.unwrap_or(context.stream_policy().barrier_timeout);
91    let started = Instant::now();
92    let query = || GroupQueryArgs {
93        include_sync_groups: true,
94        include_duplicate_dms: true,
95        ..Default::default()
96    };
97    let db = context.db();
98    let mut position = db.current_delivery_cursor().map_err(GroupError::from)?;
99    let before = db.find_groups(query()).map_err(GroupError::from)?;
100    let before_ids: HashSet<_> = before.iter().map(|group| group.id).collect();
101    let previous_rejections: HashMap<_, _> = before
102        .iter()
103        .map(|group| {
104            Ok((
105                group.id,
106                db.read_last_rejection(&StreamTopic::group(group.id))?
107                    .map(|entry| entry.sequence_id)
108                    .unwrap_or_default(),
109            ))
110        })
111        .collect::<Result<_, xmtp_db::StorageError>>()
112        .map_err(GroupError::from)?;
113    let run = receive_with_welcomes_until(
114        context,
115        before_ids.iter().copied().collect(),
116        None,
117        started + timeout,
118    )
119    .await;
120    let causes: Vec<_> = run.result.err().into_iter().collect();
121    let enrolled: HashSet<_> = run.group_ids.iter().copied().collect();
122    let groups: Vec<_> = db
123        .find_groups(query())
124        .map_err(GroupError::from)?
125        .into_iter()
126        .filter(|group| enrolled.contains(&group.id))
127        .collect();
128    let upper = db.current_delivery_cursor().map_err(GroupError::from)?;
129    let settings = context.stream_policy();
130    let mut summary = CatchUpSummary {
131        conversations: groups
132            .iter()
133            .filter(|group| {
134                !before_ids.contains(&group.id)
135                    && !ConversationType::virtual_types().contains(&group.conversation_type)
136            })
137            .count() as u64,
138        completed: causes.is_empty(),
139        ..Default::default()
140    };
141    for group in &groups {
142        if let Some(rejection) = db
143            .read_last_rejection(&StreamTopic::group(group.id))
144            .map_err(GroupError::from)?
145            && rejection.sequence_id
146                > previous_rejections
147                    .get(&group.id)
148                    .copied()
149                    .unwrap_or_default()
150        {
151            summary.failed += 1;
152        }
153    }
154    loop {
155        let rows = db
156            .replay_delivery_messages_bounded(
157                position,
158                &DeliveryScope::Groups(run.group_ids.clone()),
159                now_ns(),
160                settings.max_local_read_rows,
161                settings.max_local_read_bytes,
162            )
163            .map_err(GroupError::from)?;
164        if rows.is_empty() {
165            break;
166        }
167        let mut reached_upper = false;
168        for row in rows {
169            if row.cursor.delivery_sequence > upper.delivery_sequence {
170                reached_upper = true;
171                break;
172            }
173            position = row.cursor;
174            summary.messages += 1;
175        }
176        if reached_upper || position.delivery_sequence >= upper.delivery_sequence {
177            break;
178        }
179    }
180    if !causes.is_empty() {
181        return Err(CatchUpError::Incomplete { summary, causes });
182    }
183    Ok(summary)
184}