1#![warn(clippy::unwrap_used)]
6
7use futures::{Stream, StreamExt};
8use prost::Message;
9use tokio::sync::oneshot;
10use xmtp_common::snippet::Snippet;
11use xmtp_proto::backend_v1::ServerEnvelope;
12
13use tracing::instrument;
14use xmtp_db::prelude::*;
15use xmtp_proto::api_client::XmtpMlsStreams;
16
17use stream_all::StreamAllMessages;
18use stream_conversations::StreamConversations;
19
20const DEFAULT_STREAM_CONSENT_STATES: [ConsentState; 2] =
21 [ConsentState::Allowed, ConsentState::Unknown];
22
23use xmtp_mls_engine::subscriptions::barrier;
25pub mod catch_up;
26pub mod local_delivery;
27pub mod message_reader;
28mod stream_all;
29pub mod stream_conversations;
30pub mod stream_failure;
31pub mod stream_messages;
32#[cfg(not(target_arch = "wasm32"))]
34pub mod router_callbacks;
35pub(crate) mod watchdog;
36
37#[cfg(any(test, feature = "test-utils"))]
38use crate::stream_messages::stream_stats::{StreamStatsWrapper, StreamWithStats};
39use xmtp_mls_messages::enrichment::EnrichMessageError;
40
41use thiserror::Error;
42use xmtp_common::{ErrorCode, MaybeSend, RetryableError, StreamHandle, retryable};
43use xmtp_db::{
44 NotFound, StorageError,
45 consent_record::{ConsentState, StoredConsentRecord},
46 group::ConversationType,
47 group_message::StoredGroupMessage,
48};
49use xmtp_events::{EventFilter, Subscription};
50use xmtp_mls_core::events::InternalEvent;
51use xmtp_mls_core::events::PreferenceUpdate;
52use xmtp_mls_engine::groups::{
53 GroupError, GroupMessageProcessingError, MlsGroup, context::XmtpSharedContext,
54};
55use xmtp_mls_messages::decoded_message::{DecodedMessage, DeletedBy};
56
57pub(crate) type Result<T> = std::result::Result<T, SubscribeError>;
58
59#[derive(Debug, Error)]
60pub enum LocalEventError {
61 #[error("Unable to send event: {0}")]
62 Send(String),
63}
64
65impl RetryableError for LocalEventError {
66 fn is_retryable(&self) -> bool {
67 true
68 }
69}
70
71pub trait StreamMessages {
74 fn stream_consent_updates(self) -> impl Stream<Item = Result<Vec<StoredConsentRecord>>>;
76 fn stream_preference_updates(self) -> impl Stream<Item = Result<Vec<PreferenceUpdate>>>;
78 fn stream_message_deletions(self) -> impl Stream<Item = Result<DecodedMessage>>;
80}
81
82impl StreamMessages for Subscription<InternalEvent> {
83 #[instrument(level = "trace", skip_all)]
84 fn stream_consent_updates(self) -> impl Stream<Item = Result<Vec<StoredConsentRecord>>> {
85 futures::stream::unfold(self, |subscription| async move {
86 loop {
87 let item = subscription.next().await?;
88 if let Some(xmtp_events::ClientEvent::Lagged(lagged)) = &item.client {
89 tracing::warn!(discarded = lagged.discarded, "legacy consent stream lagged");
90 }
91 if let Some(InternalEvent::PreferencesChanged { updates, .. }) = item.internal {
92 let records = updates
93 .into_iter()
94 .filter_map(|update| match update {
95 PreferenceUpdate::Consent(record) => Some(record),
96 _ => None,
97 })
98 .collect();
99 return Some((Ok(records), subscription));
100 }
101 }
102 })
103 }
104
105 #[instrument(level = "trace", skip_all)]
106 fn stream_preference_updates(self) -> impl Stream<Item = Result<Vec<PreferenceUpdate>>> {
107 futures::stream::unfold(self, |subscription| async move {
108 loop {
109 let item = subscription.next().await?;
110 if let Some(xmtp_events::ClientEvent::Lagged(lagged)) = &item.client {
111 tracing::warn!(
112 discarded = lagged.discarded,
113 "legacy preference stream lagged"
114 );
115 }
116 if let Some(InternalEvent::PreferencesChanged { updates, .. }) = item.internal {
117 return Some((Ok(updates), subscription));
118 }
119 }
120 })
121 }
122
123 #[instrument(level = "trace", skip_all)]
124 fn stream_message_deletions(self) -> impl Stream<Item = Result<DecodedMessage>> {
125 futures::stream::unfold(self, |subscription| async move {
126 loop {
127 let item = subscription.next().await?;
128 if let Some(xmtp_events::ClientEvent::Lagged(lagged)) = &item.client {
129 tracing::warn!(
130 discarded = lagged.discarded,
131 "legacy deletion stream lagged"
132 );
133 }
134 let decoded = match item.internal {
135 Some(InternalEvent::MessagesDeleted(deleted)) => {
139 let now = xmtp_common::time::now_ns();
140 deletion_items(deleted, |m| m.expire_at_ns.is_some_and(|at| at <= now))
141 }
142 Some(InternalEvent::MessagesExpired(deleted)) => {
143 deletion_items(deleted, |_| true)
144 }
145 _ => continue,
146 };
147 return Some((futures::stream::iter(decoded), subscription));
148 }
149 })
150 .flatten()
151 }
152}
153
154fn deletion_items(
160 deleted: xmtp_mls_core::events::DeletedMessages,
161 is_expired: impl Fn(&StoredGroupMessage) -> bool,
162) -> Vec<Result<DecodedMessage>> {
163 let xmtp_mls_core::events::DeletedMessages {
164 messages,
165 deleted_by_inbox_id,
166 } = deleted;
167 messages
168 .into_iter()
169 .map(|message| {
170 if !is_expired(&message) {
171 return Ok(DecodedMessage::from(message));
172 }
173 let deleted_by = deleted_by_inbox_id
175 .as_deref()
176 .map_or(DeletedBy::Sender, |deleter| {
177 DeletedBy::new(deleter, &message.sender_inbox_id)
178 });
179 Ok(DecodedMessage::placeholder(message, deleted_by))
180 })
181 .collect()
182}
183
184#[derive(thiserror::Error, Debug, ErrorCode)]
185pub enum SubscribeError {
186 #[error(transparent)]
188 #[error_code(inherit)]
189 LocalDelivery(#[from] local_delivery::LocalDeliveryError),
190 #[cfg(not(target_arch = "wasm32"))]
192 #[error(transparent)]
193 Transport(#[from] xmtp_api_backend::TransportError),
194 #[error(transparent)]
198 Group(#[from] Box<GroupError>),
199 #[error(transparent)]
203 NotFound(#[from] NotFound),
204 #[error("group message expected in database but is missing")]
209 GroupMessageNotFound,
210 #[error("processing group message in stream: {0}")]
214 ReceiveGroup(#[from] Box<GroupMessageProcessingError>),
215 #[error(transparent)]
219 Storage(#[from] StorageError),
220 #[error(transparent)]
224 Decode(#[from] prost::DecodeError),
225 #[error(transparent)]
229 ApiClient(#[from] xmtp_api::ApiError),
230 #[error("{0}")]
234 BoxError(Box<dyn RetryableError>),
235 #[error(transparent)]
239 Db(#[from] xmtp_db::ConnectionError),
240 #[error(transparent)]
244 Conversion(#[from] xmtp_proto::ConversionError),
245 #[error(transparent)]
249 Envelope(#[from] xmtp_api_backend::envelope::EnvelopeError),
250 #[error("error occured during subscription {0}")]
252 Enriched(#[from] EnrichMessageError),
253 #[error(transparent)]
259 #[error_code(inherit)]
260 Blocked(#[from] xmtp_mls_server_config::server_configuration::BlockedConnection),
261 #[error("stream went stale: no activity within the idle timeout")]
266 StreamStale,
267}
268
269impl SubscribeError {
270 pub fn dyn_err(other: impl RetryableError + 'static) -> Self {
271 SubscribeError::BoxError(Box::new(other) as _)
272 }
273}
274
275impl From<GroupError> for SubscribeError {
276 fn from(value: GroupError) -> Self {
277 SubscribeError::Group(Box::new(value))
278 }
279}
280
281impl From<GroupMessageProcessingError> for SubscribeError {
282 fn from(value: GroupMessageProcessingError) -> Self {
283 SubscribeError::ReceiveGroup(Box::new(value))
284 }
285}
286
287impl RetryableError for SubscribeError {
288 fn is_retryable(&self) -> bool {
289 use SubscribeError::*;
290 match self {
291 #[cfg(not(target_arch = "wasm32"))]
292 Transport(error) => error.is_retryable(),
293 LocalDelivery(e) => retryable!(e),
294 Group(e) => retryable!(e),
295 GroupMessageNotFound => true,
296 ReceiveGroup(e) => retryable!(e),
297 Storage(e) => retryable!(e),
298 Decode(_) => false,
299 NotFound(e) => retryable!(e),
300 ApiClient(e) => retryable!(e),
301 BoxError(e) => retryable!(e),
302 Db(c) => retryable!(c),
303 Conversion(c) => retryable!(c),
304 Envelope(c) => retryable!(c),
305 Enriched(c) => retryable!(c),
306 Blocked(_) => false,
307 StreamStale => true,
308 }
309 }
310
311 fn rate_limit_delay(&self) -> Option<xmtp_common::time::Duration> {
312 use SubscribeError::*;
313 match self {
314 #[cfg(not(target_arch = "wasm32"))]
315 Transport(error) => error.rate_limit_delay(),
316 Group(e) => e.rate_limit_delay(),
317 ReceiveGroup(e) => e.rate_limit_delay(),
318 ApiClient(e) => e.rate_limit_delay(),
319 LocalDelivery(e) => e.rate_limit_delay(),
320 BoxError(e) => e.rate_limit_delay(),
321 _ => None,
322 }
323 }
324}
325
326impl xmtp_mls_core::worker::NeedsDbReconnect for SubscribeError {
327 #[deny(clippy::wildcard_enum_match_arm)]
330 fn needs_db_reconnect(&self) -> bool {
331 use SubscribeError::*;
332 match self {
333 Group(e) => e.needs_db_reconnect(),
334 Storage(e) => e.db_needs_connection(),
335 LocalDelivery(e) => e.needs_db_reconnect(),
336 Db(c) => c.db_needs_connection(),
337 ReceiveGroup(e) => e.needs_db_reconnect(),
338 Enriched(EnrichMessageError::Storage(e)) => e.db_needs_connection(),
339 Enriched(EnrichMessageError::DbConnection(c)) => c.db_needs_connection(),
340 #[cfg(not(target_arch = "wasm32"))]
341 Transport(..) => false,
342 NotFound(..) | GroupMessageNotFound | Decode(..) | ApiClient(..) | BoxError(..)
343 | Conversion(..) | Envelope(..) | Blocked(..) | StreamStale => false,
344 }
345 }
346}
347
348pub async fn process_streamed_welcome_message<Context>(
350 context: &Context,
351 envelope_bytes: Vec<u8>,
352) -> Result<Vec<MlsGroup<Context>>>
353where
354 Context: XmtpSharedContext + 'static,
355{
356 let wire = ServerEnvelope::decode(envelope_bytes.as_slice())?;
357 let meta = wire
358 .meta
359 .as_ref()
360 .ok_or(xmtp_api::ApiError::InvalidResponse("welcome metadata"))?;
361 let (topic, cursor, _) = xmtp_api_backend::envelope::metadata(
362 meta,
363 xmtp_proto::types::TopicKind::WelcomeMessagesV1,
364 )?;
365 if topic != xmtp_proto::types::Topic::new_welcome_message(context.installation_id()) {
366 return Err(xmtp_api::ApiError::InvalidResponse("welcome installation").into());
367 }
368 barrier::wait_through(context, [(topic, cursor)].into(), None)
369 .await
370 .map_err(|error| {
371 context
372 .server_configuration()
373 .blocked_or(GroupError::from(error))
374 })?;
375 let Some(group) = context.db().find_group_by_sequence_id(cursor)? else {
376 return Ok(Vec::new());
377 };
378 Ok(vec![MlsGroup::new(
379 context.clone(),
380 group.id,
381 group.dm_id,
382 group.conversation_type,
383 group.created_at_ns,
384 )])
385}
386
387pub async fn process_streamed_group_message<Context>(
389 group: &MlsGroup<Context>,
390 envelope_bytes: Vec<u8>,
391) -> Result<Vec<StoredGroupMessage>>
392where
393 Context: XmtpSharedContext + 'static,
394{
395 let wire = ServerEnvelope::decode(envelope_bytes.as_slice())?;
396 let meta = wire
397 .meta
398 .as_ref()
399 .ok_or(xmtp_api::ApiError::InvalidResponse("group metadata"))?;
400 let (topic, cursor, _) =
401 xmtp_api_backend::envelope::metadata(meta, xmtp_proto::types::TopicKind::GroupMessagesV1)?;
402 if topic != xmtp_proto::types::Topic::new_group_message(group.group_id) {
403 return Err(xmtp_api::ApiError::InvalidResponse("group topic").into());
404 }
405 barrier::wait_through(&group.context, [(topic, cursor)].into(), None)
406 .await
407 .map_err(|error| {
408 group
409 .context
410 .server_configuration()
411 .blocked_or(GroupError::from(error))
412 })?;
413 let message = group
414 .context
415 .db()
416 .get_group_message_by_cursor(group.group_id, cursor)?;
417 let current_time_ns = xmtp_common::time::now_ns();
419 Ok(message
420 .filter(|row| {
421 row.expire_at_ns
422 .is_none_or(|deadline| deadline > current_time_ns)
423 })
424 .into_iter()
425 .collect())
426}
427
428#[xmtp_common::span(prefix = "stream")]
431pub async fn stream_conversations<'a, Context>(
432 context: &'a Context,
433 conversation_type: Option<ConversationType>,
434 include_duplicate_dms: bool,
435) -> Result<impl Stream<Item = Result<MlsGroup<Context>>> + use<'a, Context>>
436where
437 Context: XmtpSharedContext + 'static,
438 Context::ApiClient: XmtpMlsStreams,
439{
440 StreamConversations::new(context, conversation_type, include_duplicate_dms, None).await
441}
442
443#[xmtp_common::span(prefix = "stream")]
445pub async fn stream_conversations_owned<Context>(
446 context: Context,
447 conversation_type: Option<ConversationType>,
448 include_duplicate_dms: bool,
449) -> Result<impl Stream<Item = Result<MlsGroup<Context>>> + 'static + use<Context>>
450where
451 Context: XmtpSharedContext + 'static,
452 Context::ApiClient: XmtpMlsStreams,
453{
454 StreamConversations::new_owned(context, conversation_type, include_duplicate_dms, None).await
455}
456
457pub fn stream_conversations_with_callback<Context>(
459 context: Context,
460 keep_alive: impl MaybeSend + 'static,
461 conversation_type: Option<ConversationType>,
462 convo_callback: impl FnMut(Result<MlsGroup<Context>>) + MaybeSend + 'static,
463 on_close: impl FnOnce() + MaybeSend + 'static,
464 include_duplicate_dms: bool,
465) -> impl StreamHandle<StreamOutput = Result<()>>
466where
467 Context: XmtpSharedContext + 'static,
468 Context::ApiClient: XmtpMlsStreams + 'static,
469 Context::MlsStorage: 'static,
470{
471 let cancel = watchdog::StreamCancel::new(&context);
472 watchdog::spawn_watchdog_stream(
479 cancel,
480 "stream_conversations",
481 move || {
482 let _keep_alive = &keep_alive;
483 stream_conversations_owned(context.clone(), conversation_type, include_duplicate_dms)
484 },
485 convo_callback,
486 on_close,
487 )
488}
489
490#[xmtp_common::span(prefix = "stream")]
494pub async fn stream_all_messages<'a, Context>(
495 context: &'a Context,
496 conversation_type: Option<ConversationType>,
497 consent_state: Option<Vec<ConsentState>>,
498) -> Result<impl Stream<Item = Result<StoredGroupMessage>> + use<'a, Context>>
499where
500 Context: XmtpSharedContext + 'static,
501 Context::ApiClient: XmtpMlsStreams + 'static,
502 Context::MlsStorage: 'static,
503{
504 tracing::debug!(
505 inbox_id = context.inbox_id(),
506 installation_id = context.installation_id().as_slice().snippet(),
507 conversation_type = ?conversation_type,
508 "stream all messages"
509 );
510
511 StreamAllMessages::new(context, conversation_type, consent_state).await
512}
513
514#[xmtp_common::span(prefix = "stream")]
516pub async fn stream_all_messages_owned<Context>(
517 context: Context,
518 conversation_type: Option<ConversationType>,
519 consent_state: Option<Vec<ConsentState>>,
520) -> Result<impl Stream<Item = Result<StoredGroupMessage>> + 'static + use<Context>>
521where
522 Context: XmtpSharedContext + 'static,
523 Context::ApiClient: XmtpMlsStreams + 'static,
524 Context::MlsStorage: 'static,
525{
526 tracing::debug!(
527 inbox_id = context.inbox_id(),
528 installation_id = context.installation_id().as_slice().snippet(),
529 conversation_type = ?conversation_type,
530 "stream all messages"
531 );
532
533 StreamAllMessages::new_owned(context, conversation_type, consent_state).await
534}
535
536pub fn stream_consent_with_callback<Context>(
538 context: Context,
539 keep_alive: impl MaybeSend + 'static,
540 mut callback: impl FnMut(Result<Vec<StoredConsentRecord>>) + MaybeSend + 'static,
541 on_close: impl FnOnce() + MaybeSend + 'static,
542) -> impl StreamHandle<StreamOutput = Result<()>>
543where
544 Context: XmtpSharedContext + 'static,
545{
546 let (tx, rx) = oneshot::channel();
547
548 xmtp_common::spawn(
549 Some(rx),
550 xmtp_common::bind_task_hub(async move {
551 let _keep_alive = keep_alive;
552 let cancel = watchdog::StreamCancel::new(&context);
555 let receiver = context.events().subscribe(
556 EventFilter::default().with_internal(|event| {
557 matches!(event, InternalEvent::PreferencesChanged { .. })
558 }),
559 Some(1024),
560 );
561 let stream = receiver.stream_consent_updates();
562
563 futures::pin_mut!(stream);
564 let _ = tx.send(());
565 let cancelled = loop {
566 tokio::select! {
567 _ = cancel.cancelled() => break true,
568 next = stream.next() => match next {
569 Some(message) => callback(message),
570 None => break false,
571 }
572 }
573 };
574 tracing::debug!("`stream_consent` stream ended, dropping stream");
575 let result = watchdog::close_reason(&cancel, cancelled, &mut callback);
576 on_close();
577 result
578 }),
579 )
580}
581
582pub fn stream_preferences_with_callback<Context>(
584 context: Context,
585 keep_alive: impl MaybeSend + 'static,
586 mut callback: impl FnMut(Result<Vec<PreferenceUpdate>>) + MaybeSend + 'static,
587 on_close: impl FnOnce() + MaybeSend + 'static,
588) -> impl StreamHandle<StreamOutput = Result<()>>
589where
590 Context: XmtpSharedContext + 'static,
591{
592 let (tx, rx) = oneshot::channel();
593
594 xmtp_common::spawn(
595 Some(rx),
596 xmtp_common::bind_task_hub(async move {
597 let _keep_alive = keep_alive;
598 let cancel = watchdog::StreamCancel::new(&context);
601 let receiver = context.events().subscribe(
602 EventFilter::default().with_internal(|event| {
603 matches!(event, InternalEvent::PreferencesChanged { .. })
604 }),
605 Some(1024),
606 );
607 let stream = receiver.stream_preference_updates();
608
609 futures::pin_mut!(stream);
610 let _ = tx.send(());
611 let cancelled = loop {
612 tokio::select! {
613 _ = cancel.cancelled() => break true,
614 next = stream.next() => match next {
615 Some(message) => callback(message),
616 None => break false,
617 }
618 }
619 };
620 tracing::debug!("`stream_preferences` stream ended, dropping stream");
621 let result = watchdog::close_reason(&cancel, cancelled, &mut callback);
622 on_close();
623 result
624 }),
625 )
626}
627
628pub fn stream_message_deletions_with_callback<Context>(
630 context: Context,
631 keep_alive: impl MaybeSend + 'static,
632 mut callback: impl FnMut(Result<DecodedMessage>) + MaybeSend + 'static,
633 on_close: impl FnOnce() + MaybeSend + 'static,
634) -> impl StreamHandle<StreamOutput = Result<()>>
635where
636 Context: XmtpSharedContext + 'static,
637{
638 let (tx, rx) = oneshot::channel();
639
640 xmtp_common::spawn(
641 Some(rx),
642 xmtp_common::bind_task_hub(async move {
643 let _keep_alive = keep_alive;
644 let cancel = watchdog::StreamCancel::new(&context);
647 let receiver = context.events().subscribe(
648 EventFilter::default().with_internal(InternalEvent::is_message_deletion),
649 Some(1024),
650 );
651 let stream = receiver.stream_message_deletions();
652
653 futures::pin_mut!(stream);
654 let _ = tx.send(());
655 let cancelled = loop {
656 tokio::select! {
657 _ = cancel.cancelled() => break true,
658 next = stream.next() => match next {
659 Some(message) => callback(message),
660 None => break false,
661 }
662 }
663 };
664 tracing::debug!("`stream_message_deletions` stream ended, dropping stream");
665 let result = watchdog::close_reason(&cancel, cancelled, &mut callback);
666 on_close();
667 result
668 }),
669 )
670}
671
672#[tracing::instrument(level = "trace", skip_all)]
674#[cfg(any(test, feature = "test-utils"))]
675pub async fn stream_all_messages_owned_with_stats<Context>(
676 context: Context,
677 conversation_type: Option<ConversationType>,
678 consent_state: Option<Vec<ConsentState>>,
679) -> Result<impl StreamWithStats<Item = Result<StoredGroupMessage>> + 'static>
680where
681 Context: XmtpSharedContext + 'static,
682 Context::ApiClient: XmtpMlsStreams + 'static,
683 Context::MlsStorage: 'static,
684 <Context::ApiClient as XmtpMlsStreams>::GroupMessageStream: Unpin,
685 <Context::ApiClient as XmtpMlsStreams>::WelcomeMessageStream: Unpin,
686{
687 tracing::debug!(
688 inbox_id = context.inbox_id(),
689 installation_id = context.installation_id().as_slice().snippet(),
690 conversation_type = ?conversation_type,
691 "stream all messages"
692 );
693
694 let stream = StreamAllMessages::new_owned(context, conversation_type, consent_state).await?;
695
696 Ok(StreamStatsWrapper::new(stream))
697}
698
699#[derive(Debug, Clone, Copy)]
700pub enum StreamKind {
701 All,
702 Conversations,
703 Messages,
704}
705
706#[cfg(test)]
707mod tests {
708 #[cfg(not(target_arch = "wasm32"))]
709 mod disconnect_propagation;
710}
711
712#[cfg_attr(not(target_arch = "wasm32"), ctor::ctor(unsafe))]
713#[cfg(all(test, not(target_arch = "wasm32")))]
714fn test_setup() {
715 xmtp_common::logger();
716 let _ = fdlimit::raise_fd_limit();
717}