deltachat/
scheduler.rs

1use std::cmp;
2use std::num::NonZeroUsize;
3
4use anyhow::{Context as _, Error, Result, bail};
5use async_channel::{self as channel, Receiver, Sender};
6use futures::future::try_join_all;
7use futures_lite::FutureExt;
8use tokio::sync::{RwLock, oneshot};
9use tokio::task;
10use tokio_util::sync::CancellationToken;
11use tokio_util::task::TaskTracker;
12
13pub(crate) use self::connectivity::ConnectivityStore;
14use crate::config::Config;
15use crate::contact::{ContactId, RecentlySeenLoop};
16use crate::context::Context;
17use crate::download::{download_known_post_messages_without_pre_message, download_msgs};
18use crate::ephemeral::{self, delete_expired_imap_messages};
19use crate::events::EventType;
20use crate::imap::{FolderMeaning, Imap, session::Session};
21use crate::location;
22use crate::log::{LogExt, warn};
23use crate::smtp::{Smtp, send_smtp_messages};
24use crate::sql;
25use crate::stats::maybe_send_stats;
26use crate::tools::{self, duration_to_str, maybe_add_time_based_warnings, time, time_elapsed};
27use crate::transport::ConfiguredLoginParam;
28use crate::{constants, stats};
29
30pub(crate) mod connectivity;
31
32/// State of the IO scheduler, as stored on the [`Context`].
33///
34/// The IO scheduler can be stopped or started, but core can also pause it.  After pausing
35/// the IO scheduler will be restarted only if it was running before paused or
36/// [`Context::start_io`] was called in the meantime while it was paused.
37#[derive(Debug, Default)]
38pub(crate) struct SchedulerState {
39    inner: RwLock<InnerSchedulerState>,
40}
41
42impl SchedulerState {
43    pub(crate) fn new() -> Self {
44        Default::default()
45    }
46
47    /// Whether the scheduler is currently running.
48    pub(crate) async fn is_running(&self) -> bool {
49        let inner = self.inner.read().await;
50        matches!(*inner, InnerSchedulerState::Started(_))
51    }
52
53    /// Starts the scheduler if it is not yet started.
54    pub(crate) async fn start(&self, context: &Context) {
55        let mut inner = self.inner.write().await;
56        match *inner {
57            InnerSchedulerState::Started(_) => (),
58            InnerSchedulerState::Stopped => Self::do_start(&mut inner, context).await,
59            InnerSchedulerState::Paused {
60                ref mut started, ..
61            } => *started = true,
62        }
63        context.update_connectivities(&inner);
64    }
65
66    /// Starts the scheduler if it is not yet started.
67    async fn do_start(inner: &mut InnerSchedulerState, context: &Context) {
68        info!(context, "starting IO");
69
70        // Notify message processing loop
71        // to allow processing old messages after restart.
72        context.new_msgs_notify.notify_one();
73
74        match Scheduler::start(context).await {
75            Ok(scheduler) => {
76                *inner = InnerSchedulerState::Started(scheduler);
77                context.emit_event(EventType::ConnectivityChanged);
78            }
79            Err(err) => error!(context, "Failed to start IO: {:#}", err),
80        }
81    }
82
83    /// Stops the scheduler if it is currently running.
84    pub(crate) async fn stop(&self, context: &Context) {
85        let mut inner = self.inner.write().await;
86        match *inner {
87            InnerSchedulerState::Started(_) => {
88                Self::do_stop(&mut inner, context, InnerSchedulerState::Stopped).await
89            }
90            InnerSchedulerState::Stopped => (),
91            InnerSchedulerState::Paused {
92                ref mut started, ..
93            } => *started = false,
94        }
95        context.update_connectivities(&inner);
96    }
97
98    /// Stops the scheduler if it is currently running.
99    async fn do_stop(
100        inner: &mut InnerSchedulerState,
101        context: &Context,
102        new_state: InnerSchedulerState,
103    ) {
104        // Sending an event wakes up event pollers (get_next_event)
105        // so the caller of stop_io() can arrange for proper termination.
106        // For this, the caller needs to instruct the event poller
107        // to terminate on receiving the next event and then call stop_io()
108        // which will emit the below event(s)
109        info!(context, "stopping IO");
110
111        // Wake up message processing loop even if there are no messages
112        // to allow for clean shutdown.
113        context.new_msgs_notify.notify_one();
114
115        let debug_logging = context
116            .debug_logging
117            .write()
118            .expect("RwLock is poisoned")
119            .take();
120        if let Some(debug_logging) = debug_logging {
121            debug_logging.loop_handle.abort();
122            debug_logging.loop_handle.await.ok();
123        }
124        let prev_state = std::mem::replace(inner, new_state);
125        context.emit_event(EventType::ConnectivityChanged);
126        match prev_state {
127            InnerSchedulerState::Started(scheduler) => scheduler.stop(context).await,
128            InnerSchedulerState::Stopped | InnerSchedulerState::Paused { .. } => (),
129        }
130    }
131
132    /// Pauses the IO scheduler.
133    ///
134    /// If it is currently running the scheduler will be stopped.  When the
135    /// [`IoPausedGuard`] is dropped the scheduler is started again.
136    ///
137    /// If in the meantime [`SchedulerState::start`] or [`SchedulerState::stop`] is called
138    /// resume will do the right thing and restore the scheduler to the state requested by
139    /// the last call.
140    pub(crate) async fn pause(&'_ self, context: &Context) -> Result<IoPausedGuard> {
141        {
142            let mut inner = self.inner.write().await;
143            match *inner {
144                InnerSchedulerState::Started(_) => {
145                    let new_state = InnerSchedulerState::Paused {
146                        started: true,
147                        pause_guards_count: NonZeroUsize::MIN,
148                    };
149                    Self::do_stop(&mut inner, context, new_state).await;
150                }
151                InnerSchedulerState::Stopped => {
152                    *inner = InnerSchedulerState::Paused {
153                        started: false,
154                        pause_guards_count: NonZeroUsize::MIN,
155                    };
156                }
157                InnerSchedulerState::Paused {
158                    ref mut pause_guards_count,
159                    ..
160                } => {
161                    *pause_guards_count = pause_guards_count
162                        .checked_add(1)
163                        .ok_or_else(|| Error::msg("Too many pause guards active"))?
164                }
165            }
166            context.update_connectivities(&inner);
167        }
168
169        let (tx, rx) = oneshot::channel();
170        let context = context.clone();
171        tokio::spawn(async move {
172            rx.await.ok();
173            let mut inner = context.scheduler.inner.write().await;
174            match *inner {
175                InnerSchedulerState::Started(_) => {
176                    warn!(&context, "IoPausedGuard resume: started instead of paused");
177                }
178                InnerSchedulerState::Stopped => {
179                    warn!(&context, "IoPausedGuard resume: stopped instead of paused");
180                }
181                InnerSchedulerState::Paused {
182                    ref started,
183                    ref mut pause_guards_count,
184                } => {
185                    if *pause_guards_count == NonZeroUsize::MIN {
186                        match *started {
187                            true => SchedulerState::do_start(&mut inner, &context).await,
188                            false => *inner = InnerSchedulerState::Stopped,
189                        }
190                    } else {
191                        let new_count = pause_guards_count.get() - 1;
192                        // SAFETY: Value was >=2 before due to if condition
193                        *pause_guards_count = NonZeroUsize::new(new_count).unwrap();
194                    }
195                }
196            }
197            context.update_connectivities(&inner);
198        });
199        Ok(IoPausedGuard { sender: Some(tx) })
200    }
201
202    /// Restarts the scheduler, only if it is running.
203    pub(crate) async fn restart(&self, context: &Context) {
204        info!(context, "restarting IO");
205        if self.is_running().await {
206            self.stop(context).await;
207            self.start(context).await;
208        }
209    }
210
211    /// Indicate that the network likely has come back.
212    pub(crate) async fn maybe_network(&self) {
213        let inner = self.inner.read().await;
214        let (inboxes, oboxes) = match *inner {
215            InnerSchedulerState::Started(ref scheduler) => {
216                scheduler.maybe_network();
217                let inboxes = scheduler
218                    .inboxes
219                    .iter()
220                    .map(|b| b.conn_state.state.connectivity.clone())
221                    .collect::<Vec<_>>();
222                let oboxes = scheduler
223                    .oboxes
224                    .iter()
225                    .map(|b| b.conn_state.state.connectivity.clone())
226                    .collect::<Vec<_>>();
227                (inboxes, oboxes)
228            }
229            _ => return,
230        };
231        drop(inner);
232        connectivity::idle_interrupted(inboxes, oboxes);
233    }
234
235    /// Indicate that the network likely is lost.
236    pub(crate) async fn maybe_network_lost(&self, context: &Context) {
237        let inner = self.inner.read().await;
238        let stores = match *inner {
239            InnerSchedulerState::Started(ref scheduler) => {
240                scheduler.maybe_network_lost();
241                scheduler
242                    .boxes()
243                    .map(|b| b.conn_state.state.connectivity.clone())
244                    .collect()
245            }
246            _ => return,
247        };
248        drop(inner);
249        connectivity::maybe_network_lost(context, stores);
250    }
251
252    pub(crate) async fn interrupt_inbox(&self) {
253        let inner = self.inner.read().await;
254        if let InnerSchedulerState::Started(ref scheduler) = *inner {
255            scheduler.interrupt_inbox();
256        }
257    }
258
259    pub(crate) async fn interrupt_smtp(&self) {
260        let inner = self.inner.read().await;
261        if let InnerSchedulerState::Started(ref scheduler) = *inner {
262            scheduler.interrupt_smtp();
263        }
264    }
265
266    pub(crate) async fn interrupt_ephemeral_task(&self) {
267        let inner = self.inner.read().await;
268        if let InnerSchedulerState::Started(ref scheduler) = *inner {
269            scheduler.interrupt_ephemeral_task();
270        }
271    }
272
273    pub(crate) async fn interrupt_location(&self) {
274        let inner = self.inner.read().await;
275        if let InnerSchedulerState::Started(ref scheduler) = *inner {
276            scheduler.interrupt_location();
277        }
278    }
279
280    pub(crate) async fn interrupt_recently_seen(&self, contact_id: ContactId, timestamp: i64) {
281        let inner = self.inner.read().await;
282        if let InnerSchedulerState::Started(ref scheduler) = *inner {
283            scheduler.interrupt_recently_seen(contact_id, timestamp);
284        }
285    }
286}
287
288#[derive(Debug, Default)]
289pub(crate) enum InnerSchedulerState {
290    Started(Scheduler),
291    #[default]
292    Stopped,
293    Paused {
294        started: bool,
295        pause_guards_count: NonZeroUsize,
296    },
297}
298
299/// Guard to make sure the IO Scheduler is resumed.
300///
301/// Returned by [`SchedulerState::pause`].  To resume the IO scheduler simply drop this
302/// guard.
303#[derive(Default, Debug)]
304pub(crate) struct IoPausedGuard {
305    sender: Option<oneshot::Sender<()>>,
306}
307
308impl Drop for IoPausedGuard {
309    fn drop(&mut self) {
310        if let Some(sender) = self.sender.take() {
311            // Can only fail if receiver is dropped, but then we're already resumed.
312            sender.send(()).ok();
313        }
314    }
315}
316
317#[derive(Debug)]
318struct SchedBox {
319    /// Address at the used chatmail/email relay
320    addr: String,
321    meaning: FolderMeaning,
322    conn_state: ImapConnectionState,
323
324    /// IMAP loop task handle.
325    handle: task::JoinHandle<()>,
326}
327
328/// Job and connection scheduler.
329#[derive(Debug)]
330pub(crate) struct Scheduler {
331    /// Inboxes, one per transport.
332    inboxes: Vec<SchedBox>,
333    /// Optional boxes -- mvbox.
334    oboxes: Vec<SchedBox>,
335    smtp: SmtpConnectionState,
336    smtp_handle: task::JoinHandle<()>,
337    ephemeral_handle: task::JoinHandle<()>,
338    ephemeral_interrupt_send: Sender<()>,
339    location_handle: task::JoinHandle<()>,
340    location_interrupt_send: Sender<()>,
341
342    recently_seen_loop: RecentlySeenLoop,
343}
344
345async fn inbox_loop(
346    ctx: Context,
347    started: oneshot::Sender<()>,
348    inbox_handlers: ImapConnectionHandlers,
349) {
350    use futures::future::FutureExt;
351
352    info!(ctx, "Starting inbox loop.");
353    let ImapConnectionHandlers {
354        mut connection,
355        stop_token,
356    } = inbox_handlers;
357
358    let transport_id = connection.transport_id();
359    let ctx1 = ctx.clone();
360    let fut = async move {
361        let ctx = ctx1;
362        if let Err(()) = started.send(()) {
363            warn!(ctx, "Inbox loop, missing started receiver.");
364            return;
365        };
366
367        let mut old_session: Option<Session> = None;
368        loop {
369            let session = if let Some(session) = old_session.take() {
370                session
371            } else {
372                info!(
373                    ctx,
374                    "Transport {transport_id}: Preparing new IMAP session for inbox."
375                );
376                match connection.prepare(&ctx).await {
377                    Err(err) => {
378                        warn!(
379                            ctx,
380                            "Transport {transport_id}: Failed to prepare inbox connection: {err:#}."
381                        );
382                        continue;
383                    }
384                    Ok(session) => {
385                        info!(
386                            ctx,
387                            "Transport {transport_id}: Prepared new IMAP session for inbox."
388                        );
389                        session
390                    }
391                }
392            };
393
394            match inbox_fetch_idle(&ctx, &mut connection, session).await {
395                Err(err) => warn!(
396                    ctx,
397                    "Transport {transport_id}: Failed inbox fetch_idle: {err:#}."
398                ),
399                Ok(session) => {
400                    old_session = Some(session);
401                }
402            }
403        }
404    };
405
406    stop_token
407        .cancelled()
408        .map(|_| {
409            info!(ctx, "Transport {transport_id}: Shutting down inbox loop.");
410        })
411        .race(fut)
412        .await;
413}
414
415/// Convert folder meaning
416/// used internally by [fetch_idle] and [Context::background_fetch].
417///
418/// Returns folder configuration key and folder name
419/// if such folder is configured, `Ok(None)` otherwise.
420pub async fn convert_folder_meaning(
421    ctx: &Context,
422    folder_meaning: FolderMeaning,
423) -> Result<Option<(Config, String)>> {
424    let folder_config = match folder_meaning.to_config() {
425        Some(c) => c,
426        None => {
427            // Such folder cannot be configured,
428            // e.g. a `FolderMeaning::Spam` folder.
429            return Ok(None);
430        }
431    };
432
433    let folder = ctx
434        .get_config(folder_config)
435        .await
436        .with_context(|| format!("Failed to retrieve {folder_config} folder"))?;
437
438    if let Some(watch_folder) = folder {
439        Ok(Some((folder_config, watch_folder)))
440    } else {
441        Ok(None)
442    }
443}
444
445async fn inbox_fetch_idle(ctx: &Context, imap: &mut Imap, mut session: Session) -> Result<Session> {
446    let transport_id = session.transport_id();
447
448    // Update quota no more than once a minute.
449    if ctx.quota_needs_update(session.transport_id(), 60).await
450        && let Err(err) = ctx.update_recent_quota(&mut session).await
451    {
452        warn!(
453            ctx,
454            "Transport {transport_id}: Failed to update quota: {err:#}."
455        );
456    }
457
458    if let Ok(()) = imap.resync_request_receiver.try_recv()
459        && let Err(err) = session.resync_folders(ctx).await
460    {
461        warn!(
462            ctx,
463            "Transport {transport_id}: Failed to resync folders: {err:#}."
464        );
465        imap.resync_request_sender.try_send(()).ok();
466    }
467
468    maybe_add_time_based_warnings(ctx).await;
469
470    match ctx.get_config_i64(Config::LastHousekeeping).await {
471        Ok(last_housekeeping_time) => {
472            let next_housekeeping_time =
473                last_housekeeping_time.saturating_add(constants::HOUSEKEEPING_PERIOD);
474            if next_housekeeping_time <= time() {
475                sql::housekeeping(ctx).await.log_err(ctx).ok();
476            }
477        }
478        Err(err) => {
479            warn!(
480                ctx,
481                "Transport {transport_id}: Failed to get last housekeeping time: {err:#}"
482            );
483        }
484    };
485
486    maybe_send_stats(ctx).await.log_err(ctx).ok();
487
488    session
489        .update_metadata(ctx)
490        .await
491        .context("update_metadata")?;
492    session
493        .register_token(ctx)
494        .await
495        .context("Failed to register push token")?;
496
497    let session = fetch_idle(ctx, imap, session, FolderMeaning::Inbox).await?;
498    Ok(session)
499}
500
501/// Implement a single iteration of IMAP loop.
502///
503/// This function performs all IMAP operations on a single folder, selecting it if necessary and
504/// handling all the errors. In case of an error, an error is returned and connection is dropped,
505/// otherwise connection is returned.
506async fn fetch_idle(
507    ctx: &Context,
508    connection: &mut Imap,
509    mut session: Session,
510    folder_meaning: FolderMeaning,
511) -> Result<Session> {
512    let transport_id = session.transport_id();
513
514    let Some((folder_config, watch_folder)) = convert_folder_meaning(ctx, folder_meaning).await?
515    else {
516        // The folder is not configured.
517        // For example, this happens if the server does not have Sent folder
518        // but watching Sent folder is enabled.
519        connection.connectivity.set_not_configured(ctx);
520        connection.idle_interrupt_receiver.recv().await.ok();
521        bail!("Cannot fetch folder {folder_meaning} because it is not configured");
522    };
523
524    if folder_config == Config::ConfiguredInboxFolder {
525        session
526            .store_seen_flags_on_imap(ctx)
527            .await
528            .context("store_seen_flags_on_imap")?;
529    }
530
531    // Fetch the watched folder.
532    connection
533        .fetch_move_delete(ctx, &mut session, &watch_folder, folder_meaning)
534        .await
535        .context("fetch_move_delete")?;
536
537    // Mark expired messages for deletion. Marked messages will be deleted from the server
538    // on the next iteration of `fetch_move_delete`. `delete_expired_imap_messages` is not
539    // called right before `fetch_move_delete` because it is not well optimized and would
540    // otherwise slow down message fetching.
541    delete_expired_imap_messages(ctx)
542        .await
543        .context("delete_expired_imap_messages")?;
544
545    download_known_post_messages_without_pre_message(ctx, &mut session).await?;
546    download_msgs(ctx, &mut session)
547        .await
548        .context("download_msgs")?;
549
550    // Synchronize Seen flags.
551    session
552        .sync_seen_flags(ctx, &watch_folder)
553        .await
554        .context("sync_seen_flags")
555        .log_err(ctx)
556        .ok();
557
558    connection.connectivity.set_idle(ctx);
559
560    ctx.emit_event(EventType::ImapInboxIdle);
561
562    if !session.can_idle() {
563        info!(
564            ctx,
565            "Transport {transport_id}: IMAP session does not support IDLE, going to fake idle."
566        );
567        connection.fake_idle(ctx, watch_folder).await?;
568        return Ok(session);
569    }
570
571    if ctx
572        .get_config_bool(Config::DisableIdle)
573        .await
574        .context("Failed to get disable_idle config")
575        .log_err(ctx)
576        .unwrap_or_default()
577    {
578        info!(
579            ctx,
580            "Transport {transport_id}: IMAP IDLE is disabled, going to fake idle."
581        );
582        connection.fake_idle(ctx, watch_folder).await?;
583        return Ok(session);
584    }
585
586    let session = session
587        .idle(
588            ctx,
589            connection.idle_interrupt_receiver.clone(),
590            &watch_folder,
591        )
592        .await
593        .context("idle")?;
594
595    Ok(session)
596}
597
598/// Simplified IMAP loop to watch non-inbox folders.
599async fn simple_imap_loop(
600    ctx: Context,
601    started: oneshot::Sender<()>,
602    inbox_handlers: ImapConnectionHandlers,
603    folder_meaning: FolderMeaning,
604) {
605    use futures::future::FutureExt;
606
607    info!(ctx, "Starting simple loop for {folder_meaning}.");
608    let ImapConnectionHandlers {
609        mut connection,
610        stop_token,
611    } = inbox_handlers;
612
613    let ctx1 = ctx.clone();
614
615    let fut = async move {
616        let ctx = ctx1;
617        if let Err(()) = started.send(()) {
618            warn!(
619                ctx,
620                "Simple imap loop for {folder_meaning}, missing started receiver."
621            );
622            return;
623        }
624
625        let mut old_session: Option<Session> = None;
626        loop {
627            let session = if let Some(session) = old_session.take() {
628                session
629            } else {
630                info!(ctx, "Preparing new IMAP session for {folder_meaning}.");
631                match connection.prepare(&ctx).await {
632                    Err(err) => {
633                        warn!(
634                            ctx,
635                            "Failed to prepare {folder_meaning} connection: {err:#}."
636                        );
637                        continue;
638                    }
639                    Ok(session) => session,
640                }
641            };
642
643            match fetch_idle(&ctx, &mut connection, session, folder_meaning).await {
644                Err(err) => warn!(ctx, "Failed fetch_idle: {err:#}"),
645                Ok(session) => {
646                    old_session = Some(session);
647                }
648            }
649        }
650    };
651
652    stop_token
653        .cancelled()
654        .map(|_| {
655            info!(ctx, "Shutting down IMAP loop for {folder_meaning}.");
656        })
657        .race(fut)
658        .await;
659}
660
661async fn smtp_loop(
662    ctx: Context,
663    started: oneshot::Sender<()>,
664    smtp_handlers: SmtpConnectionHandlers,
665) {
666    use futures::future::FutureExt;
667
668    info!(ctx, "Starting SMTP loop.");
669    let SmtpConnectionHandlers {
670        mut connection,
671        stop_token,
672        idle_interrupt_receiver,
673    } = smtp_handlers;
674
675    let ctx1 = ctx.clone();
676    let fut = async move {
677        let ctx = ctx1;
678        if let Err(()) = started.send(()) {
679            warn!(&ctx, "SMTP loop, missing started receiver.");
680            return;
681        }
682
683        let mut timeout = None;
684        loop {
685            if let Err(err) = send_smtp_messages(&ctx, &mut connection).await {
686                warn!(ctx, "send_smtp_messages failed: {:#}.", err);
687                timeout = Some(timeout.unwrap_or(30));
688            } else {
689                timeout = None;
690                let duration_until_can_send = ctx.ratelimit.read().await.until_can_send();
691                if !duration_until_can_send.is_zero() {
692                    info!(
693                        ctx,
694                        "smtp got rate limited, waiting for {} until can send again",
695                        duration_to_str(duration_until_can_send)
696                    );
697                    tokio::time::sleep(duration_until_can_send).await;
698                    continue;
699                }
700            }
701
702            stats::maybe_update_message_stats(&ctx)
703                .await
704                .log_err(&ctx)
705                .ok();
706
707            // Fake Idle
708            info!(ctx, "SMTP fake idle started.");
709            match &connection.last_send_error {
710                None => connection.connectivity.set_idle(&ctx),
711                Some(err) => connection.connectivity.set_err(&ctx, err),
712            }
713
714            // If send_smtp_messages() failed, we set a timeout for the fake-idle so that
715            // sending is retried (at the latest) after the timeout. If sending fails
716            // again, we increase the timeout exponentially, in order not to do lots of
717            // unnecessary retries.
718            if let Some(t) = timeout {
719                let now = tools::Time::now();
720                info!(
721                    ctx,
722                    "SMTP has messages to retry, planning to retry {t} seconds later."
723                );
724                let duration = std::time::Duration::from_secs(t);
725                tokio::time::timeout(duration, async {
726                    idle_interrupt_receiver.recv().await.unwrap_or_default()
727                })
728                .await
729                .unwrap_or_default();
730                let slept = time_elapsed(&now).as_secs();
731                timeout = Some(cmp::max(
732                    t,
733                    slept.saturating_add(rand::random_range((slept / 2)..=slept)),
734                ));
735            } else {
736                info!(ctx, "SMTP has no messages to retry, waiting for interrupt.");
737                idle_interrupt_receiver.recv().await.unwrap_or_default();
738            };
739
740            info!(ctx, "SMTP fake idle interrupted.")
741        }
742    };
743
744    stop_token
745        .cancelled()
746        .map(|_| {
747            info!(ctx, "Shutting down SMTP loop.");
748        })
749        .race(fut)
750        .await;
751}
752
753impl Scheduler {
754    /// Start the scheduler.
755    pub async fn start(ctx: &Context) -> Result<Self> {
756        let (smtp, smtp_handlers) = SmtpConnectionState::new();
757
758        let (smtp_start_send, smtp_start_recv) = oneshot::channel();
759        let (ephemeral_interrupt_send, ephemeral_interrupt_recv) = channel::bounded(1);
760        let (location_interrupt_send, location_interrupt_recv) = channel::bounded(1);
761
762        let mut inboxes = Vec::new();
763        let mut oboxes = Vec::new();
764        let mut start_recvs = Vec::new();
765
766        for (transport_id, configured_login_param) in ConfiguredLoginParam::load_all(ctx).await? {
767            let (conn_state, inbox_handlers) =
768                ImapConnectionState::new(ctx, transport_id, configured_login_param.clone()).await?;
769            let (inbox_start_send, inbox_start_recv) = oneshot::channel();
770            let handle = {
771                let ctx = ctx.clone();
772                task::spawn(inbox_loop(ctx, inbox_start_send, inbox_handlers))
773            };
774            let addr = configured_login_param.addr.clone();
775            let inbox = SchedBox {
776                addr: addr.clone(),
777                meaning: FolderMeaning::Inbox,
778                conn_state,
779                handle,
780            };
781            inboxes.push(inbox);
782            start_recvs.push(inbox_start_recv);
783
784            if ctx.should_watch_mvbox().await? {
785                let (conn_state, handlers) =
786                    ImapConnectionState::new(ctx, transport_id, configured_login_param).await?;
787                let (start_send, start_recv) = oneshot::channel();
788                let ctx = ctx.clone();
789                let meaning = FolderMeaning::Mvbox;
790                let handle = task::spawn(simple_imap_loop(ctx, start_send, handlers, meaning));
791                oboxes.push(SchedBox {
792                    addr,
793                    meaning,
794                    conn_state,
795                    handle,
796                });
797                start_recvs.push(start_recv);
798            }
799        }
800
801        let smtp_handle = {
802            let ctx = ctx.clone();
803            task::spawn(smtp_loop(ctx, smtp_start_send, smtp_handlers))
804        };
805        start_recvs.push(smtp_start_recv);
806
807        let ephemeral_handle = {
808            let ctx = ctx.clone();
809            task::spawn(async move {
810                ephemeral::ephemeral_loop(&ctx, ephemeral_interrupt_recv).await;
811            })
812        };
813
814        let location_handle = {
815            let ctx = ctx.clone();
816            task::spawn(async move {
817                location::location_loop(&ctx, location_interrupt_recv).await;
818            })
819        };
820
821        let recently_seen_loop = RecentlySeenLoop::new(ctx.clone());
822
823        let res = Self {
824            inboxes,
825            oboxes,
826            smtp,
827            smtp_handle,
828            ephemeral_handle,
829            ephemeral_interrupt_send,
830            location_handle,
831            location_interrupt_send,
832            recently_seen_loop,
833        };
834
835        // wait for all loops to be started
836        if let Err(err) = try_join_all(start_recvs).await {
837            bail!("failed to start scheduler: {err}");
838        }
839
840        info!(ctx, "scheduler is running");
841        Ok(res)
842    }
843
844    fn boxes(&self) -> impl Iterator<Item = &SchedBox> {
845        self.inboxes.iter().chain(self.oboxes.iter())
846    }
847
848    fn maybe_network(&self) {
849        for b in self.boxes() {
850            b.conn_state.interrupt();
851        }
852        self.interrupt_smtp();
853    }
854
855    fn maybe_network_lost(&self) {
856        for b in self.boxes() {
857            b.conn_state.interrupt();
858        }
859        self.interrupt_smtp();
860    }
861
862    fn interrupt_inbox(&self) {
863        for b in &self.inboxes {
864            b.conn_state.interrupt();
865        }
866    }
867
868    fn interrupt_smtp(&self) {
869        self.smtp.interrupt();
870    }
871
872    fn interrupt_ephemeral_task(&self) {
873        self.ephemeral_interrupt_send.try_send(()).ok();
874    }
875
876    fn interrupt_location(&self) {
877        self.location_interrupt_send.try_send(()).ok();
878    }
879
880    fn interrupt_recently_seen(&self, contact_id: ContactId, timestamp: i64) {
881        self.recently_seen_loop.try_interrupt(contact_id, timestamp);
882    }
883
884    /// Halt the scheduler.
885    ///
886    /// It consumes the scheduler and never fails to stop it. In the worst case, long-running tasks
887    /// are forcefully terminated if they cannot shutdown within the timeout.
888    pub(crate) async fn stop(self, context: &Context) {
889        // Send stop signals to tasks so they can shutdown cleanly.
890        for b in self.boxes() {
891            b.conn_state.stop();
892        }
893        self.smtp.stop();
894
895        // Actually shutdown tasks.
896        let timeout_duration = std::time::Duration::from_secs(30);
897
898        let tracker = TaskTracker::new();
899        for b in self.inboxes.into_iter().chain(self.oboxes) {
900            let context = context.clone();
901            tracker.spawn(async move {
902                tokio::time::timeout(timeout_duration, b.handle)
903                    .await
904                    .log_err(&context)
905            });
906        }
907        {
908            let context = context.clone();
909            tracker.spawn(async move {
910                tokio::time::timeout(timeout_duration, self.smtp_handle)
911                    .await
912                    .log_err(&context)
913            });
914        }
915        tracker.close();
916        tracker.wait().await;
917
918        // Abort tasks, then await them to ensure the `Future` is dropped.
919        // Just aborting the task may keep resources such as `Context` clone
920        // moved into it indefinitely, resulting in database not being
921        // closed etc.
922        self.ephemeral_handle.abort();
923        self.ephemeral_handle.await.ok();
924        self.location_handle.abort();
925        self.location_handle.await.ok();
926        self.recently_seen_loop.abort().await;
927    }
928}
929
930/// Connection state logic shared between imap and smtp connections.
931#[derive(Debug)]
932struct ConnectionState {
933    /// Cancellation token to interrupt the whole connection.
934    stop_token: CancellationToken,
935    /// Channel to interrupt idle.
936    idle_interrupt_sender: Sender<()>,
937    /// Mutex to pass connectivity info between IMAP/SMTP threads and the API
938    connectivity: ConnectivityStore,
939}
940
941impl ConnectionState {
942    /// Shutdown this connection completely.
943    fn stop(&self) {
944        // Trigger shutdown of the run loop.
945        self.stop_token.cancel();
946    }
947
948    fn interrupt(&self) {
949        // Use try_send to avoid blocking on interrupts.
950        self.idle_interrupt_sender.try_send(()).ok();
951    }
952}
953
954#[derive(Debug)]
955pub(crate) struct SmtpConnectionState {
956    state: ConnectionState,
957}
958
959impl SmtpConnectionState {
960    fn new() -> (Self, SmtpConnectionHandlers) {
961        let stop_token = CancellationToken::new();
962        let (idle_interrupt_sender, idle_interrupt_receiver) = channel::bounded(1);
963
964        let handlers = SmtpConnectionHandlers {
965            connection: Smtp::new(),
966            stop_token: stop_token.clone(),
967            idle_interrupt_receiver,
968        };
969
970        let state = ConnectionState {
971            stop_token,
972            idle_interrupt_sender,
973            connectivity: handlers.connection.connectivity.clone(),
974        };
975
976        let conn = SmtpConnectionState { state };
977
978        (conn, handlers)
979    }
980
981    /// Interrupt any form of idle.
982    fn interrupt(&self) {
983        self.state.interrupt();
984    }
985
986    /// Shutdown this connection completely.
987    fn stop(&self) {
988        self.state.stop();
989    }
990}
991
992struct SmtpConnectionHandlers {
993    connection: Smtp,
994    stop_token: CancellationToken,
995    idle_interrupt_receiver: Receiver<()>,
996}
997
998#[derive(Debug)]
999pub(crate) struct ImapConnectionState {
1000    state: ConnectionState,
1001}
1002
1003impl ImapConnectionState {
1004    /// Construct a new connection.
1005    async fn new(
1006        context: &Context,
1007        transport_id: u32,
1008        login_param: ConfiguredLoginParam,
1009    ) -> Result<(Self, ImapConnectionHandlers)> {
1010        let stop_token = CancellationToken::new();
1011        let (idle_interrupt_sender, idle_interrupt_receiver) = channel::bounded(1);
1012
1013        let handlers = ImapConnectionHandlers {
1014            connection: Imap::new(context, transport_id, login_param, idle_interrupt_receiver)
1015                .await?,
1016            stop_token: stop_token.clone(),
1017        };
1018
1019        let state = ConnectionState {
1020            stop_token,
1021            idle_interrupt_sender,
1022            connectivity: handlers.connection.connectivity.clone(),
1023        };
1024
1025        let conn = ImapConnectionState { state };
1026
1027        Ok((conn, handlers))
1028    }
1029
1030    /// Interrupt any form of idle.
1031    fn interrupt(&self) {
1032        self.state.interrupt();
1033    }
1034
1035    /// Shutdown this connection completely.
1036    fn stop(&self) {
1037        self.state.stop();
1038    }
1039}
1040
1041#[derive(Debug)]
1042struct ImapConnectionHandlers {
1043    connection: Imap,
1044    stop_token: CancellationToken,
1045}