src/connection.rs
1247 lines · 42894 bytes
50 symbols in this file
DEFAULT_SYNC_TIMEOUTTHREAD_LIST_PAGE_SIZESEND_RETRY_DELAYSSYNC_RETRY_INITIAL_DELAYSYNC_RETRY_MAX_DELAYROOM_METADATA_TIMEOUTSSO_CALLBACK_PORTis_retryable_network_errorsend_retry_delaysync_retry_delayshould_restart_completed_syncInteractiveAuthInfoas_auth_dataClientMessageConnectionruntimeclientspawntry_spawnget_custom_store_valueset_custom_store_valuejoin_room_on_runtimejoin_room_with_timeoutshutdownstop_sync_taskstop_receiver_tasknewsend_messagedelete_devicesdelete_deviceroom_messagesroom_threadsdevicessend_typing_noticemark_room_as_readsave_device_idload_device_idqueue_room_metadataresponse_receiversync_filtersync_looptestssend_retries_are_boundedsync_retry_delay_is_cappedcompleted_sync_restarts_unless_channel_is_closeddropruntime_boundary_testsrust_sourcesmatrix_sdk_async_io_is_owned_by_connection_runtimefallible_runtime_boundary_contains_task_panics
1use std::{
2 cell::RefCell,
3 future::Future,
4 path::PathBuf,
5 rc::{Rc, Weak},
6 time::Duration,
7};
8
9use tokio::{
10 runtime::Runtime,
11 sync::mpsc::{channel, Receiver, Sender},
12 task::JoinHandle,
13};
14
15use tracing::error;
16
17use matrix_sdk::{
18 self,
19 authentication::matrix::MatrixSession,
20 config::SyncSettings,
21 deserialized_responses::AmbiguityChange,
22 room::{Messages, MessagesOptions, Receipts, Room},
23 ruma::{
24 api::client::{
25 device::{
26 delete_device::{self, v3::Response as DeleteDeviceResponse},
27 delete_devices::v3::Response as DeleteDevicesResponse,
28 get_devices::v3::Response as DevicesResponse,
29 },
30 filter::{
31 FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter,
32 },
33 message::send_message_event,
34 session::{
35 get_login_types::v3::LoginType,
36 login::v3::Response as LoginResponse,
37 },
38 sync::sync_events::v3::Filter,
39 threads::get_threads::v1::{
40 IncludeThreads, Request as GetThreadsRequest,
41 Response as GetThreadsResponse,
42 },
43 uiaa::{AuthData, MatrixUserIdentifier, Password, UserIdentifier},
44 },
45 events::{
46 room::member::RoomMemberEventContent, AnyMessageLikeEventContent,
47 AnySyncEphemeralRoomEvent, AnySyncStateEvent, AnySyncTimelineEvent,
48 AnyToDeviceEvent, SyncStateEvent,
49 },
50 OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedTransactionId,
51 OwnedUserId,
52 },
53 store::RoomLoadSettings,
54 sync::State,
55 utils::local_server::LocalServerBuilder,
56 Client, HttpError, LoopCtrl, Result as MatrixResult, RoomMemberships,
57 SessionChange, SessionMeta, SessionTokens,
58};
59
60use weechat::{Task, Weechat};
61
62use crate::{
63 room::PrevBatch,
64 server::{InnerServer, MatrixServer},
65};
66
67const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
68const THREAD_LIST_PAGE_SIZE: u8 = 20;
69const SEND_RETRY_DELAYS: [Duration; 4] = [
70 Duration::from_secs(1),
71 Duration::from_secs(2),
72 Duration::from_secs(5),
73 Duration::from_secs(10),
74];
75const SYNC_RETRY_INITIAL_DELAY: Duration = Duration::from_secs(1);
76const SYNC_RETRY_MAX_DELAY: Duration = Duration::from_secs(60);
77const ROOM_METADATA_TIMEOUT: Duration = Duration::from_secs(30);
78const SSO_CALLBACK_PORT: u16 = 29_325;
79
80fn is_retryable_network_error(error: &matrix_sdk::Error) -> bool {
81 matches!(
82 error,
83 matrix_sdk::Error::Http(http)
84 if matches!(http.as_ref(), HttpError::Reqwest(_))
85 )
86}
87
88fn send_retry_delay(attempt: usize) -> Option<Duration> {
89 SEND_RETRY_DELAYS.get(attempt).copied()
90}
91
92fn sync_retry_delay(failures: u32) -> Duration {
93 let multiplier = 1u32.checked_shl(failures).unwrap_or(u32::MAX);
94 SYNC_RETRY_INITIAL_DELAY
95 .saturating_mul(multiplier)
96 .min(SYNC_RETRY_MAX_DELAY)
97}
98
99fn should_restart_completed_sync(channel_closed: bool) -> bool {
100 !channel_closed
101}
102
103pub struct InteractiveAuthInfo {
104 pub user: String,
105 pub password: String,
106 pub session: Option<String>,
107}
108
109impl InteractiveAuthInfo {
110 pub fn as_auth_data(&self) -> AuthData {
111 AuthData::Password(Password::new(
112 UserIdentifier::Matrix(MatrixUserIdentifier::new(
113 self.user.clone(),
114 )),
115 self.password.clone(),
116 ))
117 }
118}
119
120pub enum ClientMessage {
121 LoginMessage(LoginResponse),
122 SessionRestored(OwnedUserId),
123 SessionTokensRefreshed(SessionTokens),
124 SsoLoginUrl(String),
125 SyncState(OwnedRoomId, AnySyncStateEvent),
126 SyncEvent(OwnedRoomId, AnySyncTimelineEvent),
127 EphemeralRoomEvent(OwnedRoomId, AnySyncEphemeralRoomEvent),
128 ToDeviceEvent(AnyToDeviceEvent),
129 MemberEvent(
130 OwnedRoomId,
131 SyncStateEvent<RoomMemberEventContent>,
132 bool,
133 Option<AmbiguityChange>,
134 ),
135 RestoredRoom(OwnedRoomId),
136 RoomMetadata {
137 room_id: OwnedRoomId,
138 is_direct: bool,
139 display_name: Option<String>,
140 },
141}
142
143/// Struct representing an active connection to the homeserver.
144///
145/// Since the rust-sdk `Client` object uses reqwest for the HTTP client making
146/// requests requires the request to be made on a tokio runtime. The connection
147/// wraps the `Client` object and makes sure that requests are run on the
148/// runtime the `Connection` holds.
149///
150/// While this struct is alive a sync loop will be going on. To cancel the sync
151/// loop drop the object.
152#[derive(Debug, Clone)]
153pub struct Connection {
154 receiver_task: Rc<RefCell<Option<Task<()>>>>,
155 sync_task: Rc<RefCell<Option<JoinHandle<()>>>>,
156 client: Option<Client>,
157 runtime: Option<Rc<Runtime>>,
158}
159
160impl Connection {
161 pub fn runtime(&self) -> Rc<Runtime> {
162 self.runtime
163 .as_ref()
164 .expect("Connection runtime was already dropped")
165 .clone()
166 }
167
168 pub fn client(&self) -> &Client {
169 self.client
170 .as_ref()
171 .expect("Connection client was already dropped")
172 }
173
174 pub async fn spawn<F>(&self, future: F) -> F::Output
175 where
176 F: Future + Send + 'static,
177 F::Output: Send + 'static,
178 {
179 self.runtime()
180 .spawn(future)
181 .await
182 .expect("Tokio error while sending a message")
183 }
184
185 async fn try_spawn<F>(&self, future: F) -> Result<F::Output, String>
186 where
187 F: Future + Send + 'static,
188 F::Output: Send + 'static,
189 {
190 self.runtime()
191 .spawn(future)
192 .await
193 .map_err(|error| format!("Matrix runtime task failed: {error}"))
194 }
195
196 /// Read plugin-owned data from the Matrix state store on its Tokio runtime.
197 ///
198 /// Matrix SDK stores may use Tokio-backed pools internally. Keeping this
199 /// operation here prevents callers running on WeeChat's local executor from
200 /// polling those futures directly and aborting across the plugin FFI boundary.
201 pub async fn get_custom_store_value(
202 &self,
203 key: Vec<u8>,
204 ) -> Result<Option<Vec<u8>>, String> {
205 let client = self.client().clone();
206 self.try_spawn(async move {
207 client
208 .state_store()
209 .get_custom_value(&key)
210 .await
211 .map_err(|error| error.to_string())
212 })
213 .await?
214 }
215
216 /// Persist plugin-owned data on the Matrix SDK Tokio runtime.
217 pub async fn set_custom_store_value(
218 &self,
219 key: Vec<u8>,
220 value: Vec<u8>,
221 ) -> Result<(), String> {
222 let client = self.client().clone();
223 self.try_spawn(async move {
224 client
225 .state_store()
226 .set_custom_value_no_read(&key, value)
227 .await
228 .map_err(|error| error.to_string())
229 })
230 .await?
231 }
232
233 /// Join a room on the Matrix SDK Tokio runtime.
234 pub async fn join_room_on_runtime(
235 &self,
236 room_id: OwnedRoomId,
237 ) -> Result<Room, String> {
238 let client = self.client().clone();
239 self.try_spawn(async move { client.join_room_by_id(&room_id).await })
240 .await?
241 .map_err(|error| error.to_string())
242 }
243
244 /// Bound upgrade joins while polling both the timer and SDK on Tokio.
245 pub async fn join_room_with_timeout(
246 &self,
247 room_id: OwnedRoomId,
248 timeout: std::time::Duration,
249 ) -> Result<Result<Room, matrix_sdk::Error>, tokio::time::error::Elapsed>
250 {
251 let client = self.client().clone();
252 self.spawn(async move {
253 tokio::time::timeout(timeout, client.join_room_by_id(&room_id))
254 .await
255 })
256 .await
257 }
258
259 pub fn shutdown(&self) {
260 let runtime = self.runtime();
261
262 self.stop_sync_task(&runtime);
263 self.stop_receiver_task(&runtime);
264 }
265
266 fn stop_sync_task(&self, runtime: &Runtime) {
267 let Some(task) = self.sync_task.borrow_mut().take() else {
268 return;
269 };
270
271 task.abort();
272 let _ = runtime.block_on(async { task.await });
273 }
274
275 fn stop_receiver_task(&self, runtime: &Runtime) {
276 let Some(task) = self.receiver_task.borrow_mut().take() else {
277 return;
278 };
279
280 let _guard = runtime.enter();
281 drop(task);
282 }
283
284 pub fn new(server: &MatrixServer, client: &Client) -> Self {
285 let (tx, rx) = channel(10_000);
286
287 let server_name = server.name();
288
289 let receiver_task = Weechat::spawn(Connection::response_receiver(
290 rx,
291 server.clone_weak(),
292 ));
293
294 let runtime = Runtime::new().unwrap();
295
296 let sync_task = runtime.spawn(Connection::sync_loop(
297 client.clone(),
298 tx,
299 server.user_name(),
300 server.password(),
301 server.access_token(),
302 server.refresh_token(),
303 server.device_id(),
304 server_name.to_string(),
305 server.get_server_path(),
306 ));
307
308 Self {
309 receiver_task: Rc::new(RefCell::new(Some(receiver_task))),
310 sync_task: Rc::new(RefCell::new(Some(sync_task))),
311 client: Some(client.clone()),
312 runtime: Some(runtime.into()),
313 }
314 }
315
316 /// Send a message to the given room.
317 ///
318 /// # Arguments
319 ///
320 /// * `room_id` - The id of the room which the message should be sent to.
321 ///
322 /// * `content` - The content of the message that will be sent to the
323 /// server.
324 ///
325 /// * `transaction_id` - Attach an unique id to this message, later on the
326 /// event will contain the same id in the unsigned part of the event.
327 pub async fn send_message(
328 &self,
329 room: Room,
330 content: AnyMessageLikeEventContent,
331 transaction_id: Option<OwnedTransactionId>,
332 ) -> MatrixResult<send_message_event::v3::Response> {
333 self.spawn(async move {
334 let mut attempt = 0;
335
336 loop {
337 let mut msg = room.send(content.clone());
338 if let Some(txn_id) = transaction_id.as_deref() {
339 msg = msg.with_transaction_id(txn_id.to_owned());
340 }
341
342 match msg.await {
343 Ok(result) => return Ok(result.response),
344 Err(error)
345 if is_retryable_network_error(&error)
346 && send_retry_delay(attempt).is_some() =>
347 {
348 let delay = send_retry_delay(attempt)
349 .expect("delay checked above");
350 attempt += 1;
351 error!(
352 "Matrix message send failed due to a network error, retrying in {}s: {error}",
353 delay.as_secs()
354 );
355 tokio::time::sleep(delay).await;
356 }
357 Err(error) => return Err(error),
358 }
359 }
360 })
361 .await
362 }
363
364 pub async fn delete_devices(
365 &self,
366 devices: Vec<OwnedDeviceId>,
367 auth_info: Option<InteractiveAuthInfo>,
368 ) -> MatrixResult<DeleteDevicesResponse> {
369 let client = self.client().clone();
370 Ok(self
371 .spawn(async move {
372 if let Some(info) = auth_info {
373 let auth = Some(info.as_auth_data());
374 client.delete_devices(&devices, auth).await
375 } else {
376 client.delete_devices(&devices, None).await
377 }
378 })
379 .await?)
380 }
381
382 pub async fn delete_device(
383 &self,
384 device: OwnedDeviceId,
385 auth_info: Option<InteractiveAuthInfo>,
386 ) -> MatrixResult<DeleteDeviceResponse> {
387 let client = self.client().clone();
388 Ok(self
389 .spawn(async move {
390 let mut request = delete_device::v3::Request::new(device);
391 request.auth = auth_info.map(|info| info.as_auth_data());
392 client.send(request).await
393 })
394 .await?)
395 }
396
397 /// Fetch historical messages for the given room.
398 pub async fn room_messages(
399 &self,
400 room: Room,
401 prev_batch: PrevBatch,
402 limit: u16,
403 ) -> MatrixResult<Messages> {
404 self.spawn(async move {
405 let mut request = match &prev_batch {
406 PrevBatch::Backwards(t) => {
407 MessagesOptions::backward().from(t.as_deref())
408 }
409 PrevBatch::Forward(t) => {
410 MessagesOptions::forward().from(Some(t.as_ref()))
411 }
412 };
413 request.limit = limit.into();
414
415 room.messages(request).await
416 })
417 .await
418 }
419
420 /// List the thread roots of the given room.
421 ///
422 /// This is the `GET /_matrix/client/v1/rooms/{roomId}/threads` endpoint,
423 /// the only server-side way to discover threads without already knowing
424 /// their root event IDs.
425 pub async fn room_threads(
426 &self,
427 room_id: OwnedRoomId,
428 include: IncludeThreads,
429 from: Option<String>,
430 ) -> MatrixResult<GetThreadsResponse> {
431 let client = self.client().clone();
432 self.spawn(async move {
433 let mut request = GetThreadsRequest::new(room_id);
434 request.include = include;
435 request.from = from;
436 request.limit = Some(THREAD_LIST_PAGE_SIZE.into());
437
438 Ok(client.send(request).await?)
439 })
440 .await
441 }
442
443 /// Get the list of our own devices.
444 pub async fn devices(&self) -> MatrixResult<DevicesResponse> {
445 let client = self.client().clone();
446 Ok(self.spawn(async move { client.devices().await }).await?)
447 }
448
449 /// Set or reset a typing notice.
450 ///
451 /// # Arguments
452 ///
453 /// * `room_id` - The id of the room where the typing notice should be
454 /// active.
455 ///
456 /// * `typing` - Should we set or unset the typing notice.
457 pub async fn send_typing_notice(
458 &self,
459 room: Room,
460 typing: bool,
461 ) -> MatrixResult<()> {
462 self.spawn(async move { room.typing_notice(typing).await })
463 .await
464 }
465
466 pub async fn mark_room_as_read(
467 &self,
468 room: Room,
469 event_id: OwnedEventId,
470 public_receipt: bool,
471 ) -> MatrixResult<()> {
472 self.spawn(async move {
473 let receipts = Receipts::new().fully_read_marker(event_id.clone());
474 let receipts = if public_receipt {
475 receipts.public_read_receipt(event_id)
476 } else {
477 receipts.private_read_receipt(event_id)
478 };
479
480 room.send_multiple_receipts(receipts).await
481 })
482 .await
483 }
484
485 pub(crate) fn save_device_id(
486 user_name: &str,
487 mut server_path: PathBuf,
488 response: &LoginResponse,
489 ) -> std::io::Result<()> {
490 server_path.push(user_name);
491 server_path.set_extension("device_id");
492 std::fs::write(&server_path, &response.device_id)
493 }
494
495 fn load_device_id(
496 user_name: &str,
497 mut server_path: PathBuf,
498 ) -> std::io::Result<Option<String>> {
499 server_path.push(user_name);
500 server_path.set_extension("device_id");
501
502 let device_id = std::fs::read_to_string(server_path);
503
504 if let Err(e) = device_id {
505 // A file not found error is ok, report the rest.
506 if e.kind() != std::io::ErrorKind::NotFound {
507 return Err(e);
508 }
509 return Ok(None);
510 };
511
512 let device_id = device_id.unwrap_or_default();
513
514 if device_id.is_empty() {
515 Ok(None)
516 } else {
517 Ok(Some(device_id))
518 }
519 }
520
521 fn queue_room_metadata(
522 channel: Sender<Result<ClientMessage, String>>,
523 room: Room,
524 ) {
525 tokio::spawn(async move {
526 let room_id = room.room_id().to_owned();
527 let is_direct =
528 tokio::time::timeout(ROOM_METADATA_TIMEOUT, room.is_direct())
529 .await
530 .ok()
531 .and_then(Result::ok)
532 .unwrap_or(false);
533 let display_name = tokio::time::timeout(
534 ROOM_METADATA_TIMEOUT,
535 room.display_name(),
536 )
537 .await
538 .ok()
539 .and_then(Result::ok)
540 .map(|name| name.to_string());
541
542 let _ = channel
543 .send(Ok(ClientMessage::RoomMetadata {
544 room_id,
545 is_direct,
546 display_name,
547 }))
548 .await;
549 });
550 }
551
552 /// Response receiver loop.
553 /// This runs on the main Weechat thread and listens for responses coming
554 /// from the client running in the tokio executor.
555 pub async fn response_receiver(
556 mut receiver: Receiver<Result<ClientMessage, String>>,
557 server: Weak<InnerServer>,
558 ) {
559 while let Some(message) = receiver.recv().await {
560 let server = if let Some(s) = server.upgrade() {
561 s
562 } else {
563 return;
564 };
565
566 match message {
567 Ok(message) => match message {
568 ClientMessage::LoginMessage(r) => server.receive_login(r),
569 ClientMessage::SessionRestored(user_id) => {
570 server.receive_restored_login(user_id)
571 }
572 ClientMessage::SessionTokensRefreshed(tokens) => {
573 server.receive_session_tokens(tokens)
574 }
575 ClientMessage::SsoLoginUrl(url) => {
576 server.receive_sso_url(&url)
577 }
578 ClientMessage::SyncEvent(r, e) => {
579 server.receive_joined_timeline_event(&r, e).await
580 }
581 ClientMessage::SyncState(r, e) => {
582 server.receive_joined_state_event(&r, e).await
583 }
584 ClientMessage::EphemeralRoomEvent(r, e) => {
585 server.receive_joined_ephemeral_event(&r, e).await
586 }
587 ClientMessage::RestoredRoom(room_id) => {
588 server.restore_room_by_id(room_id).await
589 }
590 ClientMessage::RoomMetadata {
591 room_id,
592 is_direct,
593 display_name,
594 } => server.receive_room_metadata(
595 room_id,
596 is_direct,
597 display_name,
598 ),
599 ClientMessage::ToDeviceEvent(e) => {
600 server.receive_to_device_event(e).await
601 }
602 ClientMessage::MemberEvent(
603 room_id,
604 e,
605 is_state,
606 change,
607 ) => {
608 server
609 .receive_member(room_id, e, is_state, change)
610 .await
611 }
612 },
613 Err(e) => server.print_error(&format!("Ruma error {}", e)),
614 };
615 }
616 }
617
618 #[allow(clippy::field_reassign_with_default)]
619 fn sync_filter() -> FilterDefinition {
620 let mut filter = FilterDefinition::default();
621 let mut room_filter = RoomFilter::default();
622 let mut event_filter = RoomEventFilter::default();
623
624 event_filter.lazy_load_options = LazyLoadOptions::Enabled {
625 include_redundant_members: false,
626 };
627 event_filter.limit = Some(10u16.into());
628
629 room_filter.state = event_filter;
630 filter.room = room_filter;
631
632 filter
633 }
634
635 /// Main client sync loop.
636 /// This runs on the per server tokio executor.
637 /// It communicates with the main Weechat thread using a async channel.
638 pub async fn sync_loop(
639 client: Client,
640 channel: Sender<Result<ClientMessage, String>>,
641 username: String,
642 password: String,
643 access_token: String,
644 refresh_token: String,
645 device_id: String,
646 server_name: String,
647 server_path: PathBuf,
648 ) {
649 if !client.matrix_auth().logged_in() && !access_token.is_empty() {
650 let user_id = match username.parse::<OwnedUserId>() {
651 Ok(user_id) => user_id,
652 Err(error) => {
653 let _ = channel
654 .send(Err(format!(
655 "Invalid Matrix user ID for restored session: {error}"
656 )))
657 .await;
658 return;
659 }
660 };
661 if device_id.is_empty() {
662 let _ = channel
663 .send(Err(
664 "A device ID is required with a Matrix access token"
665 .to_owned(),
666 ))
667 .await;
668 return;
669 }
670 let session = MatrixSession {
671 meta: SessionMeta {
672 user_id: user_id.clone(),
673 device_id: OwnedDeviceId::from(device_id),
674 },
675 tokens: SessionTokens {
676 access_token,
677 refresh_token: (!refresh_token.is_empty())
678 .then_some(refresh_token),
679 },
680 };
681 if let Err(error) = client
682 .matrix_auth()
683 .restore_session(session, RoomLoadSettings::default())
684 .await
685 {
686 let _ = channel
687 .send(Err(format!(
688 "Failed to restore Matrix access-token session: {error}"
689 )))
690 .await;
691 return;
692 }
693 if channel
694 .send(Ok(ClientMessage::SessionRestored(user_id)))
695 .await
696 .is_err()
697 {
698 return;
699 }
700 for room in client.joined_rooms() {
701 Self::queue_room_metadata(channel.clone(), room.clone());
702 if channel
703 .send(Ok(ClientMessage::RestoredRoom(
704 room.room_id().to_owned(),
705 )))
706 .await
707 .is_err()
708 {
709 return;
710 }
711 }
712 }
713
714 if !client.matrix_auth().logged_in() {
715 let device_id_key = if username.is_empty() {
716 server_name.as_str()
717 } else {
718 username.as_str()
719 };
720
721 let device_id =
722 Connection::load_device_id(device_id_key, server_path.clone());
723
724 let device_id = match device_id {
725 Err(e) => {
726 // TODO: do we want to do something with channel.send()
727 // errors?
728 let _ = channel
729 .send(Err(format!(
730 "Error while reading the device id for server {}: {:?}",
731 server_name, e
732 )))
733 .await;
734 return;
735 }
736 Ok(d) => d,
737 };
738
739 let first_login = device_id.is_none();
740 let matrix_auth = client.matrix_auth();
741
742 let login_response = if password.is_empty() {
743 let login_types = match matrix_auth.get_login_types().await {
744 Ok(response) => response,
745 Err(e) => {
746 let _ = channel
747 .send(Err(format!(
748 "Failed to get login types: {}",
749 e
750 )))
751 .await;
752 return;
753 }
754 };
755
756 let has_sso = login_types
757 .flows
758 .iter()
759 .any(|flow| matches!(flow, LoginType::Sso(_)));
760
761 if !has_sso {
762 let _ = channel
763 .send(Err(
764 "No password configured and homeserver does not advertise SSO login"
765 .to_owned(),
766 ))
767 .await;
768 return;
769 }
770
771 let url_sender = channel.clone();
772 let mut builder = matrix_auth
773 .login_sso(move |sso_url| {
774 async move {
775 let _ = url_sender
776 .send(Ok(ClientMessage::SsoLoginUrl(sso_url)))
777 .await;
778 // Handing the URL to WeeChat successfully completes
779 // our callback; returning an error would abort SSO.
780 Ok(())
781 }
782 })
783 .initial_device_display_name("WeeChat-Matrix-rs")
784 .server_builder(
785 LocalServerBuilder::new().port_range(
786 SSO_CALLBACK_PORT..SSO_CALLBACK_PORT + 1,
787 ),
788 );
789
790 if let Some(device_id) = device_id.as_ref() {
791 builder = builder.device_id(device_id);
792 };
793
794 builder.send().await
795 } else {
796 let mut builder = matrix_auth
797 .login_username(&username, &password)
798 .initial_device_display_name("WeeChat-Matrix-rs");
799
800 if let Some(device_id) = device_id.as_ref() {
801 builder = builder.device_id(device_id);
802 };
803
804 builder.send().await
805 };
806
807 match login_response {
808 Ok(response) => {
809 if let Err(e) = Connection::save_device_id(
810 device_id_key,
811 server_path.clone(),
812 &response,
813 ) {
814 let _ = channel
815 .send(Err(format!(
816 "Error while writing the device id for server {}: {:?}",
817 server_name, e
818 ))).await;
819 return;
820 }
821
822 if channel
823 .send(Ok(ClientMessage::LoginMessage(response)))
824 .await
825 .is_err()
826 {
827 return;
828 }
829 }
830 Err(e) => {
831 let _ = channel
832 .send(Err(format!("Failed to log in: {:?}", e)))
833 .await;
834 return;
835 }
836 }
837
838 if !first_login {
839 for room in client.joined_rooms() {
840 Self::queue_room_metadata(channel.clone(), room.clone());
841 if channel
842 .send(Ok(ClientMessage::RestoredRoom(
843 room.room_id().to_owned(),
844 )))
845 .await
846 .is_err()
847 {
848 return;
849 }
850 }
851 }
852 }
853
854 // Refresh tokens can be rotated by the homeserver. Persist every
855 // rotated pair on the WeeChat thread so a later restart does not try
856 // the now-invalid token from the original login.
857 let mut session_changes = client.subscribe_to_session_changes();
858 let session_client = client.clone();
859 let session_channel = channel.clone();
860 tokio::spawn(async move {
861 loop {
862 tokio::select! {
863 _ = session_channel.closed() => return,
864 change = session_changes.recv() => {
865 match change {
866 Ok(SessionChange::TokensRefreshed) => {
867 let Some(tokens) =
868 session_client.session_tokens()
869 else {
870 continue;
871 };
872
873 if session_channel
874 .send(Ok(
875 ClientMessage::SessionTokensRefreshed(
876 tokens,
877 ),
878 ))
879 .await
880 .is_err()
881 {
882 return;
883 }
884 }
885 Ok(SessionChange::UnknownToken { .. }) => {}
886 Err(
887 tokio::sync::broadcast::error::RecvError::Lagged(
888 _,
889 ),
890 ) => {
891 // The current client tokens are authoritative;
892 // the next refresh notification will persist
893 // their latest value.
894 }
895 Err(
896 tokio::sync::broadcast::error::RecvError::Closed,
897 ) => return,
898 }
899 }
900 }
901 }
902 });
903
904 let mut filter_failures = 0;
905 let filter = loop {
906 match client
907 .get_or_upload_filter("sync", Connection::sync_filter())
908 .await
909 {
910 Ok(filter) => break filter,
911 Err(error) if is_retryable_network_error(&error) => {
912 let delay = sync_retry_delay(filter_failures);
913 filter_failures = filter_failures.saturating_add(1);
914 error!(
915 "Matrix filter upload failed due to a network error, retrying in {}s: {error}",
916 delay.as_secs()
917 );
918 tokio::time::sleep(delay).await;
919 }
920 Err(error) => {
921 let _ = channel
922 .send(Err(format!(
923 "Failed to upload Matrix sync filter: {error}"
924 )))
925 .await;
926 return;
927 }
928 }
929 };
930
931 let sync_token: Option<String> = None;
932 let sync_settings = SyncSettings::new()
933 .timeout(DEFAULT_SYNC_TIMEOUT)
934 .filter(Filter::FilterId(filter));
935
936 let sync_settings = if let Some(t) = sync_token {
937 sync_settings.token(t)
938 } else {
939 sync_settings
940 };
941
942 let sync_channel = &channel;
943
944 let client_ref = &client;
945
946 let mut sync_failures = 0;
947 loop {
948 let ret = client
949 .sync_with_callback(sync_settings.clone(), |response| async move {
950 for event in response.to_device.iter().filter_map(|e| e.to_raw().deserialize().ok()){
951 if sync_channel
952 .send(Ok(ClientMessage::ToDeviceEvent(event)))
953 .await
954 .is_err()
955 {
956 return LoopCtrl::Break;
957 }
958 }
959
960 for (room_id, room) in response.rooms.joined {
961 if let Some(room) = client_ref.get_room(&room_id) {
962 Self::queue_room_metadata(
963 sync_channel.clone(),
964 room.clone(),
965 );
966 }
967 let state_events = match &room.state {
968 State::Before(state) | State::After(state) => state,
969 };
970
971 for event in
972 state_events.iter().filter_map(|e| e.deserialize().ok())
973 {
974 if let AnySyncStateEvent::RoomMember(m) = event {
975 let change = room
976 .ambiguity_changes
977 .get(m.event_id())
978 .cloned();
979
980 if sync_channel
981 .send(Ok(ClientMessage::MemberEvent(
982 room_id.clone(),
983 m,
984 true,
985 change,
986 )))
987 .await
988 .is_err()
989 {
990 return LoopCtrl::Break;
991 }
992 } else if sync_channel
993 .send(Ok(ClientMessage::SyncState(
994 room_id.clone(),
995 event,
996 )))
997 .await
998 .is_err()
999 {
1000 return LoopCtrl::Break;
1001 }
1002 }
1003
1004 for event in room
1005 .ephemeral
1006 .iter()
1007 .filter_map(|e| e.deserialize().ok())
1008 {
1009 if sync_channel
1010 .send(Ok(ClientMessage::EphemeralRoomEvent(
1011 room_id.clone(),
1012 event,
1013 )))
1014 .await
1015 .is_err()
1016 {
1017 return LoopCtrl::Break;
1018 }
1019 }
1020
1021 for event in room
1022 .timeline
1023 .events
1024 .iter()
1025 .filter_map(|e| e.raw().deserialize().ok())
1026 {
1027 if let AnySyncTimelineEvent::State(
1028 AnySyncStateEvent::RoomMember(m),
1029 ) = event
1030 {
1031 let change = room
1032 .ambiguity_changes
1033 .get(m.event_id())
1034 .cloned();
1035
1036 if sync_channel
1037 .send(Ok(ClientMessage::MemberEvent(
1038 room_id.clone(),
1039 m,
1040 false,
1041 change,
1042 )))
1043 .await
1044 .is_err()
1045 {
1046 return LoopCtrl::Break;
1047 }
1048 } else if sync_channel
1049 .send(Ok(ClientMessage::SyncEvent(
1050 room_id.clone(),
1051 event,
1052 )))
1053 .await
1054 .is_err()
1055 {
1056 return LoopCtrl::Break;
1057 }
1058 }
1059
1060 if let Some(r) = client_ref.get_room(&room_id) {
1061 if !r.are_members_synced() {
1062 let room_id = room_id.clone();
1063 let channel = sync_channel.clone();
1064
1065 tokio::spawn(async move {
1066 if let Ok(members) =
1067 r.members(RoomMemberships::ACTIVE).await
1068 {
1069 for member in members {
1070 if let Err(e) = channel
1071 .send(Ok(
1072 ClientMessage::MemberEvent(
1073 room_id.clone(),
1074 member.event().as_sync().expect("Member event is not a StateSyncEvent").to_owned(),
1075 true,
1076 None,
1077 ),
1078 ))
1079 .await
1080 {
1081 error!(
1082 "Failed to send room member {}",
1083 e
1084 );
1085 }
1086 }
1087 }
1088 });
1089 }
1090 }
1091 }
1092
1093 LoopCtrl::Continue
1094 })
1095 .await;
1096
1097 match ret {
1098 Err(err) if channel.is_closed() => {
1099 error!("Matrix sync failed during shutdown: {err}");
1100 break;
1101 }
1102 Err(err) => {
1103 let delay = sync_retry_delay(sync_failures);
1104 sync_failures = sync_failures.saturating_add(1);
1105 error!(
1106 "Matrix sync failed, retrying in {}s: {err}",
1107 delay.as_secs()
1108 );
1109 tokio::time::sleep(delay).await;
1110 }
1111 Ok(())
1112 if should_restart_completed_sync(channel.is_closed()) =>
1113 {
1114 let delay = sync_retry_delay(sync_failures);
1115 sync_failures = sync_failures.saturating_add(1);
1116 error!(
1117 "Matrix sync stopped unexpectedly, restarting in {}s",
1118 delay.as_secs()
1119 );
1120 tokio::time::sleep(delay).await;
1121 }
1122 Ok(()) => break,
1123 }
1124 }
1125 }
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130 use super::*;
1131
1132 #[test]
1133 fn send_retries_are_bounded() {
1134 assert_eq!(send_retry_delay(0), Some(Duration::from_secs(1)));
1135 assert_eq!(send_retry_delay(3), Some(Duration::from_secs(10)));
1136 assert_eq!(send_retry_delay(4), None);
1137 }
1138
1139 #[test]
1140 fn sync_retry_delay_is_capped() {
1141 assert_eq!(sync_retry_delay(0), Duration::from_secs(1));
1142 assert_eq!(sync_retry_delay(1), Duration::from_secs(2));
1143 assert_eq!(sync_retry_delay(6), Duration::from_secs(60));
1144 assert_eq!(sync_retry_delay(31), Duration::from_secs(60));
1145 }
1146
1147 #[test]
1148 fn completed_sync_restarts_unless_channel_is_closed() {
1149 assert!(should_restart_completed_sync(false));
1150 assert!(!should_restart_completed_sync(true));
1151 }
1152}
1153
1154impl Drop for Connection {
1155 fn drop(&mut self) {
1156 let Some(runtime) = self.runtime.as_ref().cloned() else {
1157 return;
1158 };
1159
1160 if Rc::strong_count(&runtime) == 1 {
1161 self.stop_sync_task(&runtime);
1162 self.stop_receiver_task(&runtime);
1163 }
1164
1165 if let Some(client) = self.client.take() {
1166 let _guard = runtime.enter();
1167 drop(client);
1168 }
1169
1170 if Rc::strong_count(&runtime) == 1 {
1171 let runtime = self.runtime.take().expect("runtime disappeared");
1172 let handle = runtime.handle().clone();
1173 let _guard = handle.enter();
1174 drop(runtime);
1175 }
1176 }
1177}
1178
1179#[cfg(test)]
1180mod runtime_boundary_tests {
1181 use std::{cell::RefCell, fs, path::Path, rc::Rc};
1182
1183 use tokio::runtime::Runtime;
1184
1185 use super::Connection;
1186
1187 fn rust_sources(path: &Path, files: &mut Vec<std::path::PathBuf>) {
1188 for entry in fs::read_dir(path).expect("source directory is readable") {
1189 let path = entry.expect("source entry is readable").path();
1190 if path.is_dir() {
1191 rust_sources(&path, files);
1192 } else if path
1193 .extension()
1194 .is_some_and(|extension| extension == "rs")
1195 {
1196 files.push(path);
1197 }
1198 }
1199 }
1200
1201 #[test]
1202 fn matrix_sdk_async_io_is_owned_by_connection_runtime() {
1203 let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
1204 let connection = source_root.join("connection.rs");
1205 let mut files = Vec::new();
1206 rust_sources(&source_root, &mut files);
1207
1208 for path in files {
1209 if path == connection {
1210 continue;
1211 }
1212 let source =
1213 fs::read_to_string(&path).expect("Rust source is readable");
1214 let compact = source
1215 .chars()
1216 .filter(|character| !character.is_whitespace())
1217 .collect::<String>();
1218 for forbidden in [".state_store()", ".join_room_by_id("] {
1219 assert!(
1220 !compact.contains(forbidden),
1221 "{} calls {forbidden} outside connection.rs; route Matrix SDK async I/O through Connection",
1222 path.display()
1223 );
1224 }
1225 }
1226 }
1227
1228 #[test]
1229 fn fallible_runtime_boundary_contains_task_panics() {
1230 let runtime = Rc::new(Runtime::new().expect("test runtime starts"));
1231 let connection = Connection {
1232 receiver_task: Rc::new(RefCell::new(None)),
1233 sync_task: Rc::new(RefCell::new(None)),
1234 client: None,
1235 runtime: Some(runtime.clone()),
1236 };
1237
1238 let error =
1239 runtime
1240 .block_on(connection.try_spawn(async {
1241 panic!("simulated Matrix SDK task panic")
1242 }))
1243 .expect_err("task panic becomes an error");
1244
1245 assert!(error.contains("task") && error.contains("panicked"));
1246 }
1247}