tuwunel_service/migrations/
email_bindings.rs1use std::sync::Arc;
2
3use futures::TryStreamExt;
4use ruma::{MilliSecondsSinceUnixEpoch, thirdparty::Medium};
5use tuwunel_core::{Err, Result, debug_warn, err, info, warn};
6use tuwunel_database::Map;
7
8use crate::{
9 Services,
10 integrity::email_bindings::{Bindable, Row, bindable, column, rows},
11};
12
13pub(super) async fn migrate_email_bindings(services: &Services) -> Result {
21 let Some(localpart_email) = column(services)? else {
22 return Ok(());
23 };
24
25 adopt_email_bindings(services, &localpart_email).await
26}
27
28pub(super) async fn adopt_email_bindings(
34 services: &Services,
35 localpart_email: &Arc<Map>,
36) -> Result {
37 let bound_at = MilliSecondsSinceUnixEpoch::now();
38 let cork = services.db.cork_and_sync();
39
40 let (adopted, skipped, unreadable) = rows(services, localpart_email)
41 .try_fold((0_usize, 0_usize, 0_usize), async |acc, row| {
42 Ok(tally_adoption(acc, adopt_one(services, bound_at, row).await))
43 })
44 .await?;
45
46 drop(cork);
47
48 match skipped {
49 | 0 if adopted > 0 => info!(%adopted, "Adopted email bindings from a foreign database"),
50 | 0 => (),
51 | _ => warn!(
52 %adopted,
53 %skipped,
54 "Adopted email bindings from a foreign database; some addresses were left behind"
55 ),
56 }
57
58 unreadable
61 .eq(&0)
62 .then_some(())
63 .ok_or_else(|| err!(Database("{unreadable} email bindings could not be read")))
64}
65
66async fn adopt_one(
73 services: &Services,
74 bound_at: MilliSecondsSinceUnixEpoch,
75 row: Row,
76) -> Result<bool> {
77 let (user_id, address) = match row {
78 | Row::Binding { user_id, address, .. } => (user_id, address),
79 | Row::UnusableLocalpart { localpart } => {
80 debug_warn!(%localpart, "skipping an unusable localpart");
81 return Ok(false);
82 },
83 | Row::Unparsable { key } => {
84 let key = key.escape_ascii();
85
86 return Err!(Database("email binding {key} is not text"));
87 },
88 };
89
90 let email_canon = match bindable(services, &user_id, &address).await? {
91 | Bindable::NoAccount => return Ok(false),
92 | Bindable::Canonical(email_canon) => email_canon,
93 | Bindable::UnusableAddress => {
94 debug_warn!(localpart = %user_id.localpart(), "skipping an unusable address");
95 return Ok(false);
96 },
97 };
98
99 services
100 .threepid
101 .bind_unclaimed(&user_id, &email_canon, Medium::Email, bound_at)
102 .await
103}
104
105fn tally_adoption(
106 (adopted, skipped, unreadable): (usize, usize, usize),
107 result: Result<bool>,
108) -> (usize, usize, usize) {
109 match result {
110 | Ok(true) => (adopted.saturating_add(1), skipped, unreadable),
111 | Ok(false) => (adopted, skipped.saturating_add(1), unreadable),
112 | Err(e) => {
113 warn!(error = %e, "an email binding could not be read");
114
115 (adopted, skipped, unreadable.saturating_add(1))
116 },
117 }
118}