1use crate::{
2 StorageError, XmtpApi,
3 attachments::AttachmentRuntime,
4 client::{Client, ClientError, DeviceSync},
5 context::{CoreContext, XmtpMlsLocalContext, XmtpSharedContext},
6 groups::change_callbacks::UnstableChangeCallbacks,
7 identity::{Identity, IdentityStrategy},
8 identity_updates::load_identity_updates,
9 mutex_registry::MutexRegistry,
10 server_configuration::ServerConfigurationHandle,
11 utils::VersionInfo,
12 worker::{WorkerRunner, tasks::TaskWorker},
13 worker::{device_sync::worker::SyncWorker, disappearing_messages::DisappearingMessagesWorker},
14};
15use futures::FutureExt;
16use prost::Message as _;
17use std::sync::Arc;
18use std::sync::atomic::AtomicBool;
19use thiserror::Error;
20use tokio_util::sync::CancellationToken;
21use tracing::debug;
22use xmtp_api::ApiClientWrapper;
23use xmtp_api_backend::TrackedStatsClient;
24use xmtp_common::snippet::Snippet;
25use xmtp_common::{ErrorCode, Event, Retry};
26use xmtp_cryptography::signature::IdentifierValidationError;
27use xmtp_db::{XmtpDb, sql_key_store::SqlKeyStore};
28use xmtp_db::{XmtpMlsStorageProvider, prelude::*};
29use xmtp_id::scw_verifier::SmartContractSignatureVerifier;
30use xmtp_macro::log_event;
31use xmtp_proto::api_client::XmtpBackendClient;
32use xmtp_proto::xmtp::mls::database::{
33 ProcessPendingSelfRemove, Task as TaskProto, task::Task as TaskKind,
34};
35
36pub use crate::core::config::{DeviceSyncMode, ForkRecoveryOpts, ForkRecoveryPolicy};
37
38mod build;
39mod error;
40mod storage;
41
42pub use error::ClientBuilderError;
43use storage::ContextParts;
44#[cfg(not(target_arch = "wasm32"))]
45use storage::LocationStoreOpener;
46#[cfg(target_arch = "wasm32")]
47use storage::LocationStoreOpener;
48
49pub struct ClientBuilder<ApiClient, S, Db = xmtp_db::DefaultStore> {
50 pub(crate) deployment_recorder: Option<crate::storage_location::DeploymentRecorder>,
51 pub(crate) data_location: Option<crate::storage_location::StorageLocation>,
52 pub(crate) location_store_opener: Option<LocationStoreOpener<Db>>,
53 pub(crate) mls_storage_factory: Option<fn(&Db) -> S>,
54 pub(crate) storage_location_selected: bool,
55 pub(crate) storage_location_conflict: bool,
56 pub(crate) attachments_dir: Option<std::path::PathBuf>,
57 pub(crate) attachment_options: xmtp_attachments::AttachmentOptions,
58 pub(crate) api_client: Option<ApiClient>,
59 pub(crate) identity: Option<Identity>,
60 pub(crate) store: Option<Db>,
61 pub(crate) identity_strategy: IdentityStrategy,
62 pub(crate) scw_verifier: Option<Box<dyn SmartContractSignatureVerifier>>,
63 pub(crate) custom_scw_verifier: bool,
65 pub(crate) device_sync_worker_mode: DeviceSyncMode,
66 pub(crate) fork_recovery_opts: Option<ForkRecoveryOpts>,
67 pub(crate) change_callbacks: UnstableChangeCallbacks,
69 pub(crate) stream_policy: xmtp_mls_core::policy::StreamPolicy,
70 pub(crate) incoming_factory:
71 Option<Arc<dyn crate::subscriptions::incoming::SubscriptionFactory>>,
72 pub(crate) version_info: VersionInfo,
73 pub(crate) allow_offline: bool,
74 pub(crate) disable_commit_log_worker: bool,
75 pub(crate) mls_storage: Option<S>,
76 pub(crate) disable_workers: bool,
77 pub(crate) worker_config: crate::worker::WorkerConfig,
78 pub(crate) config_provider: Option<Arc<dyn xmtp_configuration::ConfigProvider>>,
82 #[cfg(any(test, feature = "test-utils"))]
83 application_components_for_test:
84 Option<Vec<xmtp_configuration::ApplicationComponentDefinition>>,
85}
86
87impl Client<()> {
88 pub fn builder(strategy: IdentityStrategy) -> ClientBuilder<(), ()> {
90 ClientBuilder::<(), ()>::new(strategy)
91 }
92}
93
94impl<ApiClient, S, Db> ClientBuilder<ApiClient, S, Db> {
95 #[cfg(any(test, feature = "test-hooks"))]
97 pub fn stream_policy(mut self, settings: xmtp_mls_core::policy::StreamPolicy) -> Self {
98 self.stream_policy = settings;
99 self
100 }
101
102 #[tracing::instrument(level = "trace", skip_all)]
103 pub fn new(identity_strategy: IdentityStrategy) -> Self {
104 Self {
105 deployment_recorder: None,
106 data_location: None,
107 location_store_opener: None,
108 mls_storage_factory: None,
109 storage_location_selected: false,
110 storage_location_conflict: false,
111 attachments_dir: None,
112 attachment_options: xmtp_attachments::AttachmentOptions::default(),
113 identity_strategy,
114 api_client: None,
115 identity: None,
116 store: None,
117 scw_verifier: None,
118 custom_scw_verifier: false,
119 device_sync_worker_mode: DeviceSyncMode::Enabled,
120 fork_recovery_opts: None,
121 change_callbacks: UnstableChangeCallbacks::default(),
122 stream_policy: xmtp_mls_core::policy::StreamPolicy::default(),
123 incoming_factory: None,
124 version_info: VersionInfo::default(),
125 allow_offline: false,
126 disable_commit_log_worker: false,
127 mls_storage: None,
128 disable_workers: false,
129 worker_config: crate::worker::WorkerConfig::default(),
130 config_provider: None,
131 #[cfg(any(test, feature = "test-utils"))]
132 application_components_for_test: None,
133 }
134 }
135}
136
137#[cfg(any(test, feature = "test-utils"))]
138impl<ApiClient, S, Db> ClientBuilder<ApiClient, S, Db>
139where
140 ApiClient: Clone,
141 Db: Clone,
142 S: Clone,
143{
144 pub fn from_client(
145 client: Client<ContextParts<ApiClient, S, Db>>,
146 ) -> ClientBuilder<ApiClient, S, Db> {
147 let cloned_api: ApiClient = client.context.api_client.api_client.raw_for_test().clone();
148 ClientBuilder {
149 deployment_recorder: None,
150 data_location: None,
151 location_store_opener: None,
152 mls_storage_factory: None,
153 storage_location_selected: false,
154 storage_location_conflict: false,
155 attachments_dir: client.context.features.attachments.dir().cloned(),
156 attachment_options: client.context.features.attachments.options().clone(),
157 api_client: Some(cloned_api),
158 identity: Some(client.context.identity.clone()),
159 store: Some(client.context.store.clone()),
160 identity_strategy: IdentityStrategy::CachedOnly,
161 scw_verifier: Some(Box::new(client.context.scw_verifier.clone())),
162 custom_scw_verifier: client.context.server_configuration.custom_verifier(),
163 device_sync_worker_mode: client.context.device_sync.mode,
164 fork_recovery_opts: Some(client.context.fork_recovery_opts.clone()),
165 change_callbacks: client.context.change_callbacks.clone(),
166 stream_policy: client.context.features.incoming.policy().clone(),
167 incoming_factory: client.context.features.incoming.original_factory(),
168 version_info: client.context.version_info.clone(),
169 allow_offline: false,
170 disable_commit_log_worker: false,
171 mls_storage: Some(client.context.mls_storage.clone()),
172 disable_workers: false,
173 worker_config: client.context.worker_config.clone(),
174 config_provider: None,
175 #[cfg(any(test, feature = "test-utils"))]
176 application_components_for_test: None,
177 }
178 }
179}
180
181impl<ApiClient, S, Db> ClientBuilder<ApiClient, S, Db> {
184 pub fn identity(self, identity: Identity) -> Self {
185 Self {
186 identity: Some(identity),
187 ..self
188 }
189 }
190
191 pub fn attachments_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
192 self.storage_location_conflict |= self.storage_location_selected;
193 self.attachments_dir = Some(path.into());
194 self
195 }
196
197 pub fn attachment_options(mut self, options: xmtp_attachments::AttachmentOptions) -> Self {
198 self.attachment_options = options;
199 self
200 }
201
202 pub fn unstable_change_callbacks(self, change_callbacks: UnstableChangeCallbacks) -> Self {
211 Self {
212 change_callbacks,
213 ..self
214 }
215 }
216
217 pub fn with_disable_workers(mut self, disable_workers: bool) -> Self {
218 self.disable_workers = disable_workers;
219 self
220 }
221
222 #[cfg(any(test, feature = "test-utils"))]
225 #[doc(hidden)]
226 pub fn incoming_factory_mut(
227 &mut self,
228 ) -> &mut Option<Arc<dyn crate::subscriptions::incoming::SubscriptionFactory>> {
229 &mut self.incoming_factory
230 }
231
232 pub fn with_device_sync_worker_mode(self, mode: Option<DeviceSyncMode>) -> Self {
233 Self {
234 device_sync_worker_mode: mode.unwrap_or(DeviceSyncMode::Enabled),
235 ..self
236 }
237 }
238
239 pub fn device_sync_worker_mode(self, mode: DeviceSyncMode) -> Self {
240 Self {
241 device_sync_worker_mode: mode,
242 ..self
243 }
244 }
245
246 pub fn fork_recovery_opts(self, opts: ForkRecoveryOpts) -> Self {
247 Self {
248 fork_recovery_opts: Some(opts),
249 ..self
250 }
251 }
252
253 pub fn worker_config(mut self, cfg: crate::worker::WorkerConfig) -> Self {
256 self.worker_config = cfg;
257 self
258 }
259
260 #[cfg(any(test, feature = "test-utils"))]
263 pub fn application_components_for_test(
264 mut self,
265 components: Vec<xmtp_configuration::ApplicationComponentDefinition>,
266 ) -> Self {
267 self.application_components_for_test = Some(components);
268 self
269 }
270
271 pub fn config_provider(
277 mut self,
278 provider: Arc<dyn xmtp_configuration::ConfigProvider>,
279 ) -> Self {
280 self.config_provider = Some(provider);
281 self
282 }
283
284 pub fn api_client<A>(self, api_client: A) -> ClientBuilder<A, S, Db> {
287 ClientBuilder {
288 deployment_recorder: self.deployment_recorder,
289 data_location: self.data_location,
290 location_store_opener: self.location_store_opener,
291 mls_storage_factory: self.mls_storage_factory,
292 storage_location_selected: self.storage_location_selected,
293 storage_location_conflict: self.storage_location_conflict,
294 api_client: Some(api_client),
295 identity: self.identity,
296 identity_strategy: self.identity_strategy,
297 scw_verifier: self.scw_verifier,
298 custom_scw_verifier: self.custom_scw_verifier,
299 store: self.store,
300 device_sync_worker_mode: self.device_sync_worker_mode,
301 fork_recovery_opts: self.fork_recovery_opts,
302 change_callbacks: self.change_callbacks,
303 stream_policy: self.stream_policy,
304 incoming_factory: None,
305 version_info: self.version_info,
306 allow_offline: self.allow_offline,
307 disable_commit_log_worker: self.disable_commit_log_worker,
308 mls_storage: self.mls_storage,
309 disable_workers: self.disable_workers,
310 worker_config: self.worker_config,
311 config_provider: self.config_provider,
312 #[cfg(any(test, feature = "test-utils"))]
313 application_components_for_test: self.application_components_for_test,
314 attachments_dir: self.attachments_dir,
315 attachment_options: self.attachment_options,
316 }
317 }
318
319 xmtp_common::if_native! {
320 pub fn api_client_with_streams<A>(self, api_client: A) -> ClientBuilder<A, S, Db>
323 where
324 A: xmtp_proto::api_client::XmtpMlsBidiStreams
325 + crate::subscriptions::router_callbacks::ApiClientIdentity
326 + Clone
327 + Send
328 + Sync
329 + 'static,
330 A::SubscribeStream: 'static,
331 {
332 let factory = crate::subscriptions::incoming::streaming_factory(api_client.clone());
333 let mut builder = self.api_client(api_client);
334 builder.incoming_factory = Some(factory);
335 builder
336 }
337 }
338
339 xmtp_common::if_wasm! {
340 pub fn api_client_with_streams<A>(self, api_client: A) -> ClientBuilder<A, S, Db>
343 where
344 A: xmtp_proto::api_client::XmtpMlsStreams + Clone + 'static,
345 {
346 let factory = crate::subscriptions::incoming::streaming_factory(api_client.clone());
347 let mut builder = self.api_client(api_client);
348 builder.incoming_factory = Some(factory);
349 builder
350 }
351 }
352
353 pub fn maybe_version(
354 mut self,
355 version: Option<VersionInfo>,
356 ) -> ClientBuilder<ApiClient, S, Db> {
357 if let Some(v) = version {
358 self.version_info = v;
359 }
360 self
361 }
362
363 pub fn version(self, version_info: VersionInfo) -> ClientBuilder<ApiClient, S, Db> {
364 Self {
365 version_info,
366 ..self
367 }
368 }
369
370 pub fn with_allow_offline(
374 self,
375 allow_offline: Option<bool>,
376 ) -> ClientBuilder<ApiClient, S, Db> {
377 Self {
378 allow_offline: allow_offline.unwrap_or(false),
379 ..self
380 }
381 }
382
383 #[cfg(any(test, feature = "test-utils"))]
386 pub fn with_commit_log_worker(self, enabled: bool) -> Self {
387 Self {
388 disable_commit_log_worker: !enabled,
389 ..self
390 }
391 }
392
393 #[cfg(any(test, feature = "test-utils"))]
394 pub fn enable_sqlite_triggers(self) -> Self
395 where
396 Db: XmtpDb,
397 {
398 let db = self.store.as_ref().expect("unwrapping in test env").conn();
399 let db = xmtp_db::DbConnection::new(db);
400 db.register_triggers();
401 db.disable_memory_security();
402 self
403 }
404
405 pub fn enable_api_stats(
406 self,
407 ) -> Result<ClientBuilder<TrackedStatsClient<ApiClient>, S, Db>, ClientBuilderError> {
408 if self.api_client.is_none() {
409 return Err(ClientBuilderError::MissingParameter {
410 parameter: "api_client",
411 });
412 }
413
414 Ok(ClientBuilder {
415 deployment_recorder: self.deployment_recorder,
416 data_location: self.data_location,
417 location_store_opener: self.location_store_opener,
418 mls_storage_factory: self.mls_storage_factory,
419 storage_location_selected: self.storage_location_selected,
420 storage_location_conflict: self.storage_location_conflict,
421 api_client: Some(TrackedStatsClient::new(
422 self.api_client.expect("checked for none"),
423 )),
424 identity: self.identity,
425 identity_strategy: self.identity_strategy,
426 scw_verifier: self.scw_verifier,
427 custom_scw_verifier: self.custom_scw_verifier,
428 store: self.store,
429
430 device_sync_worker_mode: self.device_sync_worker_mode,
431 fork_recovery_opts: self.fork_recovery_opts,
432 change_callbacks: self.change_callbacks,
433 stream_policy: self.stream_policy,
434 incoming_factory: self.incoming_factory,
435 version_info: self.version_info,
436 allow_offline: self.allow_offline,
437 disable_commit_log_worker: self.disable_commit_log_worker,
438 mls_storage: self.mls_storage,
439 disable_workers: self.disable_workers,
440 worker_config: self.worker_config,
441 config_provider: self.config_provider,
442 #[cfg(any(test, feature = "test-utils"))]
443 application_components_for_test: self.application_components_for_test,
444 attachments_dir: self.attachments_dir,
445 attachment_options: self.attachment_options,
446 })
447 }
448
449 pub fn with_scw_verifier(
450 self,
451 verifier: impl SmartContractSignatureVerifier + 'static,
452 ) -> ClientBuilder<ApiClient, S, Db> {
453 ClientBuilder {
454 deployment_recorder: self.deployment_recorder,
455 data_location: self.data_location,
456 location_store_opener: self.location_store_opener,
457 mls_storage_factory: self.mls_storage_factory,
458 storage_location_selected: self.storage_location_selected,
459 storage_location_conflict: self.storage_location_conflict,
460 api_client: self.api_client,
461 identity: self.identity,
462 identity_strategy: self.identity_strategy,
463 scw_verifier: Some(Box::new(verifier)),
464 custom_scw_verifier: true,
465 store: self.store,
466
467 device_sync_worker_mode: self.device_sync_worker_mode,
468 fork_recovery_opts: self.fork_recovery_opts,
469 change_callbacks: self.change_callbacks,
470 stream_policy: self.stream_policy,
471 incoming_factory: self.incoming_factory,
472 version_info: self.version_info,
473 allow_offline: self.allow_offline,
474 disable_commit_log_worker: self.disable_commit_log_worker,
475 mls_storage: self.mls_storage,
476 disable_workers: self.disable_workers,
477 worker_config: self.worker_config,
478 config_provider: self.config_provider,
479 #[cfg(any(test, feature = "test-utils"))]
480 application_components_for_test: self.application_components_for_test,
481 attachments_dir: self.attachments_dir,
482 attachment_options: self.attachment_options,
483 }
484 }
485
486 pub fn with_remote_verifier(self) -> Result<ClientBuilder<ApiClient, S, Db>, ClientBuilderError>
489 where
490 ApiClient: Clone + XmtpApi + 'static,
491 {
492 let api = self
493 .api_client
494 .clone()
495 .ok_or(ClientBuilderError::MissingParameter {
496 parameter: "api_client",
497 })?;
498
499 Ok(ClientBuilder {
500 deployment_recorder: self.deployment_recorder,
501 data_location: self.data_location,
502 location_store_opener: self.location_store_opener,
503 mls_storage_factory: self.mls_storage_factory,
504 storage_location_selected: self.storage_location_selected,
505 storage_location_conflict: self.storage_location_conflict,
506 api_client: self.api_client,
507 identity: self.identity,
508 identity_strategy: self.identity_strategy,
509 scw_verifier: Some(Box::new(ApiClientWrapper::new(api, Retry::default()))
510 as Box<dyn SmartContractSignatureVerifier>),
511 custom_scw_verifier: false,
514 store: self.store,
515 device_sync_worker_mode: self.device_sync_worker_mode,
516 fork_recovery_opts: self.fork_recovery_opts,
517 change_callbacks: self.change_callbacks,
518 stream_policy: self.stream_policy,
519 incoming_factory: self.incoming_factory,
520 version_info: self.version_info,
521 allow_offline: self.allow_offline,
522 disable_commit_log_worker: self.disable_commit_log_worker,
523 mls_storage: self.mls_storage,
524 disable_workers: self.disable_workers,
525 worker_config: self.worker_config,
526 config_provider: self.config_provider,
527 #[cfg(any(test, feature = "test-utils"))]
528 application_components_for_test: self.application_components_for_test,
529 attachments_dir: self.attachments_dir,
530 attachment_options: self.attachment_options,
531 })
532 }
533}
534
535#[cfg(test)]
536mod worker_registration_tests {
537 use crate::tester;
538 use crate::worker::{WorkerConfig, WorkerKind};
539
540 #[xmtp_common::test(unwrap_try = true)]
541 #[cfg_attr(target_arch = "wasm32", ignore)]
542 async fn disabled_worker_is_not_registered() {
543 let mut cfg = WorkerConfig::default();
544 cfg.enabled.insert(WorkerKind::DisappearingMessages, false);
545 tester!(alix, worker_config: cfg);
546
547 let kinds = alix.client.workers.registered_kinds();
548 assert!(
549 !kinds.contains(&WorkerKind::DisappearingMessages),
550 "disabled worker must not be registered, got {kinds:?}"
551 );
552 assert!(
553 kinds.contains(&WorkerKind::TaskRunner),
554 "un-disabled worker must still be registered, got {kinds:?}"
555 );
556 let subscriptions = alix.client.workers.subscribed_kinds();
557 assert!(!subscriptions.contains(&WorkerKind::DisappearingMessages));
558 assert!(subscriptions.contains(&WorkerKind::TaskRunner));
559 }
560
561 #[xmtp_common::test(unwrap_try = true)]
562 #[cfg_attr(target_arch = "wasm32", ignore)]
563 async fn disabled_optional_workers_keep_the_epoch_observer() {
564 tester!(alix, disable_workers);
565 assert_eq!(
566 alix.client.workers.registered_kinds(),
567 vec![WorkerKind::HmacEpoch]
568 );
569 assert!(alix.client.workers.is_running());
570 }
571
572 #[xmtp_common::test(unwrap_try = true)]
573 #[cfg_attr(target_arch = "wasm32", ignore)]
574 async fn registered_worker_kinds_reads_the_registry() {
575 tester!(alix, disable_workers);
576 assert_eq!(
577 alix.client.registered_worker_kinds(),
578 vec![WorkerKind::HmacEpoch]
579 );
580 }
581}