Skip to main content

xmtp_mls_device_sync/
worker.rs

1use super::{
2    DeviceSyncClient, DeviceSyncError, ReceivedContent, decode_sync_message,
3    preference_sync::apply_preference_updates, selected_sync_group_in, with_plaintext,
4};
5use futures::TryFutureExt;
6use std::{collections::HashSet, sync::Arc, time::Duration};
7use tokio::sync::OnceCell;
8use tracing::instrument;
9use xmtp_common::time::Instant;
10use xmtp_common::{Event, RetryableError};
11use xmtp_db::group_message::{DeliveryStatus, StoredGroupMessage};
12use xmtp_db::prelude::*;
13use xmtp_db::processed_device_sync_messages::SyncMessageKey;
14use xmtp_db::{StorageError, TransactionOutcome::Continue, sync_outbox::has_owed};
15use xmtp_events::{EventFilter, Subscription};
16use xmtp_id::associations::{AssociationState, IdentityAction, verify_updates};
17use xmtp_macro::log_event;
18pub use xmtp_mls_core::metrics::SyncMetric;
19use xmtp_mls_core::{
20    events::{InternalEvent, emit_consent_changes, emit_root_key_changed},
21    worker::{
22        BoxedWorker, NeedsDbReconnect, NewWorker, Worker, WorkerFactory, WorkerKind, WorkerResult,
23        metrics::WorkerMetrics,
24    },
25};
26use xmtp_mls_engine::{
27    groups::context::XmtpSharedContext,
28    subscriptions::incoming::{IncomingCoordinator, IncomingScope},
29};
30use xmtp_mls_identity::{
31    identity_ext::IdentityExt,
32    identity_updates::{
33        IdentityUpdateError, load_identity_updates_for_client, store_association_state,
34    },
35};
36use xmtp_proto::ShortHex;
37use xmtp_proto::xmtp::device_sync::content::{
38    DeviceSyncAcknowledge, PreferenceUpdates as PreferenceUpdatesProto,
39    device_sync_content::Content as ContentProto,
40};
41
42pub(super) fn log_incoming_preference_updates(
43    updates: &[xmtp_proto::xmtp::device_sync::content::PreferenceUpdate],
44) {
45    tracing::info!(update_count = updates.len(), "Incoming preference updates");
46}
47
48const RETRY_FIRST: Duration = Duration::from_secs(1);
49const RETRY_MAX: Duration = Duration::from_secs(10 * 60);
50
51/// 2 s doubling to 10 min.
52fn backoff(n: u32) -> Duration {
53    RETRY_FIRST.saturating_mul(1 << n.min(10)).min(RETRY_MAX)
54}
55
56/// A pass that is owed. Nothing is ever dropped: the work is in the database.
57#[derive(Default)]
58struct Pass {
59    due: Option<Instant>,
60    failures: u32,
61}
62
63/// The receive and outbox passes. Shared by the factory, so a worker rebuilt
64/// after a reconnect keeps their backoffs and rate-limit waits.
65#[derive(Default)]
66struct Passes {
67    inbox: Pass,
68    outbox: Pass,
69}
70
71type SharedPasses = Arc<parking_lot::Mutex<Passes>>;
72
73impl Pass {
74    /// A restart drains what is owed, but not inside a backoff.
75    fn restart(&mut self) {
76        if self.failures == 0 {
77            self.due = Some(Instant::now());
78        }
79    }
80
81    /// A wake does not cut a backoff short.
82    fn wake(&mut self) {
83        if self.failures == 0 {
84            self.due = Some(Instant::now());
85        }
86    }
87
88    fn is_due(&self) -> bool {
89        self.due.is_some_and(|at| at <= Instant::now())
90    }
91
92    // implements: SYNC-033
93    fn finish(
94        &mut self,
95        pass: &'static str,
96        result: Result<(), DeviceSyncError>,
97    ) -> Result<(), DeviceSyncError> {
98        match result {
99            Ok(()) => *self = Self::default(),
100            Err(e) if e.needs_db_reconnect() => return Err(e),
101            Err(e) => {
102                self.failures = self.failures.saturating_add(1);
103                // A retry resends the refused request, so it also waits out
104                // a rate limit's delay.
105                // implements: RATE-041
106                let delay = RetryableError::rate_limit_delay(&e).unwrap_or_default();
107                let wait = backoff(self.failures).max(delay);
108                self.due = Some(xmtp_common::time::saturating_after(Instant::now(), wait));
109                tracing::warn!(error = %e, pass, failures = self.failures, "device sync pass failed; it stays owed");
110            }
111        }
112        Ok(())
113    }
114}
115
116pub struct SyncWorker<Context> {
117    client: DeviceSyncClient<Context>,
118    subscription: Option<Arc<Subscription<InternalEvent>>>,
119    passes: SharedPasses,
120    init: OnceCell<()>,
121    metrics: Arc<WorkerMetrics<SyncMetric>>,
122}
123
124impl<Context> SyncWorker<Context>
125where
126    Context: XmtpSharedContext + 'static,
127{
128    fn new(
129        context: Context,
130        metrics: Option<Arc<WorkerMetrics<SyncMetric>>>,
131        passes: SharedPasses,
132    ) -> Self {
133        let metrics =
134            metrics.unwrap_or_else(|| Arc::new(WorkerMetrics::new(context.installation_id())));
135        let client = DeviceSyncClient::new(context, metrics.clone());
136
137        Self {
138            client,
139            subscription: None,
140            passes,
141            init: OnceCell::new(),
142            metrics,
143        }
144    }
145}
146
147struct Factory<Context> {
148    context: Context,
149    passes: SharedPasses,
150    metrics: Arc<WorkerMetrics<SyncMetric>>,
151}
152
153impl<Context> WorkerFactory for Factory<Context>
154where
155    Context: XmtpSharedContext + 'static,
156{
157    fn create(&self) -> BoxedWorker {
158        Box::new(SyncWorker::new(
159            self.context.clone(),
160            Some(self.metrics.clone()),
161            self.passes.clone(),
162        ))
163    }
164
165    fn kind(&self) -> WorkerKind {
166        WorkerKind::DeviceSync
167    }
168
169    fn event_interest(&self) -> Option<(EventFilter<InternalEvent>, Option<usize>)> {
170        let filter = EventFilter::default().with_internal(|event| {
171            matches!(
172                event,
173                InternalEvent::MessageStored { is_sync: true, .. } | InternalEvent::OutboxChanged
174            )
175        });
176        Some((filter, None))
177    }
178}
179
180impl<Context> NewWorker<Context> for SyncWorker<Context>
181where
182    Context: XmtpSharedContext + 'static,
183{
184    fn factory(context: Context) -> impl WorkerFactory + 'static {
185        Factory {
186            metrics: Arc::new(WorkerMetrics::new(context.installation_id())),
187            context,
188            passes: SharedPasses::default(),
189        }
190    }
191}
192
193#[xmtp_common::async_trait]
194impl<Context> Worker for SyncWorker<Context>
195where
196    Context: XmtpSharedContext + 'static,
197{
198    fn kind(&self) -> WorkerKind {
199        WorkerKind::DeviceSync
200    }
201
202    fn set_subscription(&mut self, subscription: Arc<Subscription<InternalEvent>>) {
203        self.subscription = Some(subscription);
204    }
205
206    fn sync_metrics(&self) -> Option<Arc<WorkerMetrics<SyncMetric>>> {
207        Some(self.metrics.clone())
208    }
209
210    async fn run_tasks(&mut self) -> WorkerResult<()> {
211        self.run().map_err(|e| Box::new(e) as Box<_>).await
212    }
213}
214
215impl<Context> SyncWorker<Context>
216where
217    Context: XmtpSharedContext + 'static,
218{
219    async fn run(&mut self) -> Result<(), DeviceSyncError> {
220        // Keep the large startup future off the worker poll stack.
221        Box::pin(self.sync_init()).await?;
222        // Receipt must outlive each sync call so remote updates can wake this worker.
223        let _receipt = IncomingCoordinator::for_context(&self.client.context)
224            .acquire(IncomingScope::DeviceSyncGroups);
225        self.metrics.increment_metric(SyncMetric::Init);
226
227        // Keep pass futures off the containing worker poll stack.
228        Box::pin(self.run_internal()).await
229    }
230
231    /// Two independent passes: a failing receive cannot block the outbox,
232    /// and the reverse. A wake marks a pass due; the tick re-reads both.
233    async fn run_internal(&mut self) -> Result<(), DeviceSyncError> {
234        use futures::StreamExt;
235        let (base, jitter) = self
236            .client
237            .context
238            .worker_interval(WorkerKind::DeviceSync, Duration::from_secs(20));
239        let mut intervals = xmtp_common::time::jittered_interval_stream(base, jitter);
240        // Poll events while native startup jitter delays the first tick.
241        let mut skip_initial_tick = cfg!(not(target_arch = "wasm32"));
242        let subscription = self
243            .subscription
244            .as_ref()
245            .expect("runner installs subscription")
246            .clone();
247        {
248            let mut passes = self.passes.lock();
249            passes.inbox.restart();
250            passes.outbox.restart();
251        }
252        loop {
253            if self.passes.lock().inbox.is_due() {
254                let result = Box::pin(self.client.process_sync_group_messages()).await;
255                self.passes.lock().inbox.finish("receive", result)?;
256            }
257            if self.passes.lock().outbox.is_due() {
258                let result = Box::pin(self.client.publish_outbox()).await;
259                self.passes.lock().outbox.finish("publish", result)?;
260            }
261            let wait = {
262                let passes = self.passes.lock();
263                [passes.inbox.due, passes.outbox.due]
264                    .into_iter()
265                    .flatten()
266                    .min()
267                    .map(|at| at.saturating_duration_since(Instant::now()))
268            };
269            tokio::select! {
270                event = subscription.next() => {
271                    let Some(event) = event else { break; };
272                    match event.internal {
273                        Some(InternalEvent::MessageStored { is_sync: true, .. }) => {
274                            self.passes.lock().inbox.wake();
275                        }
276                        Some(InternalEvent::OutboxChanged) => self.passes.lock().outbox.wake(),
277                        _ => {}
278                    }
279                }
280                _ = xmtp_common::time::sleep(wait.unwrap_or_default()), if wait.is_some() => {}
281                _ = intervals.next() => {
282                    if skip_initial_tick {
283                        skip_initial_tick = false;
284                        continue;
285                    }
286                    self.passes.lock().inbox.wake();
287                    if has_owed(&self.client.db())? {
288                        self.passes.lock().outbox.wake();
289                    }
290                },
291            }
292        }
293        Ok(())
294    }
295
296    /// Initialize the sync group when the client is registered.
297    #[instrument(level = "trace", skip_all)]
298    async fn sync_init(&mut self) -> Result<(), DeviceSyncError> {
299        let Self { init, client, .. } = &self;
300
301        init.get_or_try_init(|| async {
302            log_event!(
303                Event::DeviceSyncInitializing,
304                self.client.context.installation_id()
305            );
306
307            // The only thing that sync init really does right now is ensures that there's a sync group.
308            if client.primary_sync_group()?.is_none() {
309                log_event!(
310                    Event::DeviceSyncNoPrimarySyncGroup,
311                    self.client.context.installation_id()
312                );
313                // Sync-group creation polls membership publication below this call.
314                let sync_group = Box::pin(client.get_sync_group()).await?;
315                log_event!(
316                    Event::DeviceSyncCreatedPrimarySyncGroup,
317                    self.client.context.installation_id(),
318                    group_id = sync_group.group_id
319                );
320            }
321
322            log_event!(
323                Event::DeviceSyncInitializingFinished,
324                self.client.context.installation_id()
325            );
326
327            Ok(())
328        })
329        .await
330        .copied()
331    }
332}
333
334/// The own inbox's installation set after each own identity update, in
335/// sequence order, with the update's server time.
336struct OwnTimeline {
337    steps: Vec<(i64, HashSet<Vec<u8>>)>,
338}
339
340enum Sender {
341    Member,
342    Gone,
343    NotYetKnown,
344}
345
346impl OwnTimeline {
347    /// Load the own inbox's identity updates from the network, then build the
348    /// timeline. The load also emits own-installation events, which cycle the
349    /// root key on a revocation.
350    async fn load(context: &impl XmtpSharedContext) -> Result<Self, DeviceSyncError> {
351        let db = context.db();
352        let inbox_id = context.inbox_id();
353        load_identity_updates_for_client(context, &db, &[inbox_id]).await?;
354        let updates = db.get_identity_updates(inbox_id, None, None)?;
355        // A cached prefix state is one read.
356        let mut states = vec![];
357        for update in &updates {
358            let Some(cached) = db.read_from_cache(inbox_id, update.sequence_id)? else {
359                break;
360            };
361            states.push(AssociationState::try_from(cached).map_err(StorageError::from)?);
362        }
363        // The rest are verified in one batch, folded from the last cached
364        // state, and cached.
365        let rest = &updates[states.len()..];
366        if !rest.is_empty() {
367            let unverified = rest
368                .iter()
369                .cloned()
370                .map(IdentityExt::to_unverified)
371                .collect::<Result<Vec<_>, _>>()
372                .map_err(IdentityUpdateError::from)?;
373            let verifier = context.scw_verifier();
374            let verified = verify_updates(unverified, &verifier)
375                .await
376                .map_err(IdentityUpdateError::from)?;
377            for (stored, update) in rest.iter().zip(verified) {
378                let state = update
379                    .update_state(states.last().cloned(), update.client_timestamp_ns)
380                    .map_err(IdentityUpdateError::from)?;
381                store_association_state(context, stored.sequence_id, &state)?;
382                states.push(state);
383            }
384        }
385        let steps = updates
386            .iter()
387            .zip(states)
388            .map(|(update, state)| {
389                let installations = state.installation_ids().into_iter().collect();
390                (update.server_timestamp_ns, installations)
391            })
392            .collect();
393        Ok(Self { steps })
394    }
395
396    // implements: SYNC-030
397    fn sender_status(&self, own_inbox: &str, msg: &StoredGroupMessage) -> Sender {
398        if msg.sender_inbox_id != own_inbox {
399            // Sync groups admit only the own inbox already.
400            return Sender::Gone;
401        }
402        let id = &msg.sender_installation_id;
403        // Up to the last update, in sequence order, that the backend timed at
404        // or before the message. Server times need not grow with sequence.
405        let n = self
406            .steps
407            .iter()
408            .rposition(|(at, _)| *at <= msg.sent_at_ns)
409            .map_or(0, |last| last + 1);
410        if n > 0 && self.steps[n - 1].1.contains(id) {
411            Sender::Member
412        } else if self.steps[..n].iter().any(|(_, set)| set.contains(id)) {
413            Sender::Gone
414        } else {
415            Sender::NotYetKnown
416        }
417    }
418}
419
420impl<Context> DeviceSyncClient<Context>
421where
422    Context: XmtpSharedContext,
423{
424    /// Apply every unprocessed sync message whose sender was an own
425    /// installation at its envelope time.
426    // implements: SYNC-016, SYNC-030
427    pub async fn process_sync_group_messages(&self) -> Result<(), DeviceSyncError> {
428        let mut after = None;
429        loop {
430            let page = self
431                .context
432                .db()
433                .unprocessed_sync_group_messages(after.as_ref())?;
434            let Some(last) = page.last() else {
435                return Ok(());
436            };
437            after = Some(SyncMessageKey::of(last));
438            tracing::info!("Processing {} messages.", page.len());
439            // The plaintext and its inner encoding can hold an HMAC root key.
440            // Both are wiped on every path, including skipped messages.
441            let page = with_plaintext(page);
442            // Every message in `page` was stored before this load, so the load
443            // holds every own identity update the backend timed at or before
444            // it, unless a lagging replica serves the read. A failure leaves
445            // every row Pending, and the pass backs off.
446            let own = OwnTimeline::load(&self.context).await?;
447            for (msg, plaintext) in page {
448                // Only this installation's own messages are not yet published,
449                // or failed for good; neither has an envelope time to judge.
450                match msg.delivery_status {
451                    DeliveryStatus::Unpublished => continue,
452                    DeliveryStatus::Failed => {
453                        self.context
454                            .db()
455                            .mark_device_sync_msg_as_processed(&msg.id)?;
456                        continue;
457                    }
458                    DeliveryStatus::Published => {}
459                }
460                match own.sender_status(self.context.inbox_id(), &msg) {
461                    Sender::Member => {}
462                    Sender::Gone => {
463                        tracing::warn!(
464                            group_id = msg.group_id.short_hex(),
465                            "dropping a sync message whose sender was not an own installation when it sent"
466                        );
467                        self.context
468                            .db()
469                            .mark_device_sync_msg_as_processed(&msg.id)?;
470                        continue;
471                    }
472                    // Its registration is not loaded yet: read it again later.
473                    Sender::NotYetKnown => continue,
474                }
475                if let Err(err) = self.apply_message(&msg, &plaintext) {
476                    // implements: SYNC-016 (a storage error leaves the row Pending for the next pass)
477                    // A failed message is non-fatal, but a dropped pool must stop the worker.
478                    if err.needs_db_reconnect() {
479                        return Err(err);
480                    }
481                    log_event!(
482                        Event::DeviceSyncMessageProcessingError,
483                        self.context.installation_id(),
484                        error = %err,
485                        message_id = #msg.id
486                    );
487                }
488            }
489        }
490    }
491
492    /// Apply one sync message and mark it processed, in one transaction.
493    /// Content this client does not support, such as older archive transfer
494    /// content, is marked processed.
495    pub(super) fn apply_message(
496        &self,
497        msg: &StoredGroupMessage,
498        plaintext: &[u8],
499    ) -> Result<(), DeviceSyncError> {
500        let content = decode_sync_message(plaintext);
501        let own = msg.sender_installation_id == self.installation_id().as_slice();
502        let updates = match &content {
503            Some(ReceivedContent(ContentProto::PreferenceUpdates(PreferenceUpdatesProto {
504                updates,
505            }))) => updates.as_slice(),
506            Some(ReceivedContent(ContentProto::Acknowledge(DeviceSyncAcknowledge { .. })))
507            | None => &[],
508        };
509        let msg_type = match &content {
510            Some(ReceivedContent(ContentProto::PreferenceUpdates(_))) => "PreferenceUpdates",
511            Some(ReceivedContent(ContentProto::Acknowledge(_))) => "Acknowledge",
512            None => "Unsupported",
513        };
514        log_event!(
515            Event::DeviceSyncProcessingMessages,
516            self.context.installation_id(),
517            msg_type,
518            external = !own,
519            message_id = #msg.id,
520            group_id = msg.group_id
521        );
522        if !own {
523            log_incoming_preference_updates(updates);
524        }
525        // implements: PROC-036
526        tracing::info!(update_count = updates.len(), "storing preference updates");
527        xmtp_mls_core::state_tx::state_write_with_events(
528            self.context.mls_storage(),
529            self.context.events(),
530            |tx, events| {
531                // Read in this write, so a sync Welcome commits wholly before
532                // or after it.
533                let selected = selected_sync_group_in(tx, self.context.inbox_id())?;
534                let storage = tx.storage();
535                let db = storage.db();
536                let applied =
537                    apply_preference_updates(&db, self.context.inbox_id(), msg, updates, selected)?;
538                emit_consent_changes(&self.context, events, &db, &applied.consent)?;
539                if let Some(marked) = applied.root_key {
540                    emit_root_key_changed(events, &db, marked)?;
541                }
542                db.mark_device_sync_msg_as_processed(&msg.id)?;
543                Ok::<_, xmtp_mls_engine::groups::GroupError>(Continue(()))
544            },
545        )?;
546        for update in updates.iter().filter_map(|update| update.update.as_ref()) {
547            if !own {
548                self.metrics.increment_metric(match update {
549                    super::PreferenceUpdateProto::Consent(_) => SyncMetric::ConsentReceived,
550                    super::PreferenceUpdateProto::Hmac(_) => SyncMetric::HmacReceived,
551                });
552            }
553        }
554        Ok(())
555    }
556}
557
558#[cfg(test)]
559mod startup_tests {
560    use super::*;
561    use xmtp_mls_core::context::CoreContext;
562    use xmtp_mls_engine::groups::test_support::{
563        EngineTestPeer, message_rows::generate_stored_msg,
564    };
565
566    fn idle_worker<C: XmtpSharedContext + 'static>(context: C) -> SyncWorker<C> {
567        SyncWorker::new(context, None, SharedPasses::default())
568    }
569
570    /// A failed pass stays owed and waits out its backoff; a wake does not
571    /// cut the backoff short; a success clears it.
572    // verifies: SYNC-033
573    #[xmtp_common::test(unwrap_try = true)]
574    fn pass_backs_off_and_stays_owed() {
575        let mut pass = Pass::default();
576        pass.restart();
577        assert!(pass.is_due());
578        pass.finish("test", Err(DeviceSyncError::OutboxPageUnpublished))?;
579        assert_eq!(pass.failures, 1);
580        assert!(pass.due.is_some(), "a failed pass stays owed");
581        assert!(!pass.is_due());
582        pass.wake();
583        assert!(!pass.is_due(), "a wake does not cut a backoff short");
584        pass.finish("test", Err(DeviceSyncError::OutboxPageUnpublished))?;
585        assert_eq!(pass.failures, 2);
586        assert!(backoff(2) > backoff(1));
587        pass.finish("test", Ok(()))?;
588        assert_eq!((pass.due, pass.failures), (None, 0));
589        pass.wake();
590        assert!(pass.is_due());
591    }
592
593    /// A pass refused by a rate limit runs again only after the delay: a wake
594    /// or a tick does not cut it short, and neither does a worker rebuilt
595    /// after a reconnect, which shares the passes through the factory. A
596    /// refused publish and a refused own-identity read both wait.
597    // verifies: RATE-041
598    #[xmtp_common::test(unwrap_try = true)]
599    async fn a_rate_limited_pass_waits_out_its_delay() {
600        let alix = EngineTestPeer::new().await;
601        let delay = Duration::from_secs(300);
602        let refused = |method| {
603            xmtp_api::ApiError::Api(xmtp_proto::api::NetworkError::new(
604                xmtp_api_grpc::error::GrpcError::Status(xmtp_api_grpc::error::rate_limited_status(
605                    method, delay,
606                )),
607            ))
608        };
609        let publish = DeviceSyncError::Group(xmtp_mls_engine::groups::GroupError::WrappedApi(
610            refused("publish"),
611        ));
612        let identity = DeviceSyncError::IdentityUpdate(
613            xmtp_mls_identity::identity_updates::IdentityUpdateError::Api(refused(
614                "get_identity_updates",
615            )),
616        );
617        for error in [&publish, &identity] {
618            assert_eq!(RetryableError::rate_limit_delay(error), Some(delay));
619        }
620        let factory = Factory {
621            context: alix.context.clone(),
622            passes: SharedPasses::default(),
623            metrics: Arc::new(WorkerMetrics::new(alix.context.installation_id())),
624        };
625        let before = Instant::now();
626        {
627            let mut passes = factory.passes.lock();
628            passes.outbox.finish("publish", Err(publish))?;
629            passes.inbox.finish("receive", Err(identity))?;
630        }
631        let _rebuilt = factory.create();
632        assert_eq!(
633            Arc::strong_count(&factory.passes),
634            2,
635            "a rebuilt worker shares the passes"
636        );
637        let mut guard = factory.passes.lock();
638        let passes = &mut *guard;
639        for pass in [&mut passes.outbox, &mut passes.inbox] {
640            pass.wake();
641            pass.restart();
642            assert!(!pass.is_due());
643            assert!(pass.due.unwrap() >= before + delay);
644        }
645    }
646
647    /// The sender of a sync message is judged at its envelope time against
648    /// the own identity history.
649    // verifies: SYNC-030
650    #[xmtp_common::test]
651    fn sender_is_judged_at_the_envelope_time() {
652        let set = |ids: &[u8]| ids.iter().map(|id| vec![*id]).collect::<HashSet<_>>();
653        let timeline = OwnTimeline {
654            steps: vec![(10, set(&[1])), (20, set(&[1, 2])), (30, set(&[2]))],
655        };
656        let message = |inbox: &str, installation: u8, sent_at_ns| StoredGroupMessage {
657            sender_inbox_id: inbox.into(),
658            sender_installation_id: vec![installation],
659            sent_at_ns,
660            ..generate_stored_msg(
661                xmtp_proto::types::Cursor(1),
662                xmtp_proto::types::GroupId::from([1; 16]),
663            )
664        };
665        // The backend's clock stepped back: 3 is revoked at 60, then an
666        // update is timed at 50.
667        let stepped_back = OwnTimeline {
668            steps: vec![(40, set(&[3])), (60, set(&[4])), (50, set(&[4]))],
669        };
670        for (at, expected) in [(45, "member"), (55, "gone")] {
671            let status = match stepped_back.sender_status("me", &message("me", 3, at)) {
672                Sender::Member => "member",
673                Sender::Gone => "gone",
674                Sender::NotYetKnown => "not yet known",
675            };
676            assert_eq!(status, expected, "3 at {at} after the step back");
677        }
678        for (inbox, installation, at, expected) in [
679            ("me", 1, 15, "member"),
680            // Sent before its revocation at 30: applied, whenever it is processed.
681            ("me", 1, 29, "member"),
682            ("me", 1, 30, "gone"),
683            ("me", 2, 15, "not yet known"),
684            ("me", 2, 20, "member"),
685            ("me", 3, 40, "not yet known"),
686            ("other", 1, 15, "gone"),
687        ] {
688            let status = match timeline.sender_status("me", &message(inbox, installation, at)) {
689                Sender::Member => "member",
690                Sender::Gone => "gone",
691                Sender::NotYetKnown => "not yet known",
692            };
693            assert_eq!(status, expected, "{inbox} {installation} at {at}");
694        }
695    }
696
697    /// A timeline built from the cache and one verified pass gives each
698    /// prefix the state the resolver gives it, and caches each one.
699    // verifies: SYNC-030
700    #[xmtp_common::test(unwrap_try = true)]
701    async fn timeline_states_match_each_prefix() {
702        use diesel::prelude::*;
703        use xmtp_db::{ConnectionExt, schema::association_state::dsl};
704        let alix1 = EngineTestPeer::new().await;
705        let alix2 = alix1.new_installation().await;
706        let alix3 = alix1.new_installation().await;
707        let db = alix1.context.db();
708        let inbox_id = alix1.context.inbox_id();
709        load_identity_updates_for_client(&alix1.context, &db, &[inbox_id]).await?;
710        let updates = db.get_identity_updates(inbox_id, None, None)?;
711        assert!(updates.len() >= 3);
712        let mut expected = vec![];
713        for update in &updates {
714            let state = xmtp_mls_identity::identity_updates::IdentityUpdates::new(&alix1.context)
715                .get_association_state(&db, inbox_id, Some(update.sequence_id))
716                .await?;
717            let installations: HashSet<_> = state.installation_ids().into_iter().collect();
718            expected.push((update.server_timestamp_ns, installations));
719        }
720        // Only the first prefix stays cached, so the fold starts from it.
721        db.raw_query(|conn| {
722            diesel::delete(
723                dsl::association_state.filter(dsl::sequence_id.gt(updates[0].sequence_id)),
724            )
725            .execute(conn)
726        })?;
727        let timeline = OwnTimeline::load(&alix1.context).await?;
728        assert_eq!(timeline.steps, expected);
729        for update in &updates {
730            assert!(db.read_from_cache(inbox_id, update.sequence_id)?.is_some());
731        }
732        drop((alix2, alix3));
733    }
734
735    /// Closing the subscription stops the worker after its owed passes.
736    #[xmtp_common::test(unwrap_try = true)]
737    async fn closing_subscription_stops_worker() {
738        let alix = EngineTestPeer::new().await;
739        let mut worker = idle_worker(alix.context.clone());
740        let (filter, depth) = SyncWorker::factory(alix.context.clone())
741            .event_interest()
742            .unwrap();
743        let subscription = Arc::new(alix.context.events().subscribe(filter, depth));
744        worker.set_subscription(subscription.clone());
745        subscription.close();
746        xmtp_common::time::timeout(Duration::from_secs(60), worker.run_internal()).await??;
747    }
748}
749
750#[cfg(test)]
751mod tests {
752    use super::SyncWorker;
753    use xmtp_events::{EventBus, EventWriter};
754    use xmtp_mls_core::context::test_support::mock_context;
755    use xmtp_mls_core::events::InternalEvent;
756    use xmtp_mls_core::worker::{NewWorker, WorkerFactory, WorkerKind};
757    use xmtp_mls_engine::groups::test_support::{EngineTestFeatures, MockEngineContext};
758
759    /// The sync worker's event interest, as the runner subscribes with it.
760    fn worker_event_filter(
761        kind: WorkerKind,
762    ) -> Option<(xmtp_events::EventFilter<InternalEvent>, Option<usize>)> {
763        let factory =
764            SyncWorker::<MockEngineContext>::factory(mock_context::<EngineTestFeatures>());
765        assert_eq!(factory.kind(), kind);
766        factory.event_interest()
767    }
768
769    /// The outbox and the sync messages are stored state; the worker wakes
770    /// only for them, and never drops a wake while busy.
771    // verifies: SYNC-029
772    #[xmtp_common::test(unwrap_try = true)]
773    async fn device_sync_wakes_for_sync_messages_and_the_outbox() {
774        let (filter, depth) = worker_event_filter(WorkerKind::DeviceSync).unwrap();
775        assert_eq!(depth, None);
776        let bus = EventBus::new();
777        let subscription = bus.subscribe(filter, depth);
778        let group_id = xmtp_proto::types::GroupId::from([9; 16]);
779        let stored = |is_sync| InternalEvent::MessageStored {
780            group_id,
781            message_id: vec![],
782            expires_at_ns: None,
783            is_sync,
784        };
785        for event in [
786            InternalEvent::PreferencesChanged { updates: vec![] },
787            InternalEvent::GroupJoined {
788                group_id,
789                is_sync: true,
790            },
791            stored(false),
792        ] {
793            bus.emit(None, Some(event));
794        }
795        assert!(subscription.drain().is_empty());
796        for _ in 0..1_000 {
797            bus.emit(None, Some(InternalEvent::OutboxChanged));
798        }
799        bus.emit(None, Some(stored(true)));
800        assert_eq!(subscription.drain().len(), 1_001);
801    }
802}