Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IMAP refactoring #4977

Merged
merged 4 commits into from
Nov 10, 2023
Merged
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
21 changes: 4 additions & 17 deletions src/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ use crate::mimeparser::SystemMessage;
use crate::param::{Param, Params};
use crate::peerstate::{Peerstate, PeerstateVerifiedStatus};
use crate::receive_imf::ReceivedMsg;
use crate::scheduler::InterruptInfo;
use crate::smtp::send_msg_to_smtp;
use crate::sql;
use crate::stock_str;
Expand Down Expand Up @@ -702,10 +701,7 @@ impl ChatId {
context.emit_msgs_changed_without_ids();

context.set_config(Config::LastHousekeeping, None).await?;
context
.scheduler
.interrupt_inbox(InterruptInfo::new(false))
.await;
context.scheduler.interrupt_inbox().await;

if chat.is_self_talk() {
let mut msg = Message::new(Viewtype::Text);
Expand Down Expand Up @@ -2503,10 +2499,7 @@ async fn send_msg_inner(context: &Context, chat_id: ChatId, msg: &mut Message) -
context.emit_event(EventType::LocationChanged(Some(ContactId::SELF)));
}

context
.scheduler
.interrupt_smtp(InterruptInfo::new(false))
.await;
context.scheduler.interrupt_smtp().await;
}

Ok(msg.id)
Expand Down Expand Up @@ -3736,10 +3729,7 @@ pub async fn forward_msgs(context: &Context, msg_ids: &[MsgId], chat_id: ChatId)
.await?;
curr_timestamp += 1;
if create_send_msg_job(context, &mut msg).await?.is_some() {
context
.scheduler
.interrupt_smtp(InterruptInfo::new(false))
.await;
context.scheduler.interrupt_smtp().await;
}
}
created_chats.push(chat_id);
Expand Down Expand Up @@ -3796,10 +3786,7 @@ pub async fn resend_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
msg_id: msg.id,
});
if create_send_msg_job(context, &mut msg).await?.is_some() {
context
.scheduler
.interrupt_smtp(InterruptInfo::new(false))
.await;
context.scheduler.interrupt_smtp().await;
}
}
Ok(())
Expand Down
5 changes: 1 addition & 4 deletions src/configure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ use crate::login_param::{CertificateChecks, LoginParam, ServerLoginParam};
use crate::message::{Message, Viewtype};
use crate::oauth2::get_oauth2_addr;
use crate::provider::{Protocol, Socket, UsernamePattern};
use crate::scheduler::InterruptInfo;
use crate::smtp::Smtp;
use crate::socks::Socks5Config;
use crate::stock_str;
Expand Down Expand Up @@ -481,9 +480,7 @@ async fn configure(ctx: &Context, param: &mut LoginParam) -> Result<()> {

ctx.set_config_bool(Config::FetchedExistingMsgs, false)
.await?;
ctx.scheduler
.interrupt_inbox(InterruptInfo::new(false))
.await;
ctx.scheduler.interrupt_inbox().await;

progress!(ctx, 940);
update_device_chats_handle.await??;
Expand Down
8 changes: 2 additions & 6 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::key::{load_self_public_key, DcKey as _};
use crate::login_param::LoginParam;
use crate::message::{self, MessageState, MsgId};
use crate::quota::QuotaInfo;
use crate::scheduler::{InterruptInfo, SchedulerState};
use crate::scheduler::SchedulerState;
use crate::sql::Sql;
use crate::stock_str::StockStrings;
use crate::timesmearing::SmearedTimestamp;
Expand Down Expand Up @@ -437,11 +437,7 @@ impl Context {

pub(crate) async fn schedule_resync(&self) -> Result<()> {
self.resync_request.store(true, Ordering::Relaxed);
self.scheduler
.interrupt_inbox(InterruptInfo {
probe_network: false,
})
.await;
self.scheduler.interrupt_inbox().await;
Ok(())
}

Expand Down
6 changes: 1 addition & 5 deletions src/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use crate::context::Context;
use crate::imap::{Imap, ImapActionResult};
use crate::message::{Message, MsgId, Viewtype};
use crate::mimeparser::{MimeMessage, Part};
use crate::scheduler::InterruptInfo;
use crate::tools::time;
use crate::{stock_str, EventType};

Expand Down Expand Up @@ -93,10 +92,7 @@ impl MsgId {
.sql
.execute("INSERT INTO download (msg_id) VALUES (?)", (self,))
.await?;
context
.scheduler
.interrupt_inbox(InterruptInfo::new(false))
.await;
context.scheduler.interrupt_inbox().await;
}
}
Ok(())
Expand Down
12 changes: 4 additions & 8 deletions src/imap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ use crate::receive_imf::{
from_field_to_contact_id, get_prefetch_parent_message, receive_imf_inner, ReceivedMsg,
};
use crate::scheduler::connectivity::ConnectivityStore;
use crate::scheduler::InterruptInfo;
use crate::socks::Socks5Config;
use crate::sql;
use crate::stock_str;
Expand Down Expand Up @@ -86,7 +85,7 @@ const BODY_PARTIAL: &str = "(FLAGS RFC822.SIZE BODY.PEEK[HEADER])";

#[derive(Debug)]
pub struct Imap {
pub(crate) idle_interrupt_receiver: Receiver<InterruptInfo>,
pub(crate) idle_interrupt_receiver: Receiver<()>,
config: ImapConfig,
pub(crate) session: Option<Session>,
login_failed_once: bool,
Expand Down Expand Up @@ -228,7 +227,7 @@ impl Imap {
socks5_config: Option<Socks5Config>,
addr: &str,
provider_strict_tls: bool,
idle_interrupt_receiver: Receiver<InterruptInfo>,
idle_interrupt_receiver: Receiver<()>,
) -> Result<Self> {
if lp.server.is_empty() || lp.user.is_empty() || lp.password.is_empty() {
bail!("Incomplete IMAP connection parameters");
Expand Down Expand Up @@ -261,7 +260,7 @@ impl Imap {
/// Creates new disconnected IMAP client using configured parameters.
pub async fn new_configured(
context: &Context,
idle_interrupt_receiver: Receiver<InterruptInfo>,
idle_interrupt_receiver: Receiver<()>,
) -> Result<Self> {
if !context.is_configured().await? {
bail!("IMAP Connect without configured params");
Expand Down Expand Up @@ -2290,10 +2289,7 @@ pub(crate) async fn markseen_on_imap_table(context: &Context, message_id: &str)
(message_id,),
)
.await?;
context
.scheduler
.interrupt_inbox(InterruptInfo::new(false))
.await;
context.scheduler.interrupt_inbox().await;

Ok(())
}
Expand Down
67 changes: 25 additions & 42 deletions src/imap/idle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,25 @@ use futures_lite::FutureExt;
use super::session::Session;
use super::Imap;
use crate::config::Config;
use crate::context::Context;
use crate::imap::{client::IMAP_TIMEOUT, get_uid_next, FolderMeaning};
use crate::log::LogExt;
use crate::{context::Context, scheduler::InterruptInfo};

const IDLE_TIMEOUT: Duration = Duration::from_secs(23 * 60);

impl Session {
pub async fn idle(
mut self,
context: &Context,
idle_interrupt_receiver: Receiver<InterruptInfo>,
idle_interrupt_receiver: Receiver<()>,
folder: &str,
) -> Result<(Self, InterruptInfo)> {
) -> Result<Self> {
use futures::future::FutureExt;

if context.get_config_bool(Config::DisableIdle).await? {
bail!("IMAP IDLE is disabled");
}

if !self.can_idle() {
bail!("IMAP server does not have IDLE capability");
}

let mut info = Default::default();

self.select_folder(context, Some(folder)).await?;

if self.server_sent_unsolicited_exists(context)? {
return Ok((self, info));
return Ok(self);
}

// Despite checking for unsolicited EXISTS above,
Expand All @@ -55,16 +45,16 @@ impl Session {
context,
"Skipping IDLE on {folder:?} because UIDNEXT {uid_next}>{expected_uid_next} indicates there are new messages."
);
return Ok((self, info));
return Ok(self);
}
} else {
warn!(context, "STATUS {folder} (UIDNEXT) did not return UIDNEXT");
// Go to IDLE anyway if STATUS is broken.
}

if let Ok(info) = idle_interrupt_receiver.try_recv() {
info!(context, "skip idle, got interrupt {:?}", info);
return Ok((self, info));
if let Ok(()) = idle_interrupt_receiver.try_recv() {
info!(context, "skip idle, got interrupt");
return Ok(self);
}

let mut handle = self.inner.idle();
Expand All @@ -81,17 +71,17 @@ impl Session {

enum Event {
IdleResponse(IdleResponse),
Interrupt(InterruptInfo),
Interrupt,
}

info!(context, "{folder}: Idle entering wait-on-remote state");
let fut = idle_wait.map(|ev| ev.map(Event::IdleResponse)).race(async {
let info = idle_interrupt_receiver.recv().await;
idle_interrupt_receiver.recv().await.ok();

// cancel imap idle connection properly
drop(interrupt);

Ok(Event::Interrupt(info.unwrap_or_default()))
Ok(Event::Interrupt)
});

match fut.await {
Expand All @@ -104,9 +94,8 @@ impl Session {
Ok(Event::IdleResponse(IdleResponse::ManualInterrupt)) => {
info!(context, "{folder}: Idle wait was interrupted manually");
}
Ok(Event::Interrupt(i)) => {
info!(context, "{folder}: Idle wait was interrupted: {:?}", &i);
info = i;
Ok(Event::Interrupt) => {
info!(context, "{folder}: Idle wait was interrupted");
}
Err(err) => {
warn!(context, "{folder}: Idle wait errored: {err:?}");
Expand All @@ -120,7 +109,7 @@ impl Session {
session.as_mut().set_read_timeout(Some(IMAP_TIMEOUT));
self.inner = session;

Ok((self, info))
Ok(self)
}
}

Expand All @@ -130,7 +119,7 @@ impl Imap {
context: &Context,
watch_folder: Option<String>,
folder_meaning: FolderMeaning,
) -> InterruptInfo {
) {
// Idle using polling. This is also needed if we're not yet configured -
// in this case, we're waiting for a configure job (and an interrupt).

Expand All @@ -141,11 +130,8 @@ impl Imap {
watch_folder
} else {
info!(context, "IMAP-fake-IDLE: no folder, waiting for interrupt");
return self
.idle_interrupt_receiver
.recv()
.await
.unwrap_or_default();
self.idle_interrupt_receiver.recv().await.ok();
return;
};
info!(context, "IMAP-fake-IDLEing folder={:?}", watch_folder);

Expand All @@ -155,18 +141,18 @@ impl Imap {

enum Event {
Tick,
Interrupt(InterruptInfo),
Interrupt,
}
// loop until we are interrupted or if we fetched something
let info = loop {
loop {
use futures::future::FutureExt;
match interval
.tick()
.map(|_| Event::Tick)
.race(
self.idle_interrupt_receiver
.recv()
.map(|probe_network| Event::Interrupt(probe_network.unwrap_or_default())),
.map(|_| Event::Interrupt),
)
.await
{
Expand All @@ -188,7 +174,7 @@ impl Imap {
.unwrap_or_default()
{
// we only fake-idled because network was gone during IDLE, probably
break InterruptInfo::new(false);
break;
}
}
info!(context, "fake_idle is connected");
Expand All @@ -203,7 +189,7 @@ impl Imap {
Ok(res) => {
info!(context, "fetch_new_messages returned {:?}", res);
if res {
break InterruptInfo::new(false);
break;
}
}
Err(err) => {
Expand All @@ -212,13 +198,12 @@ impl Imap {
}
}
}
Event::Interrupt(info) => {
// Interrupt
Event::Interrupt => {
info!(context, "Fake IDLE interrupted");
break info;
break;
}
}
};
}

info!(
context,
Expand All @@ -229,7 +214,5 @@ impl Imap {
.as_millis() as f64
/ 1000.,
);

info
}
}
8 changes: 4 additions & 4 deletions src/imap/scan_folders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use crate::log::LogExt;
use crate::{context::Context, imap::FolderMeaning};

impl Imap {
/// Returns true if folders were scanned, false if scanning was postponed.
pub(crate) async fn scan_folders(&mut self, context: &Context) -> Result<bool> {
/// Scans not watched IMAP folders for new messages.
pub(crate) async fn scan_folders(&mut self, context: &Context) -> Result<()> {
// First of all, debounce to once per minute:
let mut last_scan = context.last_full_folder_scan.lock().await;
if let Some(last_scan) = *last_scan {
Expand All @@ -21,7 +21,7 @@ impl Imap {
.await?;

if elapsed_secs < debounce_secs {
return Ok(false);
return Ok(());
}
}
info!(context, "Starting full folder scan");
Expand Down Expand Up @@ -94,7 +94,7 @@ impl Imap {
}

last_scan.replace(Instant::now());
Ok(true)
Ok(())
}

/// Returns the names of all folders on the IMAP server.
Expand Down
Loading
Loading