1use std::collections::HashMap;
5
6use openmls_rust_crypto::RustCrypto;
7use xmtp_api::ApiError;
8use xmtp_common::RetryableError;
9use xmtp_db::incoming_envelope::{
10 AdmissionResult, IncomingLimits, NetworkEntityKind, NewIncomingEnvelope, StreamTopic,
11};
12use xmtp_db::{NotFound, XmtpOpenMlsProvider};
13use xmtp_proto::backend_v1 as wire;
14use xmtp_proto::types::{
15 IncomingBatchLimits, InstallationId, OrderedEnvelopeBatch, Topic, TopicCursor, TopicKind,
16};
17
18use crate::context::CoreContext;
19use xmtp_id::key_package::{KeyPackageVerificationError, VerifiedKeyPackageV2};
20
21use thiserror::Error;
22use xmtp_db::prelude::*;
23
24pub fn verify_served_key_package(
28 crypto: &RustCrypto,
29 id: &InstallationId,
30 package: &wire::KeyPackage,
31) -> Option<Result<VerifiedKeyPackageV2, KeyPackageVerificationError>> {
32 let verified = VerifiedKeyPackageV2::from_bytes(crypto, &package.key_package_tls_serialized);
33 if verified
34 .as_ref()
35 .is_ok_and(|package| *id != package.installation_public_key)
36 {
37 tracing::warn!("dropping a key package whose leaf names another installation");
38 return None;
39 }
40 Some(verified)
41}
42
43pub type KeyPackageResultsByInstallation =
48 HashMap<Vec<u8>, Result<VerifiedKeyPackageV2, KeyPackageVerificationError>>;
49
50#[derive(Error, Debug)]
51pub enum MlsStoreError {
52 #[error(transparent)]
53 Storage(#[from] xmtp_db::StorageError),
54 #[error(transparent)]
55 Api(#[from] ApiError),
56 #[error(transparent)]
57 Connection(#[from] xmtp_db::ConnectionError),
58 #[error(transparent)]
59 NotFound(#[from] NotFound),
60}
61
62impl RetryableError for MlsStoreError {
63 fn is_retryable(&self) -> bool {
64 match self {
65 Self::Storage(e) => e.is_retryable(),
66 Self::Api(e) => e.is_retryable(),
67 Self::Connection(e) => e.is_retryable(),
68 Self::NotFound(e) => e.is_retryable(),
69 }
70 }
71
72 fn rate_limit_delay(&self) -> Option<xmtp_common::time::Duration> {
73 match self {
74 Self::Api(e) => e.rate_limit_delay(),
75 _ => None,
76 }
77 }
78}
79
80impl crate::worker::NeedsDbReconnect for MlsStoreError {
81 #[deny(clippy::wildcard_enum_match_arm)]
84 fn needs_db_reconnect(&self) -> bool {
85 match self {
86 Self::Storage(s) => s.db_needs_connection(),
87 Self::Connection(c) => c.db_needs_connection(),
88 Self::Api(_) | Self::NotFound(_) => false,
89 }
90 }
91}
92
93#[derive(Clone)]
94pub struct MlsStore<Context> {
95 context: Context,
96}
97
98#[derive(Debug)]
100pub struct ReceivedPage {
101 pub admissions: Vec<(Topic, AdmissionResult)>,
103 pub has_more: bool,
105}
106
107fn stream_topic(topic: &Topic) -> Result<StreamTopic, ApiError> {
108 let kind = match topic.kind() {
109 TopicKind::GroupMessagesV1 => NetworkEntityKind::Group,
110 TopicKind::WelcomeMessagesV1 => NetworkEntityKind::Welcome,
111 TopicKind::IdentityUpdatesV1 => NetworkEntityKind::Identity,
112 _ => return Err(ApiError::InvalidRequest("incoming topic kind")),
113 };
114 Ok(StreamTopic {
115 entity_id: topic.identifier().to_vec(),
116 kind,
117 })
118}
119
120impl<Context> MlsStore<Context> {
121 pub fn new(context: Context) -> Self {
122 Self { context }
123 }
124}
125
126impl<Context> MlsStore<Context>
127where
128 Context: CoreContext,
129{
130 pub fn received_cursors(&self, topics: &[Topic]) -> Result<TopicCursor, MlsStoreError> {
132 let conn = self.context.db();
133 topics
134 .iter()
135 .map(|topic| {
136 Ok((
137 topic.clone(),
138 conn.topic_progress(&stream_topic(topic)?)?.received,
139 ))
140 })
141 .collect()
142 }
143
144 pub fn admit_incoming_batch(
147 &self,
148 batch: &OrderedEnvelopeBatch,
149 limits: IncomingLimits,
150 ) -> Result<AdmissionResult, MlsStoreError> {
151 let topic = stream_topic(&batch.topic)?;
152 let bytes = batch.envelopes.iter().try_fold(0u64, |bytes, envelope| {
153 bytes.checked_add(envelope.raw().len() as u64)
154 });
155 if batch.envelopes.len() as u64 > limits.batch.rows
156 || bytes.is_none_or(|bytes| bytes > limits.batch.bytes)
157 {
158 return Err(
159 ApiError::Envelope(xmtp_api_backend::envelope::EnvelopeError::Capacity).into(),
160 );
161 }
162 let mut previous = batch.after;
163 let mut rows = Vec::with_capacity(batch.envelopes.len());
164 for envelope in &batch.envelopes {
165 let meta = envelope
166 .meta()
167 .ok_or(ApiError::InvalidResponse("incoming metadata"))?;
168 let (envelope_topic, sequence_id, _) =
169 xmtp_api_backend::envelope::metadata(meta, batch.topic.kind())
170 .map_err(ApiError::from)?;
171 if envelope_topic != batch.topic || sequence_id <= previous {
172 return Err(ApiError::InvalidResponse("incoming batch order").into());
173 }
174 previous = sequence_id;
175 rows.push(NewIncomingEnvelope {
176 sequence_id,
177 envelope: envelope.raw().to_vec(),
178 });
179 }
180 let admitted = crate::state_tx::state_write(self.context.mls_storage(), |tx| {
181 let admitted =
182 tx.storage()
183 .db()
184 .admit_ordered_batch(&topic, batch.after, &rows, limits)?;
185 Ok::<_, xmtp_db::StorageError>(xmtp_db::TransactionOutcome::Continue(admitted))
186 })?
187 .into_continued();
188 Ok(admitted)
189 }
190
191 pub async fn receive_topics_once(
193 &self,
194 topics: &[Topic],
195 limits: IncomingLimits,
196 ) -> Result<ReceivedPage, MlsStoreError> {
197 let cursors = self.received_cursors(topics)?;
198 self.receive_topics_once_from(cursors, limits).await
199 }
200
201 pub async fn receive_topics_once_from(
204 &self,
205 cursors: TopicCursor,
206 limits: IncomingLimits,
207 ) -> Result<ReceivedPage, MlsStoreError> {
208 let rows = limits
209 .batch
210 .rows
211 .min(limits.topic.rows)
212 .min(limits.kind.rows)
213 .min(u64::from(self.context.stream_policy().max_fetched_rows));
214 let bytes = limits
215 .batch
216 .bytes
217 .min(limits.topic.bytes)
218 .min(limits.kind.bytes)
219 .min(self.context.stream_policy().max_fetched_bytes);
220 let page = self
221 .context
222 .api()
223 .query_ordered_page(
224 cursors,
225 rows.min(self.context.api().limits().max_query_limit as u64) as u32,
226 IncomingBatchLimits {
227 max_rows: usize::try_from(rows).unwrap_or(usize::MAX),
228 max_bytes: usize::try_from(bytes).unwrap_or(usize::MAX),
229 },
230 )
231 .await?;
232 let mut admissions = Vec::with_capacity(page.batches.len());
233 for batch in page.batches {
234 let admitted = self.admit_incoming_batch(&batch, limits)?;
235 admissions.push((batch.topic, admitted));
236 }
237 Ok(ReceivedPage {
238 admissions,
239 has_more: page.has_more,
240 })
241 }
242
243 #[tracing::instrument(level = "trace", skip_all)]
245 pub async fn get_key_packages_for_installation_ids(
246 &self,
247 installation_ids: Vec<Vec<u8>>,
248 ) -> Result<KeyPackageResultsByInstallation, MlsStoreError> {
249 let installation_ids = installation_ids
250 .into_iter()
251 .map(InstallationId::try_from)
252 .collect::<Result<Vec<_>, _>>()
253 .map_err(ApiError::from)?;
254 let key_package_results = self
255 .context
256 .api()
257 .fetch_key_packages(&installation_ids)
258 .await?;
259
260 let crypto_provider = XmtpOpenMlsProvider::<()>::new_crypto();
261
262 let results: KeyPackageResultsByInstallation = key_package_results
263 .iter()
264 .filter_map(|(id, package)| {
265 verify_served_key_package(&crypto_provider, id, package.as_ref()?)
266 .map(|result| (id.to_vec(), result))
267 })
268 .collect();
269
270 Ok(results)
271 }
272}
273
274#[cfg(all(test, not(target_arch = "wasm32")))]
277mod disconnect_propagation_tests {
278 use super::MlsStoreError;
281 use crate::reconnect::NeedsDbReconnect;
282 use xmtp_db::{ConnectionError, PlatformStorageError, StorageError};
283
284 fn disconnect_storage() -> StorageError {
286 StorageError::Platform(PlatformStorageError::PoolNeedsConnection)
287 }
288
289 fn disconnect_connection() -> ConnectionError {
291 ConnectionError::Platform(PlatformStorageError::PoolNeedsConnection)
292 }
293
294 fn benign_storage() -> StorageError {
296 StorageError::InvalidHmacLength
297 }
298
299 #[xmtp_common::test]
300 fn mls_store_error_forwards_disconnect() {
301 assert!(MlsStoreError::Storage(disconnect_storage()).needs_db_reconnect());
302 assert!(MlsStoreError::Connection(disconnect_connection()).needs_db_reconnect());
303 assert!(!MlsStoreError::Storage(benign_storage()).needs_db_reconnect());
304 }
305}