-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathmls_sync.rs
More file actions
5100 lines (4688 loc) · 221 KB
/
Copy pathmls_sync.rs
File metadata and controls
5100 lines (4688 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::{
GroupError, HmacKey, MlsGroup, build_extensions_for_admin_lists_update,
build_extensions_for_metadata_update, build_extensions_for_permissions_update,
build_group_membership_extension,
group_permissions::extract_group_permissions,
intents::{
CommitPendingProposalsIntentData, Installation, IntentError, PostCommitAction,
ProposeGroupContextExtensionsIntentData, ProposeMemberUpdateIntentData,
SendMessageIntentData, SendWelcomesAction, UpdateAdminListIntentData,
UpdateGroupMembershipIntentData, UpdatePermissionIntentData,
},
summary::{MessageIdentifier, MessageIdentifierBuilder, ProcessSummary, SyncSummary},
update_required_capabilities_for_proposals,
validated_commit::{
CommitValidationError, LibXMTPVersion, extract_group_membership, validate_proposal,
},
};
use crate::{
client::ClientError,
context::XmtpSharedContext,
groups::{
group_membership::{GroupMembership, MembershipDiffWithKeyPackages},
intents::{QueueIntent, ReaddInstallationsIntentData, UpdateMetadataIntentData},
mls_ext::{CommitLogStorer, MlsGroupReload},
mls_sync::{
GroupMessageProcessingError::OpenMlsProcessMessage,
update_group_membership::apply_readd_installations_intent,
},
validated_commit::{Inbox, MutableMetadataValidationInfo, ValidatedCommit},
},
identity::{IdentityError, parse_credential},
identity_updates::{IdentityUpdates, load_identity_updates},
intents::ProcessIntentError,
messages::{decoded_message::MessageBody, enrichment::EnrichMessageError},
mls_store::MlsStore,
subscriptions::{LocalEvents, SyncWorkerEvent},
traits::IntoWith,
utils::{
self,
hash::sha256,
id::{calculate_message_id, calculate_message_id_for_intent},
time::hmac_epoch,
},
worker::WorkerKind,
};
use futures::future::try_join_all;
use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use openmls::prelude::BasicCredentialError;
use openmls::{
credentials::BasicCredential,
framing::ProtocolMessage,
group::{
CommitToPendingProposalsError, GroupContext, GroupEpoch, ProcessMessageError, StagedCommit,
ValidationError,
},
key_packages::KeyPackage,
messages::proposals::Proposal,
prelude::{
ExtensionType, Extensions, LeafNodeIndex, MlsGroup as OpenMlsGroup, ProcessedMessage,
ProcessedMessageContent, ProposalType, Sender,
tls_codec::{Error as TlsCodecError, Serialize},
},
treesync::LeafNodeParameters,
};
use openmls_traits::OpenMlsProvider;
use prost::Message;
use prost::bytes::Bytes;
use sha2::Sha256;
use std::{
collections::{HashMap, HashSet, VecDeque},
mem::{Discriminant, discriminant},
ops::RangeInclusive,
time::Duration,
};
use thiserror::Error;
use tracing::debug;
use update_group_membership::apply_update_group_membership_intent;
use xmtp_common::{
Event, ExponentialBackoff, Retry, RetryableError, Strategy, log_event, retry_async,
time::now_ns,
};
use xmtp_configuration::{
GRPC_PAYLOAD_LIMIT, HMAC_SALT, MAX_GROUP_SIZE, MAX_GROUP_SYNC_RETRIES,
MAX_INTENT_PUBLISH_ATTEMPTS, MAX_PAST_EPOCHS, SYNC_BACKOFF_TOTAL_WAIT_MAX_SECS,
SYNC_BACKOFF_WAIT_MS, SYNC_JITTER_MS, SYNC_UPDATE_INSTALLATIONS_INTERVAL_NS,
WELCOME_HPKE_LABEL,
};
use xmtp_content_types::{CodecError, ContentCodec, group_updated::GroupUpdatedCodec};
use xmtp_db::TransactionOutcome::{Continue, Rollback};
use xmtp_db::message_deletion::{QueryMessageDeletion, StoredMessageDeletion};
use xmtp_db::{
Fetch, MlsProviderExt, StorageError, StoreOrIgnore, TransactionOutcome,
group::{ConversationType, StoredGroup},
group_intent::{ID, IntentKind, IntentState, StoredGroupIntent},
group_message::{ContentType, DeliveryStatus, GroupMessageKind, StoredGroupMessage},
remote_commit_log::CommitResult,
sql_key_store,
user_preferences::StoredUserPreferences,
};
use xmtp_db::{NotFound, group_intent::IntentKind::MetadataUpdate};
use xmtp_db::{TransactionalKeyStore, XmtpMlsStorageProvider, refresh_state::HasEntityKind};
use xmtp_db::{XmtpOpenMlsProvider, XmtpOpenMlsProviderRef, prelude::*};
use xmtp_db::{group::GroupMembershipState, group_message::Deletable};
use xmtp_db::{
group_message::MsgQueryArgs,
pending_remove::{PendingRemove, QueryPendingRemove},
};
use xmtp_id::{InboxId, InboxIdRef};
use xmtp_mls_common::group_metadata::extract_group_metadata;
use xmtp_mls_common::group_mutable_metadata::MetadataField;
use xmtp_mls_common::mls_ext::payload_encryption::{
WrapPayloadError, wrap_payload_hpke, wrap_payload_symmetric,
};
use xmtp_proto::types::GroupId;
use xmtp_proto::xmtp::mls::message_contents::content_types::DeleteMessage;
use xmtp_proto::xmtp::mls::{
api::v1::{
GroupMessageInput, WelcomeMessageInput, WelcomeMetadata,
group_message_input::{V1 as GroupMessageInputV1, Version as GroupMessageInputVersion},
welcome_message_input::{
V1 as WelcomeMessageInputV1, Version as WelcomeMessageInputVersion,
WelcomePointer as WelcomePointerInput,
},
},
database::{ProcessPendingSelfRemove, Task as TaskProto, task::Task as TaskKind},
message_contents::{
GroupUpdated, PlaintextEnvelope, WelcomePointer as WelcomePointerProto, group_updated,
plaintext_envelope::{Content, V1, V2},
},
};
use xmtp_proto::{
GroupUpdateDeduper,
types::{Cursor, GroupMessage},
};
use xmtp_proto::{ShortHex, xmtp::mls::message_contents::EncodedContent};
use zeroize::Zeroizing;
pub mod update_group_membership;
#[derive(Debug, Error)]
pub enum GroupMessageProcessingError {
#[error("intent already processed")]
IntentAlreadyProcessed,
#[error("message with cursor [{}] for group [{}] already processed", _0.cursor, xmtp_common::fmt::debug_hex(_0.group_id)
)]
MessageAlreadyProcessed(MessageIdentifier),
#[error("message identifier not found")]
MessageIdentifierNotFound,
#[error("welcome with cursor [{0}] already processed")]
WelcomeAlreadyProcessed(u64),
#[error("[{message_time_ns:?}] invalid sender with credential: {credential:?}")]
InvalidSender {
message_time_ns: u64,
credential: Vec<u8>,
},
#[error("invalid payload")]
InvalidPayload,
#[error("storage error: {0}")]
Storage(#[from] xmtp_db::StorageError),
#[error(transparent)]
Identity(#[from] IdentityError),
#[error("openmls process message error: {0}")]
OpenMlsProcessMessage(
#[from] openmls::prelude::ProcessMessageError<sql_key_store::SqlKeyStoreError>,
),
/// AppDataUpdate-aware processing wrapper error.
///
/// Wraps the same `ProcessMessageError` as the variant above, plus the
/// `ComponentSourceError` that fires when an incoming `AppDataUpdate`
/// payload can't be decoded under our wire format. Kept distinct from
/// `OpenMlsProcessMessage` so the AppData-decode failure mode is
/// greppable in logs.
#[error("app-data process message error: {0}")]
OpenMlsProcessMessageWithAppData(
#[from] super::app_data::ProcessMessageWithAppDataError<sql_key_store::SqlKeyStoreError>,
),
#[error("merge staged commit: {0}")]
MergeStagedCommit(#[from] openmls::group::MergeCommitError<sql_key_store::SqlKeyStoreError>),
#[error("TLS Codec error: {0}")]
TlsError(#[from] TlsCodecError),
#[error("unsupported message type: {0:?}")]
UnsupportedMessageType(Discriminant<ProtocolMessage>),
#[error("commit validation")]
CommitValidation(#[from] CommitValidationError),
#[error("epoch increment not allowed")]
EpochIncrementNotAllowed,
#[error("clear pending commit error: {0}")]
ClearPendingCommit(#[from] sql_key_store::SqlKeyStoreError),
#[error("Serialization/Deserialization Error {0}")]
Serde(#[from] serde_json::Error),
#[error("intent is missing staged_commit field")]
IntentMissingStagedCommit,
#[error("encode proto: {0}")]
EncodeProto(#[from] prost::EncodeError),
#[error("proto decode error: {0}")]
DecodeProto(#[from] prost::DecodeError),
#[error(transparent)]
Intent(#[from] IntentError),
#[error(transparent)]
Codec(#[from] CodecError),
#[error("wrong credential type")]
WrongCredentialType(#[from] BasicCredentialError),
#[error(transparent)]
ProcessIntent(#[from] ProcessIntentError),
#[error(transparent)]
AssociationDeserialization(#[from] xmtp_id::associations::DeserializationError),
#[error(transparent)]
Client(#[from] ClientError),
#[error("Group paused due to minimum protocol version requirement")]
GroupPaused,
#[error("Message epoch [{0}] is too old [{1}]")]
OldEpoch(u64, u64),
#[error("Message epoch [{0}] is greater than group epoch [{1}]")]
FutureEpoch(u64, u64),
#[error(transparent)]
Db(#[from] xmtp_db::ConnectionError),
#[error(transparent)]
Builder(#[from] derive_builder::UninitializedFieldError),
#[error(transparent)]
Diesel(#[from] xmtp_db::diesel::result::Error),
#[error(transparent)]
EnrichMessage(#[from] EnrichMessageError),
#[error("pre-commit proposal phase complete, re-queuing intent")]
PreCommitProposalPhaseComplete,
#[error(transparent)]
Conversion(#[from] xmtp_proto::ConversionError),
/// A successful staged-commit merge by a member that remains in the group
/// must advance the epoch and therefore change the epoch authenticator.
/// If it did not, the group state the commit was merged onto was
/// corrupt/torn (e.g. produced by a cross-process race on a shared MLS
/// DB). Retryable: the enclosing transaction (cursor + merge + commit
/// log) rolls back and the message is reprocessed against settled state.
#[error(
"staged commit merge for group [{group_id}] at sequence [{commit_sequence_id}] reached \
epoch [{epoch}] without advancing the epoch authenticator; refusing to record corrupt \
commit log entry"
)]
EpochAuthenticatorNotAdvanced {
group_id: GroupId,
commit_sequence_id: i64,
epoch: u64,
},
}
impl RetryableError for GroupMessageProcessingError {
fn is_retryable(&self) -> bool {
match self {
Self::Storage(err) => err.is_retryable(),
Self::Diesel(err) => err.is_retryable(),
Self::Identity(err) => err.is_retryable(),
Self::OpenMlsProcessMessage(err) => err.is_retryable(),
Self::OpenMlsProcessMessageWithAppData(err) => match err {
super::app_data::ProcessMessageWithAppDataError::OpenMls(e) => e.is_retryable(),
// Decode failures are wire-format violations from the
// peer — retrying won't help.
super::app_data::ProcessMessageWithAppDataError::AppDataDecode(_) => false,
// Resolved by upgrading, not by retrying. In practice
// this variant never reaches here: the call sites remap
// it to `CommitValidation(ProtocolVersionTooLow)` so
// the pause machinery in `post_process_message` fires.
super::app_data::ProcessMessageWithAppDataError::ProtocolVersionTooLow {
..
} => false,
},
Self::MergeStagedCommit(err) => err.is_retryable(),
Self::ProcessIntent(err) => err.is_retryable(),
Self::CommitValidation(err) => err.is_retryable(),
Self::ClearPendingCommit(err) => err.is_retryable(),
Self::Client(err) => err.is_retryable(),
Self::Db(e) => e.is_retryable(),
Self::EnrichMessage(e) => e.is_retryable(),
Self::IntentAlreadyProcessed
| Self::MessageIdentifierNotFound
| Self::WrongCredentialType(_)
| Self::Codec(_)
| Self::MessageAlreadyProcessed(_)
| Self::WelcomeAlreadyProcessed(_)
| Self::InvalidSender { .. }
| Self::DecodeProto(_)
| Self::InvalidPayload
| Self::Intent(_)
| Self::EpochIncrementNotAllowed
| Self::EncodeProto(_)
| Self::IntentMissingStagedCommit
| Self::Serde(_)
| Self::AssociationDeserialization(_)
| Self::TlsError(_)
| Self::UnsupportedMessageType(_)
| Self::GroupPaused
| Self::FutureEpoch(_, _)
| Self::OldEpoch(_, _)
| Self::PreCommitProposalPhaseComplete => false,
Self::Builder(_) => false,
Self::Conversion(_) => false,
// Retry so the enclosing transaction rolls back (including the
// cursor advance) and the message converges via cursor dedup
// instead of persisting a forked commit log entry.
Self::EpochAuthenticatorNotAdvanced { .. } => true,
}
}
}
impl GroupMessageProcessingError {
/// Route an app-data processing failure into this error type.
///
/// The pre-dispatch floor guard in `process_message_with_app_data`
/// surfaces as the same `ProtocolVersionTooLow` commit-validation
/// error the validator's post-policy floor check emits, so
/// `post_process_message` pauses the group (held cursor,
/// `set_group_paused`) instead of treating it like a wire-format
/// rejection that advances past the commit. Every other variant
/// wraps as `OpenMlsProcessMessageWithAppData`, same as `From`.
/// Use this instead of `?`'s implicit conversion at call sites
/// that can see commits from newer protocol versions.
fn from_app_data_processing(
err: super::app_data::ProcessMessageWithAppDataError<sql_key_store::SqlKeyStoreError>,
) -> Self {
match err {
super::app_data::ProcessMessageWithAppDataError::ProtocolVersionTooLow {
min_version,
..
} => Self::CommitValidation(CommitValidationError::ProtocolVersionTooLow(min_version)),
other => other.into(),
}
}
pub(crate) fn commit_result(&self) -> CommitResult {
use super::app_data::ProcessMessageWithAppDataError;
match self {
GroupMessageProcessingError::OpenMlsProcessMessage(
ProcessMessageError::ValidationError(ValidationError::WrongEpoch),
) => CommitResult::WrongEpoch,
// Treat the AppData-aware wrapper the same as the bare
// OpenMLS error: if it carries a ValidationError(WrongEpoch),
// surface as WrongEpoch; if it carries any other OpenMLS
// error, surface as Undecryptable. Decode failures (the
// AppData-side variant) are treated as Invalid because they
// mean the peer's wire format was wrong.
GroupMessageProcessingError::OpenMlsProcessMessageWithAppData(
ProcessMessageWithAppDataError::OpenMls(ProcessMessageError::ValidationError(
ValidationError::WrongEpoch,
)),
) => CommitResult::WrongEpoch,
GroupMessageProcessingError::OpenMlsProcessMessageWithAppData(
ProcessMessageWithAppDataError::OpenMls(_),
) => CommitResult::Undecryptable,
GroupMessageProcessingError::OpenMlsProcessMessageWithAppData(
ProcessMessageWithAppDataError::AppDataDecode(_),
) => CommitResult::Invalid,
GroupMessageProcessingError::OldEpoch(_, _) => CommitResult::WrongEpoch,
GroupMessageProcessingError::FutureEpoch(_, _) => CommitResult::WrongEpoch,
GroupMessageProcessingError::CommitValidation(_) => CommitResult::Invalid,
GroupMessageProcessingError::OpenMlsProcessMessage(_) => CommitResult::Undecryptable,
_ => CommitResult::Unknown,
}
}
}
#[derive(Debug, Error)]
pub struct IntentResolutionError {
processing_error: GroupMessageProcessingError,
// The next intent state to transition to, if the error is non-retriable.
// Should not be used for retryable errors.
next_intent_state: IntentState,
}
impl std::fmt::Display for IntentResolutionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "IntentValidationError: {}", self.processing_error)
}
}
impl RetryableError for IntentResolutionError {
fn is_retryable(&self) -> bool {
self.processing_error.is_retryable()
}
}
#[derive(Debug)]
pub(crate) struct PublishIntentData {
pub(crate) staged_commit: Option<Vec<u8>>,
pub(crate) post_commit_action: Option<Vec<u8>>,
/// One or more payloads to publish. Most intents have a single payload (commit or message),
/// but proposal intents may have multiple payloads (one per proposal).
pub(crate) payloads_to_publish: Vec<Vec<u8>>,
pub(crate) should_send_push_notification: bool,
pub(crate) group_epoch: u64,
}
#[cfg(any(test, feature = "test-utils"))]
impl PublishIntentData {
#[allow(dead_code)]
pub fn post_commit_data(&self) -> Option<Vec<u8>> {
self.post_commit_action.clone()
}
#[allow(dead_code)]
pub fn staged_commit(&self) -> Option<Vec<u8>> {
self.staged_commit.clone()
}
}
/// The result of processing a single synced/streamed message.
///
/// Carries the `MessageIdentifier` for the consumed message, plus any
/// non-retryable intent-resolution error that moved an own-intent to a terminal
/// `Error` state *without* aborting processing. That error is committed to the
/// intent row, the cursor advances, and processing returns success — so it would
/// otherwise be dropped. We surface it here so the sync summary can report the
/// real cause instead of a misleading "0 failed". `None` for external messages
/// and for intents that succeed or are merely re-queued.
#[derive(Debug)]
pub(crate) struct ProcessedMessageOutcome {
pub(crate) identifier: MessageIdentifier,
pub(crate) intent_error: Option<GroupMessageProcessingError>,
/// True when this message stored a disappearing (expiring) message. The
/// disappearing worker is re-armed *after* the storage transaction commits
/// (see `process_message`), so the worker's `min_expire_at_ns`
/// query is guaranteed to observe the newly written `expire_at_ns`.
pub(crate) disappearing_message_stored: bool,
}
impl ProcessedMessageOutcome {
/// An outcome with no swallowed intent error (external messages, successes,
/// already-processed early returns).
fn new(identifier: MessageIdentifier) -> Self {
Self {
identifier,
intent_error: None,
disappearing_message_stored: false,
}
}
}
impl<Context> MlsGroup<Context>
where
Context: XmtpSharedContext,
{
#[tracing::instrument(err, skip_all, fields(operation = "sync"))]
pub async fn sync(&self) -> Result<SyncSummary, GroupError> {
let conn = self.context.db();
let epoch = self.epoch().await?;
tracing::debug!(
inbox_id = self.context.inbox_id(),
installation_id = %self.context.installation_id(),
group_id = self.group_id.short_hex(),
epoch,
"syncing group",
);
// Also sync the "stitched DMs", if any...
for other_dm in conn.other_dms(&self.group_id)? {
let other_dm = Self::new_from_arc(
self.context.clone(),
other_dm.id,
other_dm.dm_id.clone(),
other_dm.conversation_type,
other_dm.created_at_ns,
);
other_dm.sync_with_conn().await?;
other_dm.maybe_update_installations(None).await?;
}
let sync_summary = self.sync_with_conn().await.map_err(GroupError::from)?;
self.maybe_update_installations(None).await?;
Ok(sync_summary)
}
fn handle_group_paused(&self) -> Result<(), GroupError> {
// Check if group is paused and try to unpause if version requirements are met
let group_id_typed = self.group_id;
if let Some(required_min_version_str) = self
.context
.db()
.get_group_paused_version(&group_id_typed)?
{
tracing::info!(
"Group is paused until version: {}",
required_min_version_str
);
let current_version_str = self.context.version_info().pkg_version();
let current_version = LibXMTPVersion::parse(current_version_str)?;
let required_min_version = LibXMTPVersion::parse(&required_min_version_str)?;
if required_min_version <= current_version {
tracing::info!(
"Unpausing group since version requirements are met. \
Group ID: {}",
hex::encode(self.group_id),
);
self.context.db().unpause_group(&group_id_typed)?;
} else {
tracing::warn!(
"Skipping sync for paused group since version requirements are not met. \
Group ID: {}, \
Required version: {}, \
Current version: {}",
hex::encode(self.group_id),
required_min_version_str,
current_version_str
);
// Skip sync for paused groups
return Err(GroupError::GroupPausedUntilUpdate(required_min_version_str));
}
}
Ok(())
}
/// Sync from the network with the 'conn' (local database).
/// must return a summary of all messages synced, whether they were
/// successful or not.
#[cfg_attr(any(test, feature = "test-utils"), tracing::instrument(err, fields(who = %self.context.inbox_id(), operation = "sync_with_conn")))]
#[cfg_attr(
not(any(test, feature = "test-utils")),
tracing::instrument(err, skip_all, fields(operation = "sync_with_conn"))
)]
pub async fn sync_with_conn(&self) -> Result<SyncSummary, SyncSummary> {
let _mutex = self.mutex.lock().await;
let mut summary = SyncSummary::default();
if !self.is_active().map_err(SyncSummary::other)? {
log_event!(
Event::GroupSyncGroupInactive,
self.context.installation_id(),
group_id = self.group_id
);
return Err(SyncSummary::other(GroupError::GroupInactive));
}
if let Err(e) = self.handle_group_paused() {
if matches!(e, GroupError::GroupPausedUntilUpdate(_)) {
// nothing synced
return Ok(summary);
} else {
return Err(SyncSummary::other(e));
}
}
// Even if publish fails, continue to receiving
let result = self.publish_intents().await;
if let Err(e) = result {
tracing::error!("Sync: error publishing intents {e:?}",);
summary.add_publish_err(e);
}
// Even if receiving fails, we continue to post_commit
// Errors are collected in the summary.
let result = self.receive().await;
match result {
Ok(s) => summary.add_process(s),
Err(e) => {
summary.add_other(e);
// We don't return an error if receive fails, because it's possible this is caused
// by malicious data sent over the network, or messages from before the user was
// added to the group
}
}
let result = self.post_commit().await;
if let Err(e) = result {
tracing::error!("post commit error {e:?}",);
summary.add_post_commit_err(e);
}
if summary.is_errored() {
Err(summary)
} else {
Ok(summary)
}
}
#[cfg_attr(any(test, feature = "test-utils"), tracing::instrument(level = "info", fields(who = %self.context.inbox_id()), skip_all))]
#[cfg_attr(
not(any(test, feature = "test-utils")),
tracing::instrument(level = "trace", skip_all)
)]
pub(crate) async fn sync_until_last_intent_resolved(&self) -> Result<SyncSummary, GroupError> {
// Filter to kinds this build understands: after a downgrade,
// rows written by a newer build would otherwise fail `FromSql`
// and poison the whole query (see `IntentKind::all`).
let intents = self.context.db().find_group_intents(
self.group_id,
Some(vec![IntentState::ToPublish, IntentState::Published]),
Some(IntentKind::all().collect()),
)?;
let Some(intent) = intents.last() else {
return Ok(Default::default());
};
self.sync_until_intent_resolved(intent.id).await
}
/**
* Sync the group and wait for the intent to be deleted
* Group syncing may involve picking up messages unrelated to the intent, so simply checking for errors
* does not give a clear signal as to whether the intent was successfully completed or not.
*
* This method will retry up to `xmtp_configuration::MAX_GROUP_SYNC_RETRIES` times.
*/
#[cfg_attr(any(test, feature = "test-utils"), tracing::instrument(err, level = "info", fields(who = %self.context.inbox_id(), operation = "intent"), skip(self)))]
#[cfg_attr(
not(any(test, feature = "test-utils")),
tracing::instrument(err, level = "trace", skip(self), fields(operation = "intent"))
)]
pub(crate) async fn sync_until_intent_resolved(
&self,
intent_id: ID,
) -> Result<SyncSummary, GroupError> {
log_event!(
Event::GroupSyncStart,
self.context.installation_id(),
group_id = self.group_id
);
let result = self.sync_until_intent_resolved_inner(intent_id).await;
let summary = match &result {
Ok(summary) => Some(summary),
Err(GroupError::Sync(summary)) => Some(&**summary),
Err(GroupError::SyncFailedToWait(summary)) => Some(&**summary),
_ => None,
};
log_event!(
Event::GroupSyncFinished,
self.context.installation_id(),
group_id = self.group_id,
summary = ?summary,
success = result.is_ok()
);
result
}
#[cfg_attr(any(test, feature = "test-utils"), tracing::instrument(level = "info", fields(who = %self.context.inbox_id()), skip(self)))]
#[cfg_attr(
not(any(test, feature = "test-utils")),
tracing::instrument(level = "trace", skip(self))
)]
async fn sync_until_intent_resolved_inner(
&self,
intent_id: ID,
) -> Result<SyncSummary, GroupError> {
let mut summary = SyncSummary::default();
let db = self.context.db();
let time_spent = xmtp_common::time::Instant::now();
let backoff = ExponentialBackoff::builder()
.duration(Duration::from_millis(SYNC_BACKOFF_WAIT_MS.into()))
.total_wait_max(Duration::from_secs(SYNC_BACKOFF_TOTAL_WAIT_MAX_SECS.into()))
.max_jitter(Duration::from_millis(SYNC_JITTER_MS.into()))
.build();
// Return the last error to the caller if we fail to sync
for attempt in 0..MAX_GROUP_SYNC_RETRIES {
let wait_for = backoff
.backoff(attempt + 1, time_spent)
.unwrap_or(Duration::from_millis(50));
log_event!(
Event::GroupSyncAttempt,
self.context.installation_id(),
group_id = self.group_id,
attempt,
backoff = ?wait_for
);
// Accumulate each attempt's outcome into `summary`. The terminal
// GroupSyncFinished event (in sync_until_intent_resolved) is the
// single place the summary is logged — no per-attempt logging here.
match self.sync_with_conn().await {
Ok(s) => summary.extend(s),
Err(s) => summary.extend(s),
}
match Fetch::<StoredGroupIntent>::fetch(&db, &intent_id) {
Ok(Some(StoredGroupIntent {
state: IntentState::Processed,
..
})) => {
// This is expected, we mark intents as processed on success.
return Ok(summary);
}
Ok(None) => {
// This is somewhat expected, we used to delete intents on success.
tracing::warn!(
"Intent was deleted when it should have been marked as processed.\
This is still okay, but unexpected. intent_id: {intent_id}",
);
return Ok(summary);
}
Ok(Some(StoredGroupIntent {
state: IntentState::Error,
kind,
..
})) => {
// The summary itself is logged once by GroupSyncFinished;
// this event only marks which intent errored.
log_event!(
Event::GroupSyncIntentErrored,
self.context.installation_id(),
level = warn,
group_id = self.group_id, intent_id = intent_id,
intent_kind = ?kind
);
return Err(GroupError::from(summary));
}
Ok(Some(StoredGroupIntent { state, kind, .. })) => {
log_event!(
Event::GroupSyncIntentRetry,
self.context.installation_id(),
level = warn, group_id = self.group_id,
intent_id = intent_id, state = ?state, intent_kind = ?kind
);
}
Err(err) => {
tracing::error!("database error fetching intent {err:?}");
summary.add_other(GroupError::Storage(err));
}
};
if attempt + 1 < MAX_GROUP_SYNC_RETRIES {
xmtp_common::time::sleep(wait_for).await;
}
}
Err(GroupError::SyncFailedToWait(Box::new(summary)))
}
fn validate_message_epoch(
inbox_id: InboxIdRef<'_>,
intent_id: i32,
group_epoch: GroupEpoch,
message_epoch: GroupEpoch,
max_past_epochs: usize,
) -> Result<(), GroupMessageProcessingError> {
#[cfg(any(test, feature = "test-utils"))]
utils::test_mocks_helpers::maybe_mock_future_epoch_for_tests()?;
if message_epoch.as_u64() + max_past_epochs as u64 <= group_epoch.as_u64() {
tracing::warn!(
inbox_id,
message_epoch = message_epoch.as_u64(),
group_epoch = group_epoch.as_u64(),
intent_id,
"[{}] message epoch {} is {} or more less than the group epoch {} for intent {}. Retrying message",
inbox_id,
message_epoch,
max_past_epochs,
group_epoch.as_u64(),
intent_id
);
return Err(GroupMessageProcessingError::OldEpoch(
message_epoch.as_u64(),
group_epoch.as_u64(),
));
} else if message_epoch.as_u64() > group_epoch.as_u64() {
// Should not happen, logging proactively
tracing::error!(
inbox_id,
message_epoch = message_epoch.as_u64(),
group_epoch = group_epoch.as_u64(),
intent_id,
"[{}] message epoch {} is greater than group epoch {} for intent {}. Retrying message",
inbox_id,
message_epoch,
group_epoch,
intent_id
);
return Err(GroupMessageProcessingError::FutureEpoch(
message_epoch.as_u64(),
group_epoch.as_u64(),
));
}
Ok(())
}
// This function is intended to isolate the async validation code to
// validate the message and prepare it for database insertion synchronously.
async fn stage_and_validate_intent(
&self,
mls_group: &openmls::group::MlsGroup,
intent: &StoredGroupIntent,
envelope: &GroupMessage,
) -> Result<Option<(StagedCommit, ValidatedCommit)>, IntentResolutionError> {
let GroupMessage {
message, cursor, ..
} = &envelope;
let group_epoch = mls_group.epoch();
let message_epoch = message.epoch();
match intent.kind {
// GCE proposal phase of CommitPendingProposals: no staged_commit means the
// message coming back is our GCE proposal, not a commit. Validate epoch only.
IntentKind::CommitPendingProposals if intent.staged_commit.is_none() => {
Self::validate_message_epoch(
self.context.inbox_id(),
intent.id,
group_epoch,
message_epoch,
MAX_PAST_EPOCHS,
)
.map_err(|err| IntentResolutionError {
processing_error: err,
next_intent_state: IntentState::ToPublish,
})?;
}
IntentKind::KeyUpdate
| IntentKind::UpdateGroupMembership
| IntentKind::UpdateAdminList
| IntentKind::MetadataUpdate
| IntentKind::UpdatePermission
| IntentKind::ReaddInstallations
| IntentKind::CommitPendingProposals
| IntentKind::BootstrapMigration
| IntentKind::AppDataUpdate => {
if let Some(published_in_epoch) = intent.published_in_epoch {
let group_epoch = group_epoch.as_u64() as i64;
let message_epoch = message_epoch.as_u64() as i64;
// TODO(rich): Merge into validate_message_epoch()
if message_epoch != group_epoch {
tracing::warn!(
inbox_id = self.context.inbox_id(),
installation_id = %self.context.installation_id(),
group_id = %self.group_id,
cursor = %cursor,
intent.id,
intent.kind = %intent.kind,
"Intent for msg = [{cursor}] was published in epoch {} with local save intent epoch of {} but group is currently in epoch {}",
message_epoch,
published_in_epoch,
group_epoch
);
let processing_error = if message_epoch < group_epoch {
GroupMessageProcessingError::OldEpoch(
message_epoch as u64,
group_epoch as u64,
)
} else {
GroupMessageProcessingError::FutureEpoch(
message_epoch as u64,
group_epoch as u64,
)
};
return Err(IntentResolutionError {
processing_error,
next_intent_state: IntentState::ToPublish,
});
}
let staged_commit = intent
.staged_commit
.as_ref()
.map_or(
Err(GroupMessageProcessingError::IntentMissingStagedCommit),
|staged_commit| decode_staged_commit(staged_commit),
)
.map_err(|err| {
// If we can't retrieve the cached staged commit from the intent, we can't
// apply it. It is indeterminate whether other members were able to apply it
// or not - if they did apply it, then we are forked.
tracing::error!(
inbox_id = self.context.inbox_id(),
installation_id = %self.context.installation_id(),
group_id = %self.group_id,
cursor = %cursor,
intent_id = intent.id,
intent.kind = %intent.kind,
"Error decoding staged commit for intent, now may be forked: {err:?}",
);
IntentResolutionError {
processing_error: err,
next_intent_state: IntentState::Error,
}
})?;
tracing::info!(
"[{}] Validating commit for intent {}. Message timestamp: ({})/{}",
self.context.inbox_id(),
intent.id,
envelope.timestamp(),
envelope.created_ns
);
// We just published this commit ourselves, so the committer
// is our own leaf — no need to consult the staged commit's
// path update field.
let maybe_validated_commit = ValidatedCommit::from_staged_commit(
&self.context,
&staged_commit,
mls_group.own_leaf_index(),
mls_group,
)
.await;
let validated_commit = match maybe_validated_commit {
Err(err) => {
tracing::error!(
inbox_id = self.context.inbox_id(),
installation_id = %self.context.installation_id(),
group_id = %self.group_id,
cursor = %cursor,
intent.id,
intent.kind = %intent.kind,
"Error validating commit for own message. Intent ID [{}]: {err:?}",
intent.id,
);
return Err(IntentResolutionError {
processing_error: GroupMessageProcessingError::CommitValidation(
err,
),
next_intent_state: IntentState::Error,
});
}
Ok(validated_commit) => validated_commit,
};
return Ok(Some((staged_commit, validated_commit)));
}
}
IntentKind::SendMessage
| IntentKind::ProposeMemberUpdate
| IntentKind::ProposeGroupContextExtensions => {
// Proposals and messages don't produce commits, just validate epoch
Self::validate_message_epoch(
self.context.inbox_id(),
intent.id,
group_epoch,
message_epoch,
MAX_PAST_EPOCHS,
)
.map_err(|err| IntentResolutionError {
processing_error: err,
next_intent_state: IntentState::ToPublish,
})?;
}
}
Ok(None)
}
// Applies the message/commit to the mls group. If it was successfully applied, return Ok(()),
// so that the caller can mark the intent as committed.
// If any error occurs, return an IntentResolutionError with the error, and the next intent state
// to use in the event the error is non-retriable.
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(level = "trace", skip_all)]
fn process_own_message(
&self,
mls_group: &mut OpenMlsGroup,
commit: Option<(StagedCommit, ValidatedCommit)>,
intent: &StoredGroupIntent,
envelope: &GroupMessage,
storage: &impl XmtpMlsStorageProvider,
disappearing_stored: &mut bool,
) -> Result<Option<Vec<u8>>, IntentResolutionError> {
if intent.state == IntentState::Committed
|| intent.state == IntentState::Processed
|| intent.state == IntentState::Error
{
tracing::warn!(
"Skipping already processed intent {} of kind {} because it is in state {:?}",
intent.id,
intent.kind,
intent.state
);
return Err(IntentResolutionError {
processing_error: GroupMessageProcessingError::IntentAlreadyProcessed,
next_intent_state: intent.state,
});
}
// GCE proposal phase of CommitPendingProposals: the GCE proposal was received back
// from the network. Re-queue the intent to create the actual commit in the next sync.
if intent.kind == IntentKind::CommitPendingProposals && commit.is_none() {
tracing::info!(
"CommitPendingProposals: GCE proposal received back, re-queuing to create commit"
);
return Err(IntentResolutionError {
processing_error: GroupMessageProcessingError::PreCommitProposalPhaseComplete,
next_intent_state: IntentState::ToPublish,
});
}
let message_epoch = envelope.message.epoch();
let GroupMessage { cursor, .. } = envelope;
let envelope_timestamp_ns = envelope.timestamp();
tracing::debug!(
inbox_id = self.context.inbox_id(),
installation_id = %self.context.installation_id(),
group_id = %self.group_id,
cursor = %cursor,
intent.id,
intent.kind = %intent.kind,