Skip to main content

xmtp_mls/builder/
build.rs

1//! Client builds: admitting the configuration, building offline or online, and the
2//! backfill a build runs.
3
4use super::*;
5
6// Every identity request uses an admitted snapshot, including the lookup
7// needed to find a data directory's database.
8fn admit_configuration<ApiClient: XmtpBackendClient>(
9    api_client: &mut ApiClientWrapper<ApiClient>,
10    configuration: &xmtp_configuration::ServerConfiguration,
11    client_version: &semver::Version,
12) -> Result<(), ClientError> {
13    crate::server_configuration::check_minimum_version(configuration, client_version)?;
14    // implements: CONF-051
15    if configuration.auth.enabled && !api_client.has_credential_source() {
16        return Err(ClientError::AuthRequired {
17            required_scopes: configuration.auth.required_scopes.clone(),
18        });
19    }
20    let snapshot = Arc::new(configuration.clone());
21    api_client
22        .api_client
23        .set_limits(Arc::new(snapshot.limits.clone()));
24    api_client.set_configuration(snapshot);
25    Ok(())
26}
27
28/// One-time backfill of `ProcessPendingSelfRemove` tasks for groups that already
29/// had pending leave requests before self-removal became event-driven. Such rows
30/// have no incoming LeaveRequest to re-fire, so without this they'd only be
31/// processed if a new one arrived. Best-effort and idempotent (deduped per group).
32///
33/// TODO(#3748): removable once every client has shipped a release that enqueues
34/// these tasks inline — safe to delete by the next-next stable release.
35fn backfill_pending_self_remove_tasks<C>(context: &C) -> Result<(), StorageError>
36where
37    C: XmtpSharedContext,
38{
39    let db = context.db();
40    for raw_id in db.get_groups_have_pending_leave_request()? {
41        let Ok(group_id) = xmtp_proto::types::GroupId::try_from(raw_id.as_slice()) else {
42            continue;
43        };
44        let now = xmtp_common::time::now_ns();
45        let proto = TaskProto {
46            task: Some(TaskKind::ProcessPendingSelfRemove(
47                ProcessPendingSelfRemove {
48                    group_id: group_id.to_vec(),
49                },
50            )),
51        };
52        let task = xmtp_db::tasks::NewTask::builder()
53            .originating_message_sequence_id(0)
54            .created_at_ns(now)
55            .next_attempt_at_ns(now)
56            .build(proto)?;
57        // Insert-if-absent per group: leaves any live retrying task (and its
58        // backoff) untouched, only replacing dead rows. Safe to call on every
59        // startup without resurrecting exhausted tasks.
60        db.upsert_pending_self_remove_task(&group_id, task)?;
61    }
62    Ok(())
63}
64
65impl<ApiClient, S, Db> ClientBuilder<ApiClient, S, Db> {
66    /// build a client in offline mode.
67    /// returns an error if the client failed to build as offline
68    pub fn build_offline(self) -> Result<Client<ContextParts<ApiClient, S, Db>>, ClientBuilderError>
69    where
70        ApiClient: XmtpApi + 'static,
71        Db: xmtp_db::XmtpDb + 'static,
72        S: XmtpMlsStorageProvider + 'static,
73    {
74        self.build()
75            .now_or_never()
76            .ok_or(ClientBuilderError::OfflineBuildFailed)
77            .flatten()
78    }
79
80    /// Build the client. When the identity strategy carries an identifier,
81    /// the build requires it to belong to the inbox of the identity it loads,
82    /// including a stored one: it checks the newest association state after
83    /// it loads the inbox's identity updates and before it starts any worker.
84    /// An offline build loads none and checks the newest state the database
85    /// stores, which can predate a revocation. Before the inbox's first
86    /// identity update, only the identifier whose inbox at the strategy's
87    /// nonce is that inbox belongs to it. A failure is
88    /// [`IdentityError::IdentifierNotInInbox`](crate::identity::IdentityError::IdentifierNotInInbox).
89    #[tracing::instrument(err, skip_all, fields(operation = "mls.build_client"))]
90    pub async fn build(self) -> Result<Client<ContextParts<ApiClient, S, Db>>, ClientBuilderError>
91    where
92        ApiClient: XmtpApi + 'static,
93        Db: xmtp_db::XmtpDb + 'static,
94        S: XmtpMlsStorageProvider + 'static,
95    {
96        let ClientBuilder {
97            mut deployment_recorder,
98            data_location,
99            location_store_opener,
100            mls_storage_factory,
101            storage_location_conflict,
102            mut attachments_dir,
103            attachment_options,
104            mut api_client,
105            identity,
106            mut store,
107            mut identity_strategy,
108            mut scw_verifier,
109            custom_scw_verifier,
110
111            device_sync_worker_mode,
112            fork_recovery_opts,
113            change_callbacks,
114            stream_policy,
115            incoming_factory,
116            version_info,
117            allow_offline,
118            disable_commit_log_worker,
119            mut mls_storage,
120            disable_workers,
121            worker_config,
122            config_provider,
123            #[cfg(any(test, feature = "test-utils"))]
124            application_components_for_test,
125            ..
126        } = self;
127
128        if storage_location_conflict {
129            return Err(crate::storage_location::StorageLocationError::ConflictingStore.into());
130        }
131
132        let api_client = api_client
133            .take()
134            .ok_or(ClientBuilderError::MissingParameter {
135                parameter: "api_client",
136            })?;
137
138        let mut scw_verifier = scw_verifier
139            .take()
140            .ok_or(ClientBuilderError::MissingParameter {
141                parameter: "scw_verifier",
142            })?;
143
144        let mut api_client = ApiClientWrapper::new(api_client, Retry::default());
145        let config_provider = config_provider.map(ServerConfigurationHandle::new);
146        let mut data_dir_opened_identifier = None;
147        if let Some(location) = data_location {
148            use crate::storage_location::StorageLocationError;
149            let data_dir = matches!(
150                location,
151                crate::storage_location::StorageLocation::DataDir(_)
152            );
153            // A data directory's path holds the inbox. Only an online build
154            // can look up an unknown one.
155            let look_up_inbox = data_dir && identity_strategy.inbox_id().is_none();
156            if look_up_inbox
157                && (allow_offline
158                    || !matches!(
159                        identity_strategy,
160                        IdentityStrategy::CreateForIdentifier { .. }
161                    ))
162            {
163                return Err(StorageLocationError::InboxId.into());
164            }
165            let backend_url = api_client.backend_url().unwrap_or_default().to_owned();
166            if data_dir && backend_url.trim_end_matches('/').is_empty() {
167                return Err(StorageLocationError::BackendUrl.into());
168            }
169            let recorder = location.recorder(&backend_url);
170            let recorded = match &recorder {
171                Some(recorder) => recorder.lookup().await?,
172                None => None,
173            };
174            let mut fetched = None;
175            // The request that looks up an inbox carries the identifier, and
176            // the database it finds may hold no configuration. So that build
177            // asks the deployment for its configuration first, even for a
178            // recorded URL.
179            let opened_identifier = match recorded {
180                Some(identifier) if !look_up_inbox => Some(identifier),
181                _ if !data_dir => None,
182                recorded => {
183                    if allow_offline {
184                        return Err(StorageLocationError::OfflineMissingDeployment.into());
185                    }
186                    let response = api_client.get_configuration().await.map_err(|error| {
187                        ClientBuilderError::ClientError(ClientError::ConfigurationUnavailable(
188                            Box::new(crate::server_configuration::ConfigurationFetchError::Api(
189                                error,
190                            )),
191                        ))
192                    })?;
193                    let configuration = crate::server_configuration::validated(&response)
194                        .map_err(ClientError::from)?;
195                    let identifier = configuration.identifier.clone();
196                    if let Some(recorded) = recorded
197                        && recorded != identifier
198                    {
199                        return Err(ClientError::BackendMismatch {
200                            stored: recorded,
201                            received: identifier,
202                        }
203                        .into());
204                    }
205                    if look_up_inbox {
206                        let admission = config_provider
207                            .as_ref()
208                            .map(ServerConfigurationHandle::configuration)
209                            .unwrap_or(&configuration);
210                        if admission.identifier != identifier {
211                            return Err(StorageLocationError::DeploymentMismatch.into());
212                        }
213                        admit_configuration(
214                            &mut api_client,
215                            admission,
216                            version_info.pkg_semver().semver(),
217                        )?;
218                    }
219                    fetched = Some((identifier.clone(), response));
220                    Some(identifier)
221                }
222            };
223            // An explicit database is opened first, and its build looks up
224            // an unknown inbox after the configuration checks below.
225            if look_up_inbox {
226                identity_strategy = identity_strategy.with_inbox(&api_client).await?;
227            }
228            let paths = location.resolve_identifier(
229                identity_strategy.inbox_id().unwrap_or_default(),
230                opened_identifier.as_deref().unwrap_or_default(),
231            )?;
232            let opener = location_store_opener.ok_or(StorageLocationError::ConflictingStore)?;
233            let opened = opener(paths.clone()).await?;
234            if let Some((identifier, response)) = fetched {
235                // A stored configuration stays, and the checks below compare
236                // it with this backend.
237                if opened.db().server_configuration()?.is_none() {
238                    opened.db().store_server_configuration(
239                        &identifier,
240                        backend_url.trim_end_matches('/'),
241                        &response.encode_to_vec(),
242                        xmtp_common::time::now_ns(),
243                    )?;
244                }
245                if let Some(recorder) = &recorder {
246                    recorder.record(&identifier).await?;
247                }
248            }
249            store = Some(opened);
250            attachments_dir = Some(paths.attachments_dir);
251            if data_dir {
252                data_dir_opened_identifier = opened_identifier.clone();
253            }
254            deployment_recorder = recorder.map(|recorder| match opened_identifier {
255                Some(identifier) => recorder.for_opened_identifier(identifier),
256                None => recorder,
257            });
258        }
259        let store = store
260            .take()
261            .ok_or(ClientBuilderError::MissingParameter { parameter: "store" })?;
262        let mls_storage = mls_storage
263            .take()
264            .or_else(|| mls_storage_factory.map(|factory| factory(&store)))
265            .ok_or(ClientBuilderError::MissingParameter {
266                parameter: "mls_storage",
267            })?;
268
269        let conn = store.db();
270
271        // The configuration is resolved before any identity
272        // work, so a deployment that refuses this client refuses it before the
273        // database gains an identity. A caller-supplied provider
274        // short-circuits every network and database path here, which is what
275        // keeps `build_offline` free of a pending future.
276        let has_config_provider = config_provider.is_some();
277        let server_configuration = match config_provider {
278            Some(provider) => provider,
279            None => crate::server_configuration::resolve(&api_client, &conn, allow_offline)
280                .await
281                .map_err(ClientError::from)?,
282        };
283
284        #[cfg(any(test, feature = "test-utils"))]
285        let server_configuration = match application_components_for_test {
286            Some(components) => server_configuration.with_application_components(components),
287            None => server_configuration,
288        };
289
290        if has_config_provider && let Some(opened_identifier) = data_dir_opened_identifier {
291            let provider_identifier = &server_configuration.configuration().identifier;
292            let stored_identifier = conn.server_configuration()?.map(|row| row.identifier);
293            if provider_identifier != &opened_identifier
294                || stored_identifier.as_deref().is_some_and(|identifier| {
295                    !identifier.is_empty() && identifier != provider_identifier
296                })
297            {
298                return Err(
299                    crate::storage_location::StorageLocationError::DeploymentMismatch.into(),
300                );
301            }
302        }
303
304        let server_configuration = server_configuration.with_chain_restriction(custom_scw_verifier);
305        if server_configuration.requires_preflight() {
306            api_client.api_client.require_preflight();
307        }
308        if let Some(recorder) = deployment_recorder {
309            if !has_config_provider && !server_configuration.configuration().identifier.is_empty() {
310                recorder
311                    .record(&server_configuration.configuration().identifier)
312                    .await?;
313            }
314            server_configuration.set_deployment_recorder(recorder);
315        }
316
317        admit_configuration(
318            &mut api_client,
319            server_configuration.configuration(),
320            version_info.pkg_semver().semver(),
321        )?;
322        // A shared backend can admit a different snapshot for another client.
323        // Keep this client's receiving limits before its first lazy stream opens.
324        let incoming_factory = incoming_factory
325            .map(|factory| factory.bind_limits(api_client.limits()).unwrap_or(factory));
326        // Clone after admission, so the default verifier sizes its verify
327        // requests by the published limits.
328        if !custom_scw_verifier {
329            scw_verifier = Box::new(api_client.clone());
330        }
331
332        let identifier_check = match &identity_strategy {
333            IdentityStrategy::CreateIfNotFound {
334                identifier, nonce, ..
335            }
336            | IdentityStrategy::CreateForIdentifier { identifier, nonce } => {
337                Some((identifier.clone(), *nonce))
338            }
339            _ => None,
340        };
341        let mut identity = if let Some(identity) = identity {
342            identity
343        } else {
344            identity_strategy
345                .initialize_identity(&api_client, &mls_storage, &scw_verifier)
346                .await?
347        };
348
349        // The registration request is handed to the app to
350        // sign, so bind it to the chains the deployment accepts before it
351        // leaves the client.
352        if let Some(request) = identity.signature_request.as_mut() {
353            server_configuration.restrict(request);
354        }
355
356        debug!(
357            inbox_id = identity.inbox_id(),
358            installation_id = identity.installation_keys.public_bytes().snippet(),
359            "Initialized identity"
360        );
361        if !allow_offline {
362            // get sequence_id from identity updates and loaded into the DB
363            load_identity_updates(
364                &api_client,
365                &conn,
366                vec![identity.inbox_id.as_str()].as_slice(),
367            )
368            .await
369            .map_err(ClientError::from)?;
370        }
371        // The identity store trusts a stored identity of the same inbox. The
372        // check runs on the identity updates loaded above and before any
373        // worker, so a rejected identifier makes no request as the stored
374        // installation. Offline, it reads only the database.
375        // implements: IDENT-096
376        if let Some((identifier, nonce)) = identifier_check {
377            let inbox_id = identity.inbox_id.as_str();
378            let membership = if allow_offline {
379                crate::identity_updates::stored_identifier_membership(&conn, inbox_id, &identifier)
380                    .await
381                    .map_err(ClientError::from)?
382            } else {
383                crate::identity_updates::identifier_membership(
384                    &conn,
385                    inbox_id,
386                    &identifier,
387                    &scw_verifier,
388                )
389                .await
390                .map_err(ClientError::from)?
391            };
392            if !crate::identity_updates::identifier_opens_inbox(
393                membership,
394                &identifier,
395                nonce,
396                &identity.inbox_id,
397            ) {
398                return Err(crate::identity::IdentityError::IdentifierNotInInbox {
399                    inbox_id: identity.inbox_id.clone(),
400                }
401                .into());
402            }
403        }
404
405        // Own-installation events start after the own-inbox updates stored
406        // now, including any the load above stored.
407        let own_inbox_stored_through = conn
408            .get_latest_sequence_id(&[identity.inbox_id.as_str()])
409            .map_err(StorageError::from)?
410            .get(identity.inbox_id.as_str())
411            .copied();
412
413        // Fold the legacy single-worker toggles into the unified enable map so
414        // there is one source of truth for "is worker X enabled" that code paths
415        // when it registers worker subscriptions. The old fields keep working;
416        // they just write here.
417        let mut worker_config = worker_config;
418        if disable_workers {
419            // Disable optional workers. The HMAC epoch observer still runs for
420            // every open client.
421            for kind in [
422                crate::worker::WorkerKind::DeviceSync,
423                crate::worker::WorkerKind::DisappearingMessages,
424                crate::worker::WorkerKind::CommitLog,
425                crate::worker::WorkerKind::TaskRunner,
426                crate::worker::WorkerKind::ConfigurationRefresh,
427                crate::worker::WorkerKind::AttachmentCleanup,
428            ] {
429                worker_config.enabled.insert(kind, false);
430            }
431        }
432        if matches!(device_sync_worker_mode, DeviceSyncMode::Disabled) {
433            worker_config
434                .enabled
435                .entry(crate::worker::WorkerKind::DeviceSync)
436                .or_insert(false);
437        }
438        if disable_commit_log_worker {
439            worker_config
440                .enabled
441                .entry(crate::worker::WorkerKind::CommitLog)
442                .or_insert(false);
443        }
444
445        let events = xmtp_events::EventBus::new();
446        let events_for_lifetime = events.clone();
447        let public_event_writer: Arc<dyn xmtp_events::EventWriter<()>> =
448            Arc::new(xmtp_events::PublicBusWriter::new(&events));
449        server_configuration.set_event_writer(public_event_writer.clone());
450        api_client
451            .api_client
452            .register_client_event_writer(&public_event_writer);
453        let mut workers = WorkerRunner::new();
454        let incoming_runtime = crate::subscriptions::incoming::IncomingRuntime::new(
455            stream_policy.clone(),
456            incoming_factory,
457        )
458        .with_preflight(api_client.api_client.clone());
459        let attachments =
460            Arc::new(AttachmentRuntime::new(attachments_dir, attachment_options).await?);
461        let context = Arc::new(XmtpMlsLocalContext {
462            identity,
463            mls_storage,
464            store,
465            api_client,
466            version_info,
467            server_configuration,
468            scw_verifier: Arc::new(scw_verifier),
469            mutexes: MutexRegistry::new(),
470            hooks: Default::default(),
471            events,
472            public_event_writer,
473            registration_event_pending: Arc::new(AtomicBool::new(false)),
474            device_sync: DeviceSync {
475                mode: device_sync_worker_mode,
476            },
477            fork_recovery_opts: fork_recovery_opts.unwrap_or_default(),
478            change_callbacks,
479            stream_policy,
480            worker_config,
481
482            worker_metrics: workers.sync_metrics_slot().clone(),
483            task_channels: workers.task_channels().clone(),
484            cancellation_token: CancellationToken::new(),
485            shutdown_complete: Arc::new(AtomicBool::new(false)),
486            foreground_calls: Default::default(),
487            delivery_owner: Default::default(),
488            retired_delivery_owner: Default::default(),
489            features: crate::features::MlsFeatures {
490                attachments,
491                incoming: Arc::new(incoming_runtime),
492                identity_resolutions: Arc::new(
493                    crate::identity_updates::IdentityResolutionRegistry::starting_after(
494                        own_inbox_stored_through,
495                    ),
496                ),
497            },
498        });
499
500        crate::core::preflight::bind_preflight(&context);
501
502        // register workers
503        if let Err(error) = context.features.attachments.sweep(&context).await {
504            tracing::warn!(%error, "attachment cleanup failed during client build");
505        }
506        if let Err(error) = context
507            .features
508            .attachments
509            .ensure_reconciled(&context)
510            .await
511        {
512            tracing::warn!(%error, "attachment reconciliation failed during client build");
513        }
514        if !disable_workers {
515            use crate::worker::WorkerKind;
516            // One source of truth for enablement: the folded WorkerConfig map.
517            let enabled = |k| context.worker_config().worker_enabled(k);
518
519            // Keep the original `device_sync_worker_enabled()` AND-check to
520            // preserve the exact legacy semantics alongside the map gate.
521            if enabled(WorkerKind::DeviceSync) && context.device_sync_worker_enabled() {
522                workers.register_new_worker::<SyncWorker<ContextParts<ApiClient, S, Db>>, _>(
523                    context.clone(),
524                );
525            }
526            if enabled(WorkerKind::DisappearingMessages) {
527                workers
528                    .register_new_worker::<DisappearingMessagesWorker<ContextParts<ApiClient, S, Db>>, _>(
529                        context.clone(),
530                    );
531            }
532            // Enable CommitLogWorker based on configuration
533            // The deployment decides whether the commit log runs,
534            // falling back to the compiled default when it says nothing.
535            if enabled(WorkerKind::CommitLog)
536                && context
537                    .server_configuration()
538                    .configuration()
539                    .mls
540                    .commit_log_enabled()
541                && !disable_commit_log_worker
542            {
543                workers.register_new_worker::<
544                crate::groups::commit_log::CommitLogWorker<ContextParts<ApiClient, S, Db>>,
545                _,
546                >(context.clone());
547            }
548            // Only a client that reads its configuration refreshes it.
549            // A caller-supplied provider owns its own values.
550            if enabled(WorkerKind::ConfigurationRefresh) && !has_config_provider {
551                workers.register_new_worker::<crate::core::config_refresh::ConfigurationWorker<
552                    ContextParts<ApiClient, S, Db>,
553                >, _>(context.clone());
554            }
555            if enabled(WorkerKind::TaskRunner) {
556                workers.register_new_worker::<TaskWorker<
557                    ContextParts<ApiClient, S, Db>,
558                    crate::task_handlers::MlsTaskHandlers,
559                >, _>(context.clone());
560                // KP maintenance is deliberately coupled to the TaskRunner (no
561                // standalone fallback): disabling the TaskRunner — per-kind via
562                // WorkerConfig or globally via disable_workers — disables KP
563                // rotation/deletion with it. Seeding failure is fatal to the
564                // build: the DB was already opened/migrated above, so an error
565                // here means it is broken; building a client whose critical
566                // maintenance silently never got seeded would be worse.
567                crate::worker::key_package_maintenance::seed_and_reconcile_kp_tasks(&context)?;
568                // One-time backfill: pending self-removes recorded before the
569                // worker became event-driven have no LeaveRequest to re-fire, so
570                // seed a ProcessPendingSelfRemove task for each already-flagged
571                // group. Best-effort (logged, never fails the build).
572                //
573                // TODO: remove this migration once all clients have shipped a
574                // release that enqueues these tasks inline — safe to delete by the
575                // next-next stable release.
576                if let Err(e) = backfill_pending_self_remove_tasks(&context) {
577                    tracing::warn!(
578                        "pending-self-remove backfill failed (will rely on next sync): {e}"
579                    );
580                }
581            }
582            if enabled(WorkerKind::AttachmentCleanup) && context.features.attachments.has_store() {
583                workers.register_new_worker::<crate::attachments::cleanup::AttachmentCleanup<
584                    ContextParts<ApiClient, S, Db>,
585                >, _>(context.clone());
586            }
587        }
588
589        // Every open client observes HMAC epoch changes, including clients
590        // that disable the other background workers.
591        workers.register_new_worker::<
592            crate::worker::hmac_epoch::HmacEpochWorker<ContextParts<ApiClient, S, Db>>,
593            _,
594        >(context.clone());
595
596        let workers = Arc::new(workers);
597
598        workers.spawn(context.clone());
599
600        log_event!(
601            Event::ClientCreated,
602            context.installation_id(),
603            inbox_id = context.inbox_id(),
604            device_sync_enabled = context.device_sync_worker_enabled(),
605            disabled_workers = disable_workers,
606        );
607
608        let installation_id = context.installation_id();
609        let client = Client {
610            context,
611            installation_id,
612            workers,
613            app_lifetime: Arc::new(crate::client::AppLifetime {
614                events: events_for_lifetime,
615            }),
616        };
617
618        Ok(client)
619    }
620}