1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::sync::Arc;
use matrix_sdk_base::{locks::RwLock, store::StoreConfig, BaseClient, StateStore};
use ruma::{
api::{client::discovery::discover_homeserver, error::FromHttpResponseError, MatrixVersion},
OwnedServerName, ServerName, UserId,
};
use thiserror::Error;
use url::Url;
use super::{Client, ClientInner};
use crate::{
config::RequestConfig,
error::RumaApiError,
http_client::{HttpClient, HttpSend, HttpSettings},
HttpError,
};
#[must_use]
#[derive(Debug)]
pub struct ClientBuilder {
homeserver_cfg: Option<HomeserverConfig>,
http_cfg: Option<HttpConfig>,
store_config: StoreConfig,
request_config: RequestConfig,
respect_login_well_known: bool,
appservice_mode: bool,
server_versions: Option<Arc<[MatrixVersion]>>,
}
impl ClientBuilder {
pub(crate) fn new() -> Self {
Self {
homeserver_cfg: None,
http_cfg: None,
store_config: Default::default(),
request_config: Default::default(),
respect_login_well_known: true,
appservice_mode: false,
server_versions: None,
}
}
pub fn homeserver_url(mut self, url: impl AsRef<str>) -> Self {
self.homeserver_cfg = Some(HomeserverConfig::Url(url.as_ref().to_owned()));
self
}
pub fn user_id(self, user_id: &UserId) -> Self {
self.server_name(user_id.server_name())
}
pub fn server_name(mut self, server_name: &ServerName) -> Self {
self.homeserver_cfg = Some(HomeserverConfig::ServerName(server_name.to_owned()));
self
}
pub fn store_config(mut self, store_config: StoreConfig) -> Self {
self.store_config = store_config;
self
}
pub fn state_store(mut self, store: Box<dyn StateStore>) -> Self {
self.store_config = self.store_config.state_store(store);
self
}
#[cfg(feature = "e2e-encryption")]
pub fn crypto_store(
mut self,
store: Box<dyn matrix_sdk_base::crypto::store::CryptoStore>,
) -> Self {
self.store_config = self.store_config.crypto_store(store);
self
}
pub fn respect_login_well_known(mut self, value: bool) -> Self {
self.respect_login_well_known = value;
self
}
pub fn request_config(mut self, request_config: RequestConfig) -> Self {
self.request_config = request_config;
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn proxy(mut self, proxy: impl AsRef<str>) -> Self {
self.http_settings().proxy = Some(proxy.as_ref().to_owned());
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn disable_ssl_verification(mut self) -> Self {
self.http_settings().disable_ssl_verification = true;
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn user_agent(mut self, user_agent: impl AsRef<str>) -> Self {
self.http_settings().user_agent = Some(user_agent.as_ref().to_owned());
self
}
pub fn http_client(mut self, client: Arc<dyn HttpSend>) -> Self {
self.http_cfg = Some(HttpConfig::Custom(client));
self
}
#[doc(hidden)]
#[cfg(feature = "appservice")]
pub fn appservice_mode(mut self) -> Self {
self.appservice_mode = true;
self
}
#[doc(hidden)]
#[cfg(feature = "appservice")]
pub fn assert_identity(mut self) -> Self {
self.request_config.assert_identity = true;
self
}
pub fn server_versions(mut self, value: impl IntoIterator<Item = MatrixVersion>) -> Self {
self.server_versions = Some(value.into_iter().collect());
self
}
#[cfg(not(target_arch = "wasm32"))]
fn http_settings(&mut self) -> &mut HttpSettings {
self.http_cfg.get_or_insert_with(Default::default).settings()
}
pub async fn build(self) -> Result<Client, ClientBuildError> {
let homeserver_cfg = self.homeserver_cfg.ok_or(ClientBuildError::MissingHomeserver)?;
let inner_http_client = match self.http_cfg.unwrap_or_default() {
#[allow(unused_mut)]
HttpConfig::Settings(mut settings) => {
#[cfg(not(target_arch = "wasm32"))]
{
settings.timeout = self.request_config.timeout;
}
Arc::new(settings.make_client()?)
}
HttpConfig::Custom(c) => c,
};
let base_client = BaseClient::with_store_config(self.store_config);
let mk_http_client = |homeserver| {
HttpClient::new(
inner_http_client.clone(),
homeserver,
base_client.session().clone(),
self.request_config,
)
};
let homeserver = match homeserver_cfg {
HomeserverConfig::Url(url) => url,
HomeserverConfig::ServerName(server_name) => {
let homeserver = homeserver_from_name(&server_name)?;
let http_client = mk_http_client(Arc::new(RwLock::new(homeserver)));
let well_known = http_client
.send(
discover_homeserver::Request::new(),
None,
[MatrixVersion::V1_0].into_iter().collect(),
)
.await
.map_err(|e| match e {
HttpError::Api(err) => ClientBuildError::AutoDiscovery(err),
err => ClientBuildError::Http(err),
})?;
well_known.homeserver.base_url
}
};
let homeserver = Arc::new(RwLock::new(Url::parse(&homeserver)?));
let http_client = mk_http_client(homeserver.clone());
#[cfg(target_arch = "wasm32")]
let server_versions = {
let cell = async_once_cell::OnceCell::new();
if let Some(server_versions) = self.server_versions {
cell.get_or_init(async move { server_versions }).await;
}
cell
};
#[cfg(not(target_arch = "wasm32"))]
let server_versions = tokio::sync::OnceCell::new_with(self.server_versions);
let inner = Arc::new(ClientInner {
homeserver,
http_client,
base_client,
server_versions,
#[cfg(feature = "e2e-encryption")]
group_session_locks: Default::default(),
#[cfg(feature = "e2e-encryption")]
key_claim_lock: Default::default(),
members_request_locks: Default::default(),
typing_notice_times: Default::default(),
event_handlers: Default::default(),
event_handler_data: Default::default(),
notification_handlers: Default::default(),
appservice_mode: self.appservice_mode,
respect_login_well_known: self.respect_login_well_known,
sync_beat: event_listener::Event::new(),
});
Ok(Client { inner })
}
}
fn homeserver_from_name(server_name: &ServerName) -> Result<Url, url::ParseError> {
#[cfg(not(test))]
let homeserver = format!("https://{}", server_name);
#[cfg(test)]
let homeserver = format!("http://{}", server_name);
Url::parse(&homeserver)
}
#[derive(Debug)]
enum HomeserverConfig {
Url(String),
ServerName(OwnedServerName),
}
#[derive(Debug)]
enum HttpConfig {
Settings(HttpSettings),
Custom(Arc<dyn HttpSend>),
}
#[cfg(not(target_arch = "wasm32"))]
impl HttpConfig {
fn settings(&mut self) -> &mut HttpSettings {
match self {
Self::Settings(s) => s,
Self::Custom(_) => {
*self = Self::default();
match self {
Self::Settings(s) => s,
Self::Custom(_) => unreachable!(),
}
}
}
}
}
impl Default for HttpConfig {
fn default() -> Self {
Self::Settings(HttpSettings::default())
}
}
#[derive(Debug, Error)]
pub enum ClientBuildError {
#[error("no homeserver or user ID was configured")]
MissingHomeserver,
#[error("Error looking up the .well-known endpoint on auto-discovery")]
AutoDiscovery(FromHttpResponseError<RumaApiError>),
#[error(transparent)]
Url(#[from] url::ParseError),
#[error(transparent)]
Http(#[from] HttpError),
#[cfg(feature = "indexeddb")]
#[error(transparent)]
IndexeddbStore(#[from] matrix_sdk_indexeddb::OpenStoreError),
#[cfg(feature = "sled")]
#[error(transparent)]
SledStore(#[from] matrix_sdk_sled::OpenStoreError),
}
impl ClientBuildError {
#[doc(hidden)]
pub fn assert_valid_builder_args(self) -> HttpError {
match self {
ClientBuildError::Http(e) => e,
_ => unreachable!("homeserver URL was asserted to be valid"),
}
}
}