diff --git a/deltachat-rpc-client/tests/test_multitransport.py b/deltachat-rpc-client/tests/test_multitransport.py index 2c2497f441..b62904fd3f 100644 --- a/deltachat-rpc-client/tests/test_multitransport.py +++ b/deltachat-rpc-client/tests/test_multitransport.py @@ -1,4 +1,5 @@ import os +import re import time import urllib.parse @@ -382,6 +383,52 @@ def test_background_fetch_no_duplicates(acf, direct_imap, dc): assert len(messages_with_text(alice_chat, "hello")) == 1 +def test_post_msg_downloaded_once(acf, direct_imap, tmp_path): + """A post-message that is available on multiple relays + must be downloaded only once.""" + # Min. UI setting as of v2.35 + download_limit = 163840 + alice, _alice_chat, bob_chat = alice_with_two_transports_and_bob(acf) + alice.set_config("download_limit", str(download_limit)) + imaps = [direct_imap(alice, transport["addr"], transport["password"]) for transport in alice.list_transports()] + assert len(imaps) == 2 + + alice.stop_io() + path = tmp_path / "large" + path.write_bytes(os.urandom(download_limit + 1)) + bob_chat.send_file(str(path)) + + # Wait for the pre- and post-message on both relays + for imap in imaps: + while len(imap.get_all_messages()) < 2: + time.sleep(0.1) + + alice.start_io() + msg = alice.wait_for_incoming_msg() + assert msg.get_snapshot().download_state == DownloadState.AVAILABLE + alice._rpc.download_full_message(alice.id, msg.id) + + # Wait until both transports are idle, + # then check that the message was downloaded only from one transport: + + idle_transports = set() + downloaded = False + downloads = 0 + + while len(idle_transports) < 2: + event = alice.wait_for_event() + + if event.kind == EventType.MSGS_CHANGED and event.msg_id == msg.id: + downloaded = msg.get_snapshot().download_state == DownloadState.DONE + elif event.kind == EventType.INFO: + if re.search(r"Downloading message \S+ fully", event.msg): + downloads += 1 + elif downloaded and (m := re.search(r"Transport (\d+): IDLE entering wait-on-remote state", event.msg)): + idle_transports.add(m[1]) + + assert downloads == 1 + + def test_multitransport_mdn(acf): """Test sending an MDN right after configuring two transports.""" alice, bob = acf.get_online_accounts(2) diff --git a/src/download.rs b/src/download.rs index e154fbaaa9..5a07b9758c 100644 --- a/src/download.rs +++ b/src/download.rs @@ -5,6 +5,7 @@ use std::collections::BTreeMap; use anyhow::{Result, anyhow, bail, ensure}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; +use tokio::sync::MutexGuard; use crate::context::Context; use crate::imap::session::Session; @@ -136,6 +137,7 @@ pub(crate) async fn download_msg( context: &Context, rfc724_mid: String, session: &mut Session, + _fetch_msgs_lock_guard: &MutexGuard<'_, ()>, ) -> Result> { let transport_id = session.transport_id(); let row = context @@ -160,7 +162,13 @@ pub(crate) async fn download_msg( return Ok(None); }; session - .fetch_single_msg(context, &server_folder, server_uid, rfc724_mid) + .fetch_single_msg( + context, + &server_folder, + server_uid, + rfc724_mid, + _fetch_msgs_lock_guard, + ) .await?; if ephemeral::should_delete_all_downloaded_messages(context).await? { @@ -185,6 +193,7 @@ impl Session { folder: &str, uid: u32, rfc724_mid: String, + _fetch_msgs_lock_guard: &MutexGuard<'_, ()>, ) -> Result<()> { if uid == 0 { bail!("Attempt to fetch UID 0"); @@ -199,11 +208,15 @@ impl Session { let mut uid_message_ids: BTreeMap = BTreeMap::new(); uid_message_ids.insert(uid, rfc724_mid); let (sender, receiver) = async_channel::unbounded(); - { - let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; - Box::pin(self.fetch_many_msgs(context, folder, vec![uid], &uid_message_ids, sender)) - .await?; - } + Box::pin(self.fetch_many_msgs( + context, + folder, + vec![uid], + &uid_message_ids, + sender, + _fetch_msgs_lock_guard, + )) + .await?; if receiver.recv().await.is_err() { bail!("Failed to fetch UID {uid}"); } @@ -275,7 +288,28 @@ pub(crate) async fn download_msgs(context: &Context, session: &mut Session) -> R .await?; for rfc724_mid in &rfc724_mids { - match download_msg(context, rfc724_mid.clone(), session).await { + let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; + + if !context + .sql + .exists( + "SELECT COUNT(*) FROM download WHERE rfc724_mid=?", + (rfc724_mid,), + ) + .await? + { + // Another transport has downloaded the message in the meantime + continue; + } + + match download_msg( + context, + rfc724_mid.clone(), + session, + &_fetch_msgs_lock_guard, + ) + .await + { Ok(Some(())) => { delete_from_downloads(context, rfc724_mid).await?; delete_from_available_post_msgs(context, rfc724_mid).await?; @@ -329,6 +363,11 @@ pub(crate) async fn download_known_post_messages_without_pre_message( }) .await?; for rfc724_mid in &rfc724_mids { + let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; + if !available_post_msgs_contains_rfc724_mid(context, rfc724_mid).await? { + // Another transport has downloaded the message in the meantime + continue; + } if msg_is_downloaded_for(context, rfc724_mid).await? { delete_from_available_post_msgs(context, rfc724_mid).await?; continue; @@ -338,7 +377,13 @@ pub(crate) async fn download_known_post_messages_without_pre_message( // because the Pre-Message got lost. // The message may be in the wrong order, // but at least we have it at all. - let res = download_msg(context, rfc724_mid.clone(), session).await; + let res = download_msg( + context, + rfc724_mid.clone(), + session, + &_fetch_msgs_lock_guard, + ) + .await; if let Ok(Some(())) = res { delete_from_available_post_msgs(context, rfc724_mid).await?; } diff --git a/src/imap.rs b/src/imap.rs index 6669ffbfbf..8f46dcd707 100644 --- a/src/imap.rs +++ b/src/imap.rs @@ -18,6 +18,7 @@ use async_channel::{self, Receiver, Sender}; use async_imap::types::{Fetch, Flag, UnsolicitedResponse}; use futures::TryStreamExt as _; use ratelimit::Ratelimit; +use tokio::sync::MutexGuard; use tokio_util::sync::CancellationToken; use url::Url; @@ -706,7 +707,14 @@ impl Imap { let actually_download_messages_future = async { session - .fetch_many_msgs(context, folder, uids_fetch, &uid_message_ids, sender) + .fetch_many_msgs( + context, + folder, + uids_fetch, + &uid_message_ids, + sender, + &_fetch_msgs_lock_guard, + ) .await .context("fetch_many_msgs") }; @@ -1016,6 +1024,7 @@ impl Session { request_uids: Vec, uid_message_ids: &BTreeMap, received_msgs_channel: Sender<(u32, Option)>, + _fetch_msgs_lock_guard: &MutexGuard<'_, ()>, ) -> Result<()> { if request_uids.is_empty() { return Ok(());