Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions deltachat-rpc-client/tests/test_multitransport.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import re
import time
import urllib.parse

Expand Down Expand Up @@ -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)
Expand Down
61 changes: 53 additions & 8 deletions src/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -136,6 +137,7 @@ pub(crate) async fn download_msg(
context: &Context,
rfc724_mid: String,
session: &mut Session,
_fetch_msgs_lock_guard: &MutexGuard<'_, ()>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vertical line minimization police here: if you gave a shorter name ruff format might produce less lines, which i much prefer for readability.

@Hocuri Hocuri Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally, I even like that these function calls get more vertical weight, because the function calls that need _fetch_msgs_lock_guard are usually the most important function calls. But it's not important, we can also rename it, maybe to _fetch_guard?

) -> Result<Option<()>> {
let transport_id = session.transport_id();
let row = context
Expand All @@ -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? {
Expand All @@ -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");
Expand All @@ -199,11 +208,15 @@ impl Session {
let mut uid_message_ids: BTreeMap<u32, String> = 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}");
}
Expand Down Expand Up @@ -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?;
Expand Down Expand Up @@ -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;
Expand All @@ -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?;
}
Expand Down
11 changes: 10 additions & 1 deletion src/imap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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")
};
Expand Down Expand Up @@ -1016,6 +1024,7 @@ impl Session {
request_uids: Vec<u32>,
uid_message_ids: &BTreeMap<u32, String>,
received_msgs_channel: Sender<(u32, Option<ReceivedMsg>)>,
_fetch_msgs_lock_guard: &MutexGuard<'_, ()>,
) -> Result<()> {
if request_uids.is_empty() {
return Ok(());
Expand Down
Loading