Skip to main content

xmtp_mls_device_sync/
archive.rs

1use super::DeviceSyncError;
2use futures::{Stream, StreamExt};
3use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
4pub use xmtp_archive::*;
5use xmtp_configuration::LEGACY_GROUP_ID_BYTES;
6use xmtp_db::{
7    StorageError,
8    TransactionOutcome::Continue,
9    consent_record::{ConsentKey, ConsentWrite, Owed, parse_consent_save, write_consent},
10    group::ConversationType,
11    group_message::StoredGroupMessage,
12    message_deletion::StoredMessageDeletion,
13    prelude::*,
14};
15use xmtp_mls_core::{events::InternalEvent, state_tx::state_write, worker::NeedsDbReconnect};
16use xmtp_mls_engine::groups::deletion::{
17    ArchivedSelfDeletions, DiscardEvents, Source, apply_deletion, apply_stored_records,
18    import_record,
19};
20use xmtp_mls_engine::groups::{MlsGroup, context::XmtpSharedContext};
21use xmtp_proto::types::GroupId;
22use xmtp_proto::xmtp::device_sync::{
23    BackupElement, backup_element::Element, consent_backup::ConsentSave,
24};
25
26use xmtp_events::{ArchiveRestored, ClientEvent, EventWriter};
27#[derive(Default)]
28struct ImportContext {
29    changed: bool,
30    /// The import stored a deletion record or marked a row. It is not a
31    /// change other installations are owed, but the app hears of
32    /// it once through `archive.restored`.
33    deletions_stored: bool,
34    /// The archive's usable consent records, applied after all its elements.
35    /// Archive frames are ciphertext and do not compress, so these grow with
36    /// the archive's own size.
37    consent: Vec<ConsentSave>,
38    /// The archive's 16-byte DM groups, whatever their restore did.
39    dm_groups: HashSet<GroupId>,
40    /// Whether the client holds each group the archive's messages name as a
41    /// sync or one-shot conversation.
42    internal: HashMap<GroupId, bool>,
43    /// The archive's deletion messages, which delete a message this import
44    /// creates when its own sender sent them.
45    self_deletions: ArchivedSelfDeletions,
46}
47
48impl ImportContext {
49    fn is_internal(&mut self, db: &impl DbQuery, group_id: GroupId) -> Result<bool, StorageError> {
50        if let Some(internal) = self.internal.get(&group_id) {
51            return Ok(*internal);
52        }
53        let internal = db
54            .find_group(&group_id)?
55            .is_some_and(|group| group.conversation_type.is_virtual());
56        self.internal.insert(group_id, internal);
57        Ok(internal)
58    }
59}
60
61/// Import an archive. `first` reads it once for its deletion messages;
62/// `reopen` then reads it again for the import, so a pre-8.0 self-deletion
63/// is restored whichever comes first, it or its target.
64pub async fn insert_archive<F, Fut>(
65    first: &mut ArchiveImporter,
66    reopen: F,
67    context: &impl XmtpSharedContext,
68) -> Result<(), DeviceSyncError>
69where
70    F: FnOnce() -> Fut,
71    Fut: std::future::Future<Output = Result<ArchiveImporter, ArchiveError>>,
72{
73    let self_deletions = collect_self_deletions(first).await?;
74    let mut importer = reopen().await?;
75    insert_elements(&mut importer, context, self_deletions).await
76}
77
78/// The archive's deletion messages. A read failure fails the scan, so the
79/// import never runs with some of them missing; an element that reads but
80/// does not convert is left to the import, which reports it.
81pub(super) async fn collect_self_deletions<S, E>(
82    elements: &mut S,
83) -> Result<ArchivedSelfDeletions, E>
84where
85    S: Stream<Item = Result<BackupElement, E>> + Unpin,
86{
87    let mut found = ArchivedSelfDeletions::default();
88    while let Some(element) = elements.next().await {
89        if let Some(Element::GroupMessage(save)) = element?.element
90            && let Ok(message) = StoredGroupMessage::try_from(save)
91        {
92            found.note(&message);
93        }
94    }
95    Ok(found)
96}
97
98/// Import archive elements already read, as an archive holding them imports.
99#[cfg(any(test, feature = "test-utils"))]
100#[doc(hidden)]
101pub async fn insert_elements_for_test<S, E>(
102    elements: &mut S,
103    context: &impl XmtpSharedContext,
104) -> Result<(), DeviceSyncError>
105where
106    S: Stream<Item = Result<BackupElement, E>> + Unpin,
107    DeviceSyncError: From<E>,
108{
109    insert_elements(elements, context, ArchivedSelfDeletions::default()).await
110}
111
112// implements: ARCH-027
113pub(super) async fn insert_elements<S, E>(
114    elements: &mut S,
115    context: &impl XmtpSharedContext,
116    self_deletions: ArchivedSelfDeletions,
117) -> Result<(), DeviceSyncError>
118where
119    S: Stream<Item = Result<BackupElement, E>> + Unpin,
120    DeviceSyncError: From<E>,
121{
122    let mut import = ImportContext {
123        self_deletions,
124        ..Default::default()
125    };
126    let mut first_error = None;
127    while let Some(element) = elements.next().await {
128        let element = match element {
129            Ok(element) => element,
130            // A broken stream ends the import.
131            Err(e) => {
132                first_error.get_or_insert(DeviceSyncError::from(e));
133                break;
134            }
135        };
136        // A failed element does not stop the rest: a pre-8.0 archive lists
137        // consent and later groups after a message whose group it left out.
138        if let Err(e) = insert(element, context, &mut import) {
139            if e.needs_db_reconnect() {
140                return Err(e);
141            }
142            first_error.get_or_insert(e);
143        }
144    }
145    // Consent after groups, even after a failed element.
146    let consent = state_write(context.mls_storage(), |tx| {
147        let storage = tx.storage();
148        let db = storage.db();
149        let changed = import_consent(
150            &db,
151            context.inbox_id(),
152            &import,
153            xmtp_common::time::now_ns(),
154        )?;
155        Ok::<_, StorageError>(Continue(changed))
156    });
157    match consent {
158        Ok(changed) => import.changed |= changed.into_continued(),
159        Err(e) if e.db_needs_connection() => return Err(e.into()),
160        Err(e) => {
161            first_error.get_or_insert(e.into());
162        }
163    }
164    let result = first_error.map_or(Ok(()), Err);
165    if import.changed {
166        context.task_channels().mark_notification_changed();
167        context.events().emit(
168            Some(ClientEvent::ArchiveRestored(ArchiveRestored {
169                complete: result.is_ok(),
170            })),
171            // Imported records are owed to the other installations.
172            Some(InternalEvent::OutboxChanged),
173        );
174    } else if import.deletions_stored {
175        context.events().emit(
176            Some(ClientEvent::ArchiveRestored(ArchiveRestored {
177                complete: result.is_ok(),
178            })),
179            None,
180        );
181    }
182    result
183}
184
185fn insert(
186    element: BackupElement,
187    context: &impl XmtpSharedContext,
188    import: &mut ImportContext,
189) -> Result<(), DeviceSyncError> {
190    let Some(element) = element.element else {
191        return Ok(());
192    };
193
194    match element {
195        // An unusable record is dropped here, so each held record is small.
196        Element::Consent(save) => {
197            if parse_consent_save(&save).is_some() {
198                import.consent.push(save);
199            }
200        }
201        // The exporter writes no sync or one-shot conversation, so an import
202        // makes none and adds no message to one: device sync applies only
203        // what the backend delivered.
204        Element::Group(save)
205            if ConversationType::try_from(save.conversation_type())
206                .is_ok_and(|kind| kind.is_virtual()) => {}
207        Element::Group(save) => {
208            // Registered before the restore, so a re-import that finds the
209            // group held combines the same rows.
210            if save.dm_id.is_some()
211                && save.id.len() == LEGACY_GROUP_ID_BYTES
212                && let Ok(id) = GroupId::try_from(save.id.as_slice())
213            {
214                import.dm_groups.insert(id);
215            }
216            import.changed |= MlsGroup::restore_from_archive(context, &save)?;
217        }
218        // implements: ARCH-028
219        Element::MessageDeletion(save) => {
220            let record: StoredMessageDeletion = save.try_into()?;
221            if !import.is_internal(&context.db(), record.group_id)? {
222                import.deletions_stored |= state_write(context.mls_storage(), |tx| {
223                    let stored = import_record(&tx.storage().db(), &DiscardEvents, &record)?;
224                    Ok::<_, StorageError>(Continue(stored))
225                })?
226                .into_continued();
227            }
228        }
229        // implements: ARCH-013, ARCH-028
230        Element::GroupMessage(message) => {
231            // Field 19 makes a new row marked and empty. A known row keeps
232            // its state: archive data changes a row only in the insert that
233            // creates it.
234            let message: StoredGroupMessage = message.try_into()?;
235            if import.is_internal(&context.db(), message.group_id)? {
236                return Ok(());
237            }
238            import.self_deletions.note(&message);
239            let self_deletions = &import.self_deletions;
240            let (inserted, deletions) = state_write(context.mls_storage(), |tx| {
241                let storage = tx.storage();
242                let db = storage.db();
243                let inserted = message.store_or_ignore_changed(&db)?;
244                // A pre-8.0 self-deletion of the row this insert created.
245                let mut deletions = inserted && self_deletions.apply_to_inserted(&db, &message)?;
246                // The evidence is the incoming copy: a stored `Unpublished`
247                // copy of the same id must not hide a later `Published` one.
248                // The stored row itself stays unchanged.
249                deletions |= apply_deletion(&db, &DiscardEvents, &message, Source::Archive)?;
250                if let Some(row) = db.get_group_message(&message.id)? {
251                    deletions |= apply_stored_records(&db, &DiscardEvents, &row)?;
252                }
253                Ok::<_, StorageError>(Continue((inserted, deletions)))
254            })?
255            .into_continued();
256            import.changed |= inserted;
257            import.deletions_stored |= deletions;
258        }
259        _ => {}
260    }
261
262    Ok(())
263}
264
265/// Apply one archive's consent records, after its groups. When the archive
266/// carries a 16-byte DM with a peer, its records for every 16-byte DM held
267/// with that peer and its inbox record for the peer become one record. For
268/// any other peer, a record naming a 16-byte DM held from elsewhere moves to
269/// the peer and merges by time. Every other record merges as named. Returns
270/// whether anything changed.
271// implements: CONS-051, CONS-054, CONS-061
272fn import_consent(
273    db: &impl DbQuery,
274    own_inbox: &str,
275    import: &ImportContext,
276    now_ns: i64,
277) -> Result<bool, StorageError> {
278    // The peers of the 16-byte DMs this archive carries.
279    let mut carried = BTreeSet::new();
280    for id in &import.dm_groups {
281        if let Some((peer, _)) = ConsentKey::group(id.as_ref()).pre8_dm(db, own_inbox)? {
282            carried.insert(peer);
283        }
284    }
285    let mut plain: BTreeMap<ConsentKey, Vec<ConsentSave>> = BTreeMap::new();
286    let mut pre8: BTreeMap<ConsentKey, Vec<ConsentSave>> = BTreeMap::new();
287    for save in &import.consent {
288        // An unusable record is skipped.
289        let Some((key, _)) = parse_consent_save(save) else {
290            continue;
291        };
292        // A record naming a held 16-byte DM is its peer's.
293        let key = key.pre8_dm(db, own_inbox)?.map_or(key, |(peer, _)| peer);
294        let rows = if carried.contains(&key) {
295            pre8.entry(key)
296        } else {
297            plain.entry(key)
298        };
299        rows.or_default().push(save.clone());
300    }
301    for (peer, rows) in pre8 {
302        let combined = pre8::pre8_peer_consent(&peer.entity, &rows);
303        plain.insert(peer, combined.into_iter().collect());
304    }
305    let mut changed = false;
306    for (key, saves) in plain {
307        for save in saves {
308            let Some((_, value)) = parse_consent_save(&save) else {
309                continue;
310            };
311            let write = ConsentWrite::from_archive(value, now_ns);
312            changed |= write_consent(db, &key, write, Owed::Mark)?.is_some();
313        }
314    }
315    Ok(changed)
316}