Skip to main content

xmtp_mls/
client.rs

1pub use crate::core::config::DeviceSync;
2use crate::subscriptions::catch_up::{CatchUpError, CatchUpSummary};
3#[cfg(not(target_arch = "wasm32"))]
4use crate::subscriptions::router_callbacks::{self, ApiClientIdentity};
5#[cfg(any(test, feature = "test-utils"))]
6use crate::subscriptions::stream_messages::stream_stats::StreamWithStats;
7use crate::{
8    attachments::Attachments,
9    context::XmtpSharedContext,
10    groups::{
11        ConversationListItem, GroupError, MlsGroup, group_permissions::PolicySet,
12        welcome_sync::WelcomeService,
13    },
14    identity::{Identity, IdentityError, parse_credential},
15    identity_updates::{
16        IdentityUpdateError, IdentityUpdates, load_identity_updates,
17        load_identity_updates_for_client,
18    },
19    inbox_handles::{self, HandleError, IdentityTarget, account_targets, resolve_verified_in},
20    mls_store::{KeyPackageResultsByInstallation, MlsStore, MlsStoreError},
21    server_configuration::{BlockedConnection, ServerConfigError},
22    subscriptions::{
23        LocalEventError,
24        internal::{emit_consent_changes, emit_deleted_messages},
25    },
26    utils::VersionInfo,
27    worker::device_sync::{DeviceSyncClient, worker::SyncMetric},
28    worker::{WorkerRunner, metrics::WorkerMetrics},
29};
30use crate::{
31    core::events::PreferenceUpdate,
32    subscriptions::{self, SubscribeError},
33};
34use crate::{
35    groups::welcome_sync::GroupSyncSummary,
36    identity_updates::{batch_get_association_state_with_verifier, get_creation_signature_kind},
37    messages::{
38        decoded_message::DecodedMessage,
39        enrichment::{EnrichMessageError, enrich_messages},
40    },
41};
42use futures::Stream;
43use notifications::{NotificationConfig, NotificationError, NotificationState};
44use openmls::prelude::tls_codec::Error as TlsCodecError;
45use std::{
46    collections::HashMap,
47    sync::{Arc, atomic::Ordering},
48};
49use thiserror::Error;
50use xmtp_api::{ApiClientWrapper, XmtpApi};
51use xmtp_common::{ErrorCode, Event, Retry, retry_async, retryable};
52use xmtp_common::{MaybeSend, StreamHandle};
53use xmtp_configuration::{
54    CONVERSATION_LIST_DEFAULT_LIMIT, CREATE_PQ_KEY_PACKAGE_EXTENSION,
55    KEY_PACKAGE_ROTATION_INTERVAL_NS, LOCAL_PAGE_MAX_LIMIT,
56};
57use xmtp_cryptography::signature::IdentifierValidationError;
58use xmtp_db::TransactionOutcome::Continue;
59use xmtp_db::consent_record::StoredConsentRecord;
60use xmtp_db::{
61    ConnectionExt, NotFound, StorageError, TransactionOutcome, XmtpDb,
62    consent_record::{
63        ConsentActError, ConsentKey, ConsentState, ConsentType, ConsentWrite, Decision, Owed,
64        conversation_consent, write_consent,
65    },
66    db_connection::DbConnection,
67    encrypted_store::conversation_list::ConversationListItem as DbConversationListItem,
68    group::{ConversationType, GroupQueryArgs},
69    group_message::StoredGroupMessage,
70    identity::StoredIdentity,
71};
72use xmtp_db::{group::GroupQueryOrderBy, prelude::*};
73use xmtp_events::DeletionCause;
74use xmtp_id::associations::handle::Handle;
75use xmtp_id::key_package::KeyPackageVerificationError;
76use xmtp_id::{
77    AsIdRef, InboxId, InboxIdRef, InboxOwner,
78    associations::{
79        AssociationError, AssociationState, Identifier, MemberIdentifier, SignatureError,
80        builder::{SignatureRequest, SignatureRequestError},
81    },
82    scw_verifier::SmartContractSignatureVerifier,
83};
84use xmtp_macro::log_event;
85use xmtp_mls_group_state::{
86    group::{DMMetadataOptions, GroupMetadataOptions},
87    group_metadata::DmMembers,
88    group_mutable_metadata::MessageDisappearingSettings,
89};
90pub use xmtp_mls_notifications::client as notifications;
91#[cfg(not(target_arch = "wasm32"))]
92use xmtp_proto::api_client::XmtpMlsBidiStreams;
93use xmtp_proto::api_client::XmtpMlsStreams;
94use xmtp_proto::types::InstallationId;
95use xmtp_proto::{
96    api::HasStats,
97    api_client::{ApiStats, IdentityStats, XmtpBackendClient},
98};
99
100use xmtp_proto::types::GroupId;
101
102mod conversations;
103mod error;
104mod identity;
105mod registration;
106mod streams;
107mod sync;
108
109pub use error::{ClientError, stream_failure_details};
110
111/// Enum representing the network the Client is connected to
112#[derive(Clone, Copy, Default, Debug)]
113pub enum Network {
114    Local(&'static str),
115    #[default]
116    Dev,
117    Prod,
118}
119
120/// Timeout for waiting until a registration publish can be read.
121#[derive(Debug, Clone)]
122pub struct VisibilityConfirmationOptions {
123    pub timeout_ms: u64,
124}
125
126impl Default for VisibilityConfirmationOptions {
127    fn default() -> Self {
128        Self { timeout_ms: 30_000 }
129    }
130}
131
132/// An app's consent decision about one entity. It carries no
133/// time: the client times it.
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub struct ConsentAct {
136    pub entity_type: ConsentType,
137    pub entity: String,
138    pub state: ConsentState,
139}
140
141impl ConsentAct {
142    pub fn new(entity_type: ConsentType, state: ConsentState, entity: String) -> Self {
143        Self {
144            entity_type,
145            entity,
146            state,
147        }
148    }
149}
150
151/// Clients manage access to the network, identity, and data store
152pub struct Client<Context> {
153    pub context: Context,
154    pub installation_id: InstallationId,
155    pub(crate) workers: Arc<WorkerRunner>,
156    pub(crate) app_lifetime: Arc<AppLifetime>,
157}
158
159pub(crate) struct AppLifetime {
160    pub(crate) events: xmtp_events::EventBus<crate::subscriptions::internal::InternalEvent>,
161}
162
163impl Drop for AppLifetime {
164    fn drop(&mut self) {
165        self.events.close_app_subscriptions();
166    }
167}
168
169impl<Context> Drop for Client<Context> {
170    fn drop(&mut self) {
171        log_event!(Event::ClientDropped, self.installation_id);
172    }
173}
174
175// most of these things are `Arc`'s
176impl<Context: Clone> Clone for Client<Context> {
177    fn clone(&self) -> Self {
178        Self {
179            context: self.context.clone(),
180            installation_id: self.installation_id,
181            workers: self.workers.clone(),
182            app_lifetime: self.app_lifetime.clone(),
183        }
184    }
185}
186
187impl<Context> Client<Context>
188where
189    Context: XmtpSharedContext,
190{
191    pub fn identity_updates(&self) -> IdentityUpdates<&Context> {
192        IdentityUpdates::new(&self.context)
193    }
194
195    pub fn mls_store(&self) -> MlsStore<Context> {
196        MlsStore::new(self.context.clone())
197    }
198
199    pub fn scw_verifier(&self) -> Arc<Box<dyn SmartContractSignatureVerifier>> {
200        self.context.scw_verifier()
201    }
202
203    pub fn version_info(&self) -> &VersionInfo {
204        self.context.version_info()
205    }
206}
207
208impl<Context> Client<Context>
209where
210    Context: XmtpSharedContext,
211    Context::ApiClient: HasStats,
212{
213    pub fn api_stats(&self) -> ApiStats {
214        self.context.api().api_client.mls_stats()
215    }
216
217    pub fn identity_api_stats(&self) -> IdentityStats {
218        self.context.api().api_client.identity_stats()
219    }
220
221    pub fn clear_stats(&self) {
222        self.context.api().api_client.mls_stats().clear();
223        self.context.api().api_client.identity_stats().clear();
224    }
225}
226
227/// Get the [`AssociationState`] for each `inbox_id`
228pub async fn inbox_addresses_with_verifier<ApiClient: XmtpApi>(
229    api_client: &ApiClientWrapper<ApiClient>,
230    conn: &impl DbQuery,
231    inbox_ids: Vec<InboxIdRef<'_>>,
232    scw_verifier: &impl SmartContractSignatureVerifier,
233) -> Result<Vec<AssociationState>, ClientError> {
234    load_identity_updates(api_client, conn, &inbox_ids).await?;
235    let state = batch_get_association_state_with_verifier(
236        conn,
237        &inbox_ids.into_iter().map(|i| (i, None)).collect::<Vec<_>>(),
238        scw_verifier,
239    )
240    .await?;
241    Ok(state)
242}
243
244impl<Context> Client<Context>
245where
246    Context: XmtpSharedContext + 'static,
247{
248    /// Reconnect to the client's database if it has previously been released
249    pub fn reconnect_db(&self) -> Result<(), ClientError> {
250        // Hold the call gate until the workers start. `close` waits for this
251        // call before it stops the workers, so it also stops the ones started
252        // here.
253        let _call = self
254            .context
255            .foreground_calls()
256            .enter()
257            .ok_or(ClientError::AlreadyClosed)?;
258        if self.context.is_closed() {
259            return Err(ClientError::AlreadyClosed);
260        }
261        #[cfg(all(test, not(target_arch = "wasm32")))]
262        test_hooks::pause_reconnect(&self.context.installation_id().to_vec());
263        self.context.db().reconnect().map_err(StorageError::from)?;
264        self.workers.spawn(self.context.clone());
265        Ok(())
266    }
267
268    /// Cleanly shut down this client: cancel in-flight workers and streams,
269    /// then release the DB connection. Idempotent — a second call is `Ok(())`.
270    ///
271    /// Callers (notably the Node binding consumers) should `await` this before
272    /// deleting the SQLite file or dropping the client wrapper, to avoid late
273    /// log spew from detached workers/streams firing against a dead DB.
274    pub async fn close(&self) -> Result<(), ClientError> {
275        // `shutdown_complete` is distinct from `is_closed()` (which reflects
276        // cancellation): only set after the DB actually disconnects. If
277        // `disconnect()` errors below, callers can retry `close()` and we'll
278        // attempt disconnect again rather than silently short-circuiting.
279        if self.context.shutdown_complete() {
280            return Ok(());
281        }
282        self.context
283            .api()
284            .api_client
285            .unregister_client_event_writer(self.context.public_event_writer());
286        self.context.events().close_app_subscriptions();
287        self.context.cancellation_token().cancel();
288        // A running host call can hold a pooled connection, and a running
289        // reconnect can start workers. Wait for both before the workers stop
290        // and the database disconnects.
291        self.context.foreground_calls().close_and_wait().await;
292        let delivery_result = self.context.close_message_delivery();
293        self.workers.shutdown().await;
294        self.context.events().close_internal_subscriptions();
295        // Keep the database connected when lease release fails so a later
296        // close call can retry it.
297        delivery_result?;
298        self.context
299            .db()
300            .disconnect()
301            .map_err(xmtp_db::StorageError::from)?;
302        self.context.mark_shutdown_complete();
303        log_event!(Event::ClientClosed, self.installation_id);
304        Ok(())
305    }
306
307    /// yields until the sync worker notifies that it is initialized and running.
308    pub async fn wait_for_sync_worker_init(&self) {
309        self.workers.wait_for_sync_worker_init().await;
310    }
311
312    pub fn sync_metrics(&self) -> Option<Arc<WorkerMetrics<SyncMetric>>> {
313        self.workers.sync_metrics()
314    }
315}
316
317impl<Context> Client<Context>
318where
319    Context: XmtpSharedContext,
320{
321    /// What this deployment published about itself, as resolved at build.
322    /// A refresh rewrites the stored copy; it never changes
323    /// this value.
324    pub fn server_configuration(&self) -> &xmtp_configuration::ServerConfiguration {
325        self.context.server_configuration().configuration()
326    }
327
328    /// Fetch the deployment configuration now and rewrite the stored copy.
329    ///
330    /// Applies the same validation, storage, and identifier
331    /// binding the refresh worker applies. The snapshot this client is
332    /// holding is unchanged: a new value takes effect at the next build.
333    pub async fn refresh_server_configuration(
334        &self,
335    ) -> Result<xmtp_configuration::ServerConfiguration, ClientError> {
336        Ok(crate::core::preflight::refresh(&self.context).await?)
337    }
338
339    /// Retrieves the client's installation public key, sometimes also called `installation_id`
340    pub fn installation_public_key(&self) -> InstallationId {
341        self.context.installation_id()
342    }
343    /// Retrieves the client's inbox ID
344    pub fn inbox_id(&self) -> InboxIdRef<'_> {
345        self.context.identity().inbox_id()
346    }
347
348    /// get a reference to the monolithic Database object where
349    /// higher-level queries are defined
350    pub fn db(&self) -> <Context::Db as XmtpDb>::DbQuery {
351        self.context.db()
352    }
353
354    /// This associates an installation_id with a human-readable
355    /// name and makes the logs a little easier to read.
356    #[cfg(any(test, feature = "test-utils"))]
357    pub fn set_name(&self, name: &str) {
358        log_event!(Event::AssociateName, self.context.installation_id(), name);
359    }
360
361    pub fn device_sync_client(&self) -> DeviceSyncClient<Context> {
362        let metrics = self.context.sync_metrics();
363        DeviceSyncClient::new(
364            self.context.clone(),
365            metrics.unwrap_or(Arc::new(WorkerMetrics::new(self.context.installation_id()))),
366        )
367    }
368
369    /// Store the app's consent decisions in one transaction. An
370    /// act on a group id the client does not hold fails the whole call, and
371    /// nothing is stored.
372    pub async fn set_consent_states(&self, acts: &[ConsentAct]) -> Result<(), ClientError> {
373        let own = self.context.inbox_id();
374        let keys = acts
375            .iter()
376            .map(|act| ConsentKey::for_app(&self.context.db(), own, act.entity_type, &act.entity))
377            .collect::<Result<Vec<_>, _>>()?;
378        crate::state_tx::state_write_with_events(
379            self.context.mls_storage(),
380            self.context.events(),
381            |tx, events| {
382                let storage = tx.storage();
383                let db = storage.db();
384                let mut changes = vec![];
385                for (key, act) in keys.iter().zip(acts) {
386                    let decision = ConsentWrite::Decide(Decision::Set(act.state));
387                    changes.extend(write_consent(&db, key, decision, Owed::Mark)?);
388                }
389                emit_consent_changes(&self.context, events, &db, &changes)?;
390                Ok::<_, StorageError>(Continue(()))
391            },
392        )?
393        .into_continued();
394
395        Ok(())
396    }
397
398    /// The consent an app reads for an entity: a conversation's under
399    /// its key, held or not, or an inbox's record.
400    // implements: CONS-001
401    pub async fn get_consent_state(
402        &self,
403        entity_type: ConsentType,
404        entity: String,
405    ) -> Result<ConsentState, ClientError> {
406        let db = self.context.db();
407        let Some(key) = ConsentKey::parse(entity_type, &entity) else {
408            return Ok(ConsentState::Unknown);
409        };
410        Ok(match key.group_id() {
411            Some(id) => conversation_consent(&db, self.context.inbox_id(), &id)?,
412            None => db
413                .consent_row(&key)?
414                .map_or(ConsentState::Unknown, |r| r.state),
415        })
416    }
417
418    /// Release the client's database connection
419    pub fn release_db_connection(&self) -> Result<(), ClientError> {
420        self.context
421            .db()
422            .disconnect()
423            .map_err(xmtp_db::StorageError::from)?;
424        Ok(())
425    }
426
427    /// Get a reference to the client's identity struct
428    pub fn identity(&self) -> &Identity {
429        self.context.identity()
430    }
431
432    /// Ensures identity is ready before performing operations.
433    /// Call `register_identity()` first if this fails.
434    pub(crate) fn ensure_identity_ready<E: From<BlockedConnection> + From<IdentityError>>(
435        &self,
436    ) -> Result<(), E> {
437        // Once the connection is blocked, every later call fails with the
438        // reason. This is the gate every client-level operation already passes
439        // through, so the check costs nothing extra.
440        self.context.server_configuration().check()?;
441        if !self.identity().is_ready() {
442            tracing::warn!(
443                inbox_id = %self.inbox_id(),
444                "Operation attempted before register_identity() was called"
445            );
446            return Err(IdentityError::UninitializedIdentity.into());
447        }
448        Ok(())
449    }
450}
451
452impl<Context: XmtpSharedContext> Client<Context> {
453    pub fn attachments(&self) -> Attachments<Context> {
454        Attachments::new(self.context.clone())
455    }
456
457    /// The kinds of the workers this client registered.
458    #[cfg(any(test, feature = "test-utils"))]
459    #[doc(hidden)]
460    pub fn registered_worker_kinds(&self) -> Vec<crate::worker::WorkerKind> {
461        self.workers.registered_kinds()
462    }
463}
464
465impl<Context: XmtpSharedContext> Client<Context> {
466    /// Store configuration, then register inline. The task retries transient errors.
467    pub async fn enable_notifications(
468        &self,
469        config: NotificationConfig,
470    ) -> Result<NotificationState, NotificationError> {
471        notifications::enable_notifications(&self.context, config).await
472    }
473
474    /// Disable locally before unregistering. The recipient identity and overrides stay.
475    /// A failed unregister leaves the client disabled with its recipient reset owed.
476    pub async fn disable_notifications(&self) -> Result<(), NotificationError> {
477        notifications::disable_notifications(&self.context).await
478    }
479
480    /// Read the locally stored state without a backend call.
481    pub fn notification_state(&self) -> Result<NotificationState, StorageError> {
482        notifications::notification_state(&self.context)
483    }
484}
485
486#[cfg(test)]
487pub(crate) mod tests;
488
489#[cfg(all(test, not(target_arch = "wasm32")))]
490pub(crate) mod test_hooks {
491    use std::sync::Arc;
492    use tokio::sync::Barrier;
493
494    type PauseHook = (Vec<u8>, Arc<Barrier>, Arc<Barrier>);
495    /// Stops the next `reconnect_db` of one installation after its closed
496    /// check. The test runs this synchronous call on a blocking thread.
497    pub(crate) static PAUSE_RECONNECT: parking_lot::Mutex<Option<PauseHook>> =
498        parking_lot::Mutex::new(None);
499
500    pub(super) fn pause_reconnect(installation_id: &[u8]) {
501        let paused = {
502            let mut hook = PAUSE_RECONNECT.lock();
503            if hook
504                .as_ref()
505                .is_some_and(|(installation, _, _)| installation.as_slice() == installation_id)
506            {
507                hook.take()
508            } else {
509                None
510            }
511        };
512        if let Some((_, entered, release)) = paused {
513            tokio::runtime::Handle::current().block_on(async {
514                entered.wait().await;
515                release.wait().await;
516            });
517        }
518    }
519}