Commit d6dd9f720d

d6dd9f720d57b2ad9e3062e31cd1145dc2783dec

parent: ecd22dd5b9

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-08-11 10:41 UTC
committer: <strk@kbt.io>

fix: retry Matrix network reconnects

Layout: unified · split

Cargo.toml +1 −1
@@ -39,7 +39,7 @@ dashmap = "6.1.0"
39url = "2.3.1" 39url = "2.3.1"
40serde_json = "1.0.85" 40serde_json = "1.0.85"
41strum = { version = "0.24.0", features = ["derive"] } 41strum = { version = "0.24.0", features = ["derive"] }
42tokio = { version = "1.21.1", features = ["rt-multi-thread", "sync"] } 42tokio = { version = "1.21.1", features = ["rt-multi-thread", "sync", "time"] }
43tracing = "0.1.36" 43tracing = "0.1.36"
44tracing-subscriber = { version = "0.3.15", features = ["env-filter"] } 44tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
45uuid = { version = "1.1.2", features = ["v4"] } 45uuid = { version = "1.1.2", features = ["v4"] }
src/connection.rs +137 −15
@@ -49,8 +49,8 @@ use matrix_sdk::{
49 store::RoomLoadSettings, 49 store::RoomLoadSettings,
50 sync::State, 50 sync::State,
51 utils::local_server::LocalServerBuilder, 51 utils::local_server::LocalServerBuilder,
52 Client, LoopCtrl, Result as MatrixResult, RoomMemberships, SessionChange, 52 Client, HttpError, LoopCtrl, Result as MatrixResult, RoomMemberships,
53 SessionMeta, SessionTokens, 53 SessionChange, SessionMeta, SessionTokens,
54}; 54};
55 55
56use weechat::{Task, Weechat}; 56use weechat::{Task, Weechat};
@@ -61,8 +61,39 @@ use crate::{
61}; 61};
62 62
63const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30); 63const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
64const SEND_RETRY_DELAYS: [Duration; 4] = [
65 Duration::from_secs(1),
66 Duration::from_secs(2),
67 Duration::from_secs(5),
68 Duration::from_secs(10),
69];
70const SYNC_RETRY_INITIAL_DELAY: Duration = Duration::from_secs(1);
71const SYNC_RETRY_MAX_DELAY: Duration = Duration::from_secs(60);
64const SSO_CALLBACK_PORT: u16 = 29_325; 72const SSO_CALLBACK_PORT: u16 = 29_325;
65 73
74fn is_retryable_network_error(error: &matrix_sdk::Error) -> bool {
75 matches!(
76 error,
77 matrix_sdk::Error::Http(http)
78 if matches!(http.as_ref(), HttpError::Reqwest(_))
79 )
80}
81
82fn send_retry_delay(attempt: usize) -> Option<Duration> {
83 SEND_RETRY_DELAYS.get(attempt).copied()
84}
85
86fn sync_retry_delay(failures: u32) -> Duration {
87 let multiplier = 1u32.checked_shl(failures).unwrap_or(u32::MAX);
88 SYNC_RETRY_INITIAL_DELAY
89 .saturating_mul(multiplier)
90 .min(SYNC_RETRY_MAX_DELAY)
91}
92
93fn should_restart_completed_sync(channel_closed: bool) -> bool {
94 !channel_closed
95}
96
66pub struct InteractiveAuthInfo { 97pub struct InteractiveAuthInfo {
67 pub user: String, 98 pub user: String,
68 pub password: String, 99 pub password: String,
@@ -212,12 +243,32 @@ impl Connection {
212 transaction_id: Option<OwnedTransactionId>, 243 transaction_id: Option<OwnedTransactionId>,
213 ) -> MatrixResult<RoomSendResponse> { 244 ) -> MatrixResult<RoomSendResponse> {
214 self.spawn(async move { 245 self.spawn(async move {
215 let mut msg = room.send(content); 246 let mut attempt = 0;
216 if let Some(txn_id) = transaction_id.as_deref() { 247
217 msg = msg.with_transaction_id(txn_id.to_owned()); 248 loop {
218 } 249 let mut msg = room.send(content.clone());
250 if let Some(txn_id) = transaction_id.as_deref() {
251 msg = msg.with_transaction_id(txn_id.to_owned());
252 }
219 253
220 msg.await 254 match msg.await {
255 Ok(response) => return Ok(response),
256 Err(error)
257 if is_retryable_network_error(&error)
258 && send_retry_delay(attempt).is_some() =>
259 {
260 let delay = send_retry_delay(attempt)
261 .expect("delay checked above");
262 attempt += 1;
263 error!(
264 "Matrix message send failed due to a network error, retrying in {}s: {error}",
265 delay.as_secs()
266 );
267 tokio::time::sleep(delay).await;
268 }
269 Err(error) => return Err(error),
270 }
271 }
221 }) 272 })
222 .await 273 .await
223 } 274 }
@@ -694,10 +745,32 @@ impl Connection {
694 } 745 }
695 }); 746 });
696 747
697 let filter = client 748 let mut filter_failures = 0;
698 .get_or_upload_filter("sync", Connection::sync_filter()) 749 let filter = loop {
699 .await 750 match client
700 .unwrap(); 751 .get_or_upload_filter("sync", Connection::sync_filter())
752 .await
753 {
754 Ok(filter) => break filter,
755 Err(error) if is_retryable_network_error(&error) => {
756 let delay = sync_retry_delay(filter_failures);
757 filter_failures = filter_failures.saturating_add(1);
758 error!(
759 "Matrix filter upload failed due to a network error, retrying in {}s: {error}",
760 delay.as_secs()
761 );
762 tokio::time::sleep(delay).await;
763 }
764 Err(error) => {
765 let _ = channel
766 .send(Err(format!(
767 "Failed to upload Matrix sync filter: {error}"
768 )))
769 .await;
770 return;
771 }
772 }
773 };
701 774
702 let sync_token: Option<String> = None; 775 let sync_token: Option<String> = None;
703 let sync_settings = SyncSettings::new() 776 let sync_settings = SyncSettings::new()
@@ -714,6 +787,7 @@ impl Connection {
714 787
715 let client_ref = &client; 788 let client_ref = &client;
716 789
790 let mut sync_failures = 0;
717 loop { 791 loop {
718 let ret = client 792 let ret = client
719 .sync_with_callback(sync_settings.clone(), |response| async move { 793 .sync_with_callback(sync_settings.clone(), |response| async move {
@@ -841,15 +915,63 @@ impl Connection {
841 }) 915 })
842 .await; 916 .await;
843 917
844 if let Err(err) = ret { 918 match ret {
845 error!("Matrix sync failed: {err}"); 919 Err(err) if channel.is_closed() => {
846 } else { 920 error!("Matrix sync failed during shutdown: {err}");
847 break; 921 break;
922 }
923 Err(err) => {
924 let delay = sync_retry_delay(sync_failures);
925 sync_failures = sync_failures.saturating_add(1);
926 error!(
927 "Matrix sync failed, retrying in {}s: {err}",
928 delay.as_secs()
929 );
930 tokio::time::sleep(delay).await;
931 }
932 Ok(())
933 if should_restart_completed_sync(channel.is_closed()) =>
934 {
935 let delay = sync_retry_delay(sync_failures);
936 sync_failures = sync_failures.saturating_add(1);
937 error!(
938 "Matrix sync stopped unexpectedly, restarting in {}s",
939 delay.as_secs()
940 );
941 tokio::time::sleep(delay).await;
942 }
943 Ok(()) => break,
848 } 944 }
849 } 945 }
850 } 946 }
851} 947}
852 948
949#[cfg(test)]
950mod tests {
951 use super::*;
952
953 #[test]
954 fn send_retries_are_bounded() {
955 assert_eq!(send_retry_delay(0), Some(Duration::from_secs(1)));
956 assert_eq!(send_retry_delay(3), Some(Duration::from_secs(10)));
957 assert_eq!(send_retry_delay(4), None);
958 }
959
960 #[test]
961 fn sync_retry_delay_is_capped() {
962 assert_eq!(sync_retry_delay(0), Duration::from_secs(1));
963 assert_eq!(sync_retry_delay(1), Duration::from_secs(2));
964 assert_eq!(sync_retry_delay(6), Duration::from_secs(60));
965 assert_eq!(sync_retry_delay(31), Duration::from_secs(60));
966 }
967
968 #[test]
969 fn completed_sync_restarts_unless_channel_is_closed() {
970 assert!(should_restart_completed_sync(false));
971 assert!(!should_restart_completed_sync(true));
972 }
973}
974
853impl Drop for Connection { 975impl Drop for Connection {
854 fn drop(&mut self) { 976 fn drop(&mut self) {
855 let Some(runtime) = self.runtime.as_ref().cloned() else { 977 let Some(runtime) = self.runtime.as_ref().cloned() else {