Skip to main content

xmtp_mls_streams/
stream_conversations.rs

1//! Live conversation notifications from committed group discovery.
2
3use super::{Result, local_delivery::LocalDeliveryError};
4use futures::Stream;
5use std::{
6    collections::{HashMap, VecDeque},
7    pin::Pin,
8    sync::{Arc, Weak},
9    task::{Context, Poll},
10};
11use xmtp_common::{BoxDynStream, time::sleep};
12use xmtp_db::{
13    consent_record::ConsentState,
14    group::{ConversationType, GroupQueryArgs, StoredGroup},
15    prelude::*,
16};
17use xmtp_events::EventFilter;
18use xmtp_mls_core::events::InternalEvent;
19use xmtp_mls_engine::groups::{MlsGroup, context::XmtpSharedContext};
20use xmtp_mls_engine::subscriptions::incoming::{
21    IncomingCoordinator, IncomingLease, IncomingScope, stream_api::GroupSetGate,
22};
23use xmtp_proto::{
24    api_client::XmtpMlsStreams,
25    types::{GroupId, Topic},
26};
27
28const ALL_CONSENT_STATES: [ConsentState; 3] = [
29    ConsentState::Allowed,
30    ConsentState::Unknown,
31    ConsentState::Denied,
32];
33
34/// Local notification history, not durable receipt or processing progress.
35#[derive(Default)]
36struct KnownConversations {
37    /// A later Welcome for an existing group is a new rejoin notification.
38    welcomes: HashMap<GroupId, Option<i64>>,
39    /// Keep one selected group per participant pair for this stream's lifetime.
40    dms: HashMap<String, GroupId>,
41}
42
43impl KnownConversations {
44    /// Exclude groups already committed when the live stream starts.
45    fn from_groups(groups: Vec<StoredGroup>) -> Self {
46        let mut known = Self::default();
47        for group in groups {
48            known.welcomes.insert(group.id, group.sequence_id);
49            if let Some(dm_id) = group.dm_id {
50                known.dms.entry(dm_id).or_insert(group.id);
51            }
52        }
53        known
54    }
55
56    /// Observe committed discovery without letting DM list ranking change its identity.
57    fn observe(&mut self, group: &StoredGroup, include_duplicate_dms: bool) -> bool {
58        if self.welcomes.insert(group.id, group.sequence_id) == Some(group.sequence_id)
59            || ConversationType::virtual_types().contains(&group.conversation_type)
60        {
61            return false;
62        }
63        if !include_duplicate_dms && let Some(dm_id) = &group.dm_id {
64            return *self.dms.entry(dm_id.clone()).or_insert(group.id) == group.id;
65        }
66        true
67    }
68}
69
70/// The groups the stream selects, or none while the group-set generation
71/// equals the one `gate` recorded at its last successful read. A new group, a
72/// later Welcome and a consent change all change the generation. A message
73/// does not, though it can make another group a stitched DM's winner: when
74/// that DM's groups hold different consent, a consent-filtered stream reports
75/// it at the next change of the group set instead of the next pass.
76// implements: PROC-015
77fn changed_groups<C: XmtpSharedContext>(
78    context: &C,
79    query: &GroupQueryArgs,
80    gate: &mut GroupSetGate,
81) -> std::result::Result<Vec<StoredGroup>, xmtp_db::ConnectionError> {
82    let db = context.db();
83    let generation = db.group_set_generation()?;
84    if !gate.changed(generation) {
85        return Ok(Vec::new());
86    }
87    let groups = if query.consent_states.as_ref().is_some_and(Vec::is_empty) {
88        Vec::new()
89    } else {
90        #[cfg(any(test, feature = "test-hooks"))]
91        test_hooks::count_groups_read();
92        db.find_groups(query)?
93    };
94    gate.record(generation);
95    Ok(groups)
96}
97
98/// Notify one subscriber of committed local creation and Welcome joins.
99pub struct StreamConversations<C: XmtpSharedContext> {
100    inner: BoxDynStream<'static, Result<MlsGroup<C>>>,
101    lease: Weak<IncomingLease>,
102}
103
104impl<C: XmtpSharedContext + 'static> StreamConversations<C> {
105    pub async fn new(
106        context: &C,
107        conversation_type: Option<ConversationType>,
108        include_duplicate_dms: bool,
109        consent_states: Option<Vec<ConsentState>>,
110    ) -> Result<Self>
111    where
112        C::ApiClient: XmtpMlsStreams,
113    {
114        Self::new_owned(
115            context.clone(),
116            conversation_type,
117            include_duplicate_dms,
118            consent_states,
119        )
120        .await
121    }
122
123    /// Capture the local discovery baseline before starting the shared receiver.
124    pub async fn new_owned(
125        context: C,
126        conversation_type: Option<ConversationType>,
127        include_duplicate_dms: bool,
128        consent_states: Option<Vec<ConsentState>>,
129    ) -> Result<Self>
130    where
131        C::ApiClient: XmtpMlsStreams,
132    {
133        context.server_configuration().check()?;
134        let events = context.events().subscribe(
135            EventFilter::default().with_internal(|event| {
136                matches!(event, InternalEvent::GroupJoined { is_sync: false, .. })
137            }),
138            Some(10),
139        );
140        let known = KnownConversations::from_groups(context.db().find_groups(GroupQueryArgs {
141            include_sync_groups: true,
142            include_duplicate_dms: true,
143            consent_states: Some(ALL_CONSENT_STATES.to_vec()),
144            ..Default::default()
145        })?);
146        let coordinator = IncomingCoordinator::for_context(&context);
147        let lease = Arc::new(coordinator.acquire_stream(IncomingScope::Topics(vec![
148            Topic::new_welcome_message(context.installation_id()),
149        ])));
150        let query = GroupQueryArgs {
151            conversation_type,
152            consent_states: Some(consent_states.unwrap_or_else(|| ALL_CONSENT_STATES.to_vec())),
153            include_duplicate_dms,
154            ..Default::default()
155        };
156        let observer = Arc::downgrade(&lease);
157        let stream = futures::stream::unfold(
158            Some((
159                context,
160                events,
161                lease,
162                known,
163                VecDeque::new(),
164                query,
165                GroupSetGate::default(),
166            )),
167            |state| async move {
168                let (context, events, lease, mut known, mut ready, query, mut gate) = state?;
169                loop {
170                    if let Err(error) = context.server_configuration().check() {
171                        lease.close();
172                        return Some((Err(error.into()), None));
173                    }
174                    if context.is_closed() {
175                        return None;
176                    }
177                    if let Err(error) = lease.check_recovery() {
178                        lease.close();
179                        return Some((Err(LocalDeliveryError::from(error).into()), None));
180                    }
181                    if let Some(group) = ready.pop_front() {
182                        return Some((
183                            Ok(group),
184                            Some((context, events, lease, known, ready, query, gate)),
185                        ));
186                    }
187                    #[cfg(any(test, feature = "test-hooks"))]
188                    test_hooks::count_pass();
189                    match changed_groups(&context, &query, &mut gate) {
190                        Ok(groups) => {
191                            for group in groups {
192                                if known.observe(&group, query.include_duplicate_dms) {
193                                    ready.push_back(MlsGroup::new(
194                                        context.clone(),
195                                        group.id,
196                                        group.dm_id,
197                                        group.conversation_type,
198                                        group.created_at_ns,
199                                    ));
200                                }
201                            }
202                        }
203                        Err(error) => {
204                            // The database operation has already used its normal
205                            // retry policy. Only the app can start another stream.
206                            lease.close();
207                            return Some((Err(error.into()), None));
208                        }
209                    }
210                    if !ready.is_empty() {
211                        continue;
212                    }
213                    tokio::select! {
214                        _ = context.cancellation_token().cancelled() => {},
215                        _ = lease.changed() => {},
216                        _ = sleep(context.stream_policy().active_database_poll_interval) => {},
217                        event = events.next() => { event?; },
218                    }
219                }
220            },
221        );
222        Ok(Self {
223            inner: Box::pin(stream),
224            lease: observer,
225        })
226    }
227
228    /// Observe the same connection that supplies this conversation stream.
229    pub fn lease(&self) -> Option<Arc<IncomingLease>> {
230        self.lease.upgrade()
231    }
232}
233
234impl<C: XmtpSharedContext> Stream for StreamConversations<C> {
235    type Item = Result<MlsGroup<C>>;
236    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
237        self.inner.as_mut().poll_next(cx)
238    }
239}
240
241#[cfg(any(test, feature = "test-hooks"))]
242mod test_hooks;
243
244#[cfg(test)]
245mod test {
246    use super::test_hooks::{GROUPS_READS, PASSES};
247    use super::*;
248    use futures::StreamExt;
249    use std::cell::Cell;
250    use xmtp_mls_engine::groups::test_support::{EnginePeer, EngineTestPeer};
251
252    /// Idle passes do not reread the groups table, and an invitation that
253    /// changes the group set is still delivered on the next pass.
254    // verifies: CONS-044, PROC-015
255    #[xmtp_common::test(unwrap_try = true)]
256    async fn conversation_stream_rereads_groups_only_after_a_change() {
257        let alix = EngineTestPeer::new().await;
258        let bo = EngineTestPeer::new().await;
259        let passes = || PASSES.with(Cell::get);
260        let reads = || GROUPS_READS.with(Cell::get);
261        let mut stream = StreamConversations::new(&bo.context, None, false, None).await?;
262        tokio::select! {
263            _ = stream.next() => panic!("the stream yielded with no new conversation"),
264            waited = xmtp_common::wait_for_ge(|| async { passes() }, 3) => waited?,
265        }
266        assert_eq!(reads(), 1, "an idle pass reread the groups table");
267
268        let group = alix.create_group(None, None)?;
269        group.add_members(&[bo.context.inbox_id()]).await?;
270        assert_eq!(stream.next().await.unwrap()?.group_id, group.group_id);
271        assert_eq!(reads(), 2);
272    }
273}