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"
3939url = "2.3.1"
4040serde_json = "1.0.85"
4141strum = { 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"] }
4343tracing = "0.1.36"
4444tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
4545uuid = { version = "1.1.2", features = ["v4"] }
src/connection.rs +137 −15
@@ -49,8 +49,8 @@ use matrix_sdk::{
4949 store::RoomLoadSettings,
5050 sync::State,
5151 utils::local_server::LocalServerBuilder,
52 Client, LoopCtrl, Result as MatrixResult, RoomMemberships, SessionChange,
53 SessionMeta, SessionTokens,
52 Client, HttpError, LoopCtrl, Result as MatrixResult, RoomMemberships,
53 SessionChange, SessionMeta, SessionTokens,
5454};
5555
5656use weechat::{Task, Weechat};
@@ -61,8 +61,39 @@ use crate::{
6161};
6262
6363const 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);
6472const SSO_CALLBACK_PORT: u16 = 29_325;
6573
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
6697pub struct InteractiveAuthInfo {
6798 pub user: String,
6899 pub password: String,
@@ -212,12 +243,32 @@ impl Connection {
212243 transaction_id: Option<OwnedTransactionId>,
213244 ) -> MatrixResult<RoomSendResponse> {
214245 self.spawn(async move {
215 let mut msg = room.send(content);
216 if let Some(txn_id) = transaction_id.as_deref() {
217 msg = msg.with_transaction_id(txn_id.to_owned());
218 }
246 let mut attempt = 0;
247
248 loop {
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 }
219253
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 }
221272 })
222273 .await
223274 }
@@ -694,10 +745,32 @@ impl Connection {
694745 }
695746 });
696747
697 let filter = client
698 .get_or_upload_filter("sync", Connection::sync_filter())
699 .await
700 .unwrap();
748 let mut filter_failures = 0;
749 let filter = loop {
750 match client
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 };
701774
702775 let sync_token: Option<String> = None;
703776 let sync_settings = SyncSettings::new()
@@ -714,6 +787,7 @@ impl Connection {
714787
715788 let client_ref = &client;
716789
790 let mut sync_failures = 0;
717791 loop {
718792 let ret = client
719793 .sync_with_callback(sync_settings.clone(), |response| async move {
@@ -841,15 +915,63 @@ impl Connection {
841915 })
842916 .await;
843917
844 if let Err(err) = ret {
845 error!("Matrix sync failed: {err}");
846 } else {
847 break;
918 match ret {
919 Err(err) if channel.is_closed() => {
920 error!("Matrix sync failed during shutdown: {err}");
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,
848944 }
849945 }
850946 }
851947}
852948
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
853975impl Drop for Connection {
854976 fn drop(&mut self) {
855977 let Some(runtime) = self.runtime.as_ref().cloned() else {