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::{self, Config};
15use crate::contact::{ContactId, RecentlySeenLoop};
16use crate::context::Context;
17use crate::download::{DownloadState, download_msg};
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::message::MsgId;
24use crate::smtp::{Smtp, send_smtp_messages};
25use crate::sql;
26use crate::stats::maybe_send_stats;
27use crate::tools::{self, duration_to_str, maybe_add_time_based_warnings, time, time_elapsed};
28use crate::transport::ConfiguredLoginParam;
29use crate::{constants, stats};
30
31pub(crate) mod connectivity;
32
33#[derive(Debug, Default)]
39pub(crate) struct SchedulerState {
40 inner: RwLock<InnerSchedulerState>,
41}
42
43impl SchedulerState {
44 pub(crate) fn new() -> Self {
45 Default::default()
46 }
47
48 pub(crate) async fn is_running(&self) -> bool {
50 let inner = self.inner.read().await;
51 matches!(*inner, InnerSchedulerState::Started(_))
52 }
53
54 pub(crate) async fn start(&self, context: &Context) {
56 let mut inner = self.inner.write().await;
57 match *inner {
58 InnerSchedulerState::Started(_) => (),
59 InnerSchedulerState::Stopped => Self::do_start(&mut inner, context).await,
60 InnerSchedulerState::Paused {
61 ref mut started, ..
62 } => *started = true,
63 }
64 context.update_connectivities(&inner);
65 }
66
67 async fn do_start(inner: &mut InnerSchedulerState, context: &Context) {
69 info!(context, "starting IO");
70
71 context.new_msgs_notify.notify_one();
74
75 match Scheduler::start(context).await {
76 Ok(scheduler) => {
77 *inner = InnerSchedulerState::Started(scheduler);
78 context.emit_event(EventType::ConnectivityChanged);
79 }
80 Err(err) => error!(context, "Failed to start IO: {:#}", err),
81 }
82 }
83
84 pub(crate) async fn stop(&self, context: &Context) {
86 let mut inner = self.inner.write().await;
87 match *inner {
88 InnerSchedulerState::Started(_) => {
89 Self::do_stop(&mut inner, context, InnerSchedulerState::Stopped).await
90 }
91 InnerSchedulerState::Stopped => (),
92 InnerSchedulerState::Paused {
93 ref mut started, ..
94 } => *started = false,
95 }
96 context.update_connectivities(&inner);
97 }
98
99 async fn do_stop(
101 inner: &mut InnerSchedulerState,
102 context: &Context,
103 new_state: InnerSchedulerState,
104 ) {
105 info!(context, "stopping IO");
111
112 context.new_msgs_notify.notify_one();
115
116 let debug_logging = context
117 .debug_logging
118 .write()
119 .expect("RwLock is poisoned")
120 .take();
121 if let Some(debug_logging) = debug_logging {
122 debug_logging.loop_handle.abort();
123 debug_logging.loop_handle.await.ok();
124 }
125 let prev_state = std::mem::replace(inner, new_state);
126 context.emit_event(EventType::ConnectivityChanged);
127 match prev_state {
128 InnerSchedulerState::Started(scheduler) => scheduler.stop(context).await,
129 InnerSchedulerState::Stopped | InnerSchedulerState::Paused { .. } => (),
130 }
131 }
132
133 pub(crate) async fn pause(&'_ self, context: &Context) -> Result<IoPausedGuard> {
142 {
143 let mut inner = self.inner.write().await;
144 match *inner {
145 InnerSchedulerState::Started(_) => {
146 let new_state = InnerSchedulerState::Paused {
147 started: true,
148 pause_guards_count: NonZeroUsize::MIN,
149 };
150 Self::do_stop(&mut inner, context, new_state).await;
151 }
152 InnerSchedulerState::Stopped => {
153 *inner = InnerSchedulerState::Paused {
154 started: false,
155 pause_guards_count: NonZeroUsize::MIN,
156 };
157 }
158 InnerSchedulerState::Paused {
159 ref mut pause_guards_count,
160 ..
161 } => {
162 *pause_guards_count = pause_guards_count
163 .checked_add(1)
164 .ok_or_else(|| Error::msg("Too many pause guards active"))?
165 }
166 }
167 context.update_connectivities(&inner);
168 }
169
170 let (tx, rx) = oneshot::channel();
171 let context = context.clone();
172 tokio::spawn(async move {
173 rx.await.ok();
174 let mut inner = context.scheduler.inner.write().await;
175 match *inner {
176 InnerSchedulerState::Started(_) => {
177 warn!(&context, "IoPausedGuard resume: started instead of paused");
178 }
179 InnerSchedulerState::Stopped => {
180 warn!(&context, "IoPausedGuard resume: stopped instead of paused");
181 }
182 InnerSchedulerState::Paused {
183 ref started,
184 ref mut pause_guards_count,
185 } => {
186 if *pause_guards_count == NonZeroUsize::MIN {
187 match *started {
188 true => SchedulerState::do_start(&mut inner, &context).await,
189 false => *inner = InnerSchedulerState::Stopped,
190 }
191 } else {
192 let new_count = pause_guards_count.get() - 1;
193 *pause_guards_count = NonZeroUsize::new(new_count).unwrap();
195 }
196 }
197 }
198 context.update_connectivities(&inner);
199 });
200 Ok(IoPausedGuard { sender: Some(tx) })
201 }
202
203 pub(crate) async fn restart(&self, context: &Context) {
205 info!(context, "restarting IO");
206 if self.is_running().await {
207 self.stop(context).await;
208 self.start(context).await;
209 }
210 }
211
212 pub(crate) async fn maybe_network(&self) {
214 let inner = self.inner.read().await;
215 let (inboxes, oboxes) = match *inner {
216 InnerSchedulerState::Started(ref scheduler) => {
217 scheduler.maybe_network();
218 let inboxes = scheduler
219 .inboxes
220 .iter()
221 .map(|b| b.conn_state.state.connectivity.clone())
222 .collect::<Vec<_>>();
223 let oboxes = scheduler
224 .oboxes
225 .iter()
226 .map(|b| b.conn_state.state.connectivity.clone())
227 .collect::<Vec<_>>();
228 (inboxes, oboxes)
229 }
230 _ => return,
231 };
232 drop(inner);
233 connectivity::idle_interrupted(inboxes, oboxes);
234 }
235
236 pub(crate) async fn maybe_network_lost(&self, context: &Context) {
238 let inner = self.inner.read().await;
239 let stores = match *inner {
240 InnerSchedulerState::Started(ref scheduler) => {
241 scheduler.maybe_network_lost();
242 scheduler
243 .boxes()
244 .map(|b| b.conn_state.state.connectivity.clone())
245 .collect()
246 }
247 _ => return,
248 };
249 drop(inner);
250 connectivity::maybe_network_lost(context, stores);
251 }
252
253 pub(crate) async fn interrupt_inbox(&self) {
254 let inner = self.inner.read().await;
255 if let InnerSchedulerState::Started(ref scheduler) = *inner {
256 scheduler.interrupt_inbox();
257 }
258 }
259
260 pub(crate) async fn interrupt_oboxes(&self) {
262 let inner = self.inner.read().await;
263 if let InnerSchedulerState::Started(ref scheduler) = *inner {
264 scheduler.interrupt_oboxes();
265 }
266 }
267
268 pub(crate) async fn interrupt_smtp(&self) {
269 let inner = self.inner.read().await;
270 if let InnerSchedulerState::Started(ref scheduler) = *inner {
271 scheduler.interrupt_smtp();
272 }
273 }
274
275 pub(crate) async fn interrupt_ephemeral_task(&self) {
276 let inner = self.inner.read().await;
277 if let InnerSchedulerState::Started(ref scheduler) = *inner {
278 scheduler.interrupt_ephemeral_task();
279 }
280 }
281
282 pub(crate) async fn interrupt_location(&self) {
283 let inner = self.inner.read().await;
284 if let InnerSchedulerState::Started(ref scheduler) = *inner {
285 scheduler.interrupt_location();
286 }
287 }
288
289 pub(crate) async fn interrupt_recently_seen(&self, contact_id: ContactId, timestamp: i64) {
290 let inner = self.inner.read().await;
291 if let InnerSchedulerState::Started(ref scheduler) = *inner {
292 scheduler.interrupt_recently_seen(contact_id, timestamp);
293 }
294 }
295}
296
297#[derive(Debug, Default)]
298pub(crate) enum InnerSchedulerState {
299 Started(Scheduler),
300 #[default]
301 Stopped,
302 Paused {
303 started: bool,
304 pause_guards_count: NonZeroUsize,
305 },
306}
307
308#[derive(Default, Debug)]
313pub(crate) struct IoPausedGuard {
314 sender: Option<oneshot::Sender<()>>,
315}
316
317impl Drop for IoPausedGuard {
318 fn drop(&mut self) {
319 if let Some(sender) = self.sender.take() {
320 sender.send(()).ok();
322 }
323 }
324}
325
326#[derive(Debug)]
327struct SchedBox {
328 meaning: FolderMeaning,
329 conn_state: ImapConnectionState,
330
331 handle: task::JoinHandle<()>,
333}
334
335#[derive(Debug)]
337pub(crate) struct Scheduler {
338 inboxes: Vec<SchedBox>,
340 oboxes: Vec<SchedBox>,
342 smtp: SmtpConnectionState,
343 smtp_handle: task::JoinHandle<()>,
344 ephemeral_handle: task::JoinHandle<()>,
345 ephemeral_interrupt_send: Sender<()>,
346 location_handle: task::JoinHandle<()>,
347 location_interrupt_send: Sender<()>,
348
349 recently_seen_loop: RecentlySeenLoop,
350}
351
352async fn download_msgs(context: &Context, session: &mut Session) -> Result<()> {
353 let msg_ids = context
354 .sql
355 .query_map_vec("SELECT msg_id FROM download", (), |row| {
356 let msg_id: MsgId = row.get(0)?;
357 Ok(msg_id)
358 })
359 .await?;
360
361 for msg_id in msg_ids {
362 if let Err(err) = download_msg(context, msg_id, session).await {
363 warn!(context, "Failed to download message {msg_id}: {:#}.", err);
364
365 msg_id
372 .update_download_state(context, DownloadState::Failure)
373 .await?;
374 }
375 context
376 .sql
377 .execute("DELETE FROM download WHERE msg_id=?", (msg_id,))
378 .await?;
379 }
380
381 Ok(())
382}
383
384async fn inbox_loop(
385 ctx: Context,
386 started: oneshot::Sender<()>,
387 inbox_handlers: ImapConnectionHandlers,
388) {
389 use futures::future::FutureExt;
390
391 info!(ctx, "Starting inbox loop.");
392 let ImapConnectionHandlers {
393 mut connection,
394 stop_token,
395 } = inbox_handlers;
396
397 let ctx1 = ctx.clone();
398 let fut = async move {
399 let ctx = ctx1;
400 if let Err(()) = started.send(()) {
401 warn!(ctx, "Inbox loop, missing started receiver.");
402 return;
403 };
404
405 let mut old_session: Option<Session> = None;
406 loop {
407 let session = if let Some(session) = old_session.take() {
408 session
409 } else {
410 info!(ctx, "Preparing new IMAP session for inbox.");
411 match connection.prepare(&ctx).await {
412 Err(err) => {
413 warn!(ctx, "Failed to prepare inbox connection: {err:#}.");
414 continue;
415 }
416 Ok(session) => session,
417 }
418 };
419
420 match inbox_fetch_idle(&ctx, &mut connection, session).await {
421 Err(err) => warn!(ctx, "Failed inbox fetch_idle: {err:#}."),
422 Ok(session) => {
423 info!(
424 ctx,
425 "IMAP loop iteration for inbox finished, keeping the session."
426 );
427 old_session = Some(session);
428 }
429 }
430 }
431 };
432
433 stop_token
434 .cancelled()
435 .map(|_| {
436 info!(ctx, "Shutting down inbox loop.");
437 })
438 .race(fut)
439 .await;
440}
441
442pub async fn convert_folder_meaning(
448 ctx: &Context,
449 folder_meaning: FolderMeaning,
450) -> Result<Option<(Config, String)>> {
451 let folder_config = match folder_meaning.to_config() {
452 Some(c) => c,
453 None => {
454 return Ok(None);
457 }
458 };
459
460 let folder = ctx
461 .get_config(folder_config)
462 .await
463 .with_context(|| format!("Failed to retrieve {folder_config} folder"))?;
464
465 if let Some(watch_folder) = folder {
466 Ok(Some((folder_config, watch_folder)))
467 } else {
468 Ok(None)
469 }
470}
471
472async fn inbox_fetch_idle(ctx: &Context, imap: &mut Imap, mut session: Session) -> Result<Session> {
473 if !ctx.get_config_bool(Config::FixIsChatmail).await? {
474 ctx.set_config_internal(
475 Config::IsChatmail,
476 crate::config::from_bool(session.is_chatmail()),
477 )
478 .await?;
479 }
480
481 if ctx.quota_needs_update(60).await
483 && let Err(err) = ctx.update_recent_quota(&mut session).await
484 {
485 warn!(ctx, "Failed to update quota: {:#}.", err);
486 }
487
488 if let Ok(()) = imap.resync_request_receiver.try_recv()
489 && let Err(err) = session.resync_folders(ctx).await
490 {
491 warn!(ctx, "Failed to resync folders: {:#}.", err);
492 imap.resync_request_sender.try_send(()).ok();
493 }
494
495 maybe_add_time_based_warnings(ctx).await;
496
497 match ctx.get_config_i64(Config::LastHousekeeping).await {
498 Ok(last_housekeeping_time) => {
499 let next_housekeeping_time =
500 last_housekeeping_time.saturating_add(constants::HOUSEKEEPING_PERIOD);
501 if next_housekeeping_time <= time() {
502 sql::housekeeping(ctx).await.log_err(ctx).ok();
503 }
504 }
505 Err(err) => {
506 warn!(ctx, "Failed to get last housekeeping time: {}", err);
507 }
508 };
509
510 maybe_send_stats(ctx).await.log_err(ctx).ok();
511 match ctx.get_config_bool(Config::FetchedExistingMsgs).await {
512 Ok(fetched_existing_msgs) => {
513 if !fetched_existing_msgs {
514 if let Err(err) = ctx
519 .set_config_internal(Config::FetchedExistingMsgs, config::from_bool(true))
520 .await
521 {
522 warn!(ctx, "Can't set Config::FetchedExistingMsgs: {:#}", err);
523 }
524
525 if let Err(err) = imap.fetch_existing_msgs(ctx, &mut session).await {
526 warn!(ctx, "Failed to fetch existing messages: {:#}", err);
527 }
528 }
529 }
530 Err(err) => {
531 warn!(ctx, "Can't get Config::FetchedExistingMsgs: {:#}", err);
532 }
533 }
534
535 download_msgs(ctx, &mut session)
536 .await
537 .context("Failed to download messages")?;
538 session
539 .fetch_metadata(ctx)
540 .await
541 .context("Failed to fetch metadata")?;
542 session
543 .register_token(ctx)
544 .await
545 .context("Failed to register push token")?;
546
547 let session = fetch_idle(ctx, imap, session, FolderMeaning::Inbox).await?;
548 Ok(session)
549}
550
551async fn fetch_idle(
557 ctx: &Context,
558 connection: &mut Imap,
559 mut session: Session,
560 folder_meaning: FolderMeaning,
561) -> Result<Session> {
562 let Some((folder_config, watch_folder)) = convert_folder_meaning(ctx, folder_meaning).await?
563 else {
564 connection.connectivity.set_not_configured(ctx);
568 connection.idle_interrupt_receiver.recv().await.ok();
569 bail!("Cannot fetch folder {folder_meaning} because it is not configured");
570 };
571
572 if folder_config == Config::ConfiguredInboxFolder {
573 let mvbox;
574 let syncbox = match ctx.should_move_sync_msgs().await? {
575 false => &watch_folder,
576 true => {
577 mvbox = ctx.get_config(Config::ConfiguredMvboxFolder).await?;
578 mvbox.as_deref().unwrap_or(&watch_folder)
579 }
580 };
581 if ctx
582 .get_config(Config::ConfiguredAddr)
583 .await?
584 .unwrap_or_default()
585 == connection.addr
586 {
587 session
588 .send_sync_msgs(ctx, syncbox)
589 .await
590 .context("fetch_idle: send_sync_msgs")
591 .log_err(ctx)
592 .ok();
593 }
594
595 session
596 .store_seen_flags_on_imap(ctx)
597 .await
598 .context("store_seen_flags_on_imap")?;
599 }
600
601 if !ctx.should_delete_to_trash().await?
602 || ctx
603 .get_config(Config::ConfiguredTrashFolder)
604 .await?
605 .is_some()
606 {
607 connection
609 .fetch_move_delete(ctx, &mut session, &watch_folder, folder_meaning)
610 .await
611 .context("fetch_move_delete")?;
612
613 delete_expired_imap_messages(ctx)
618 .await
619 .context("delete_expired_imap_messages")?;
620 } else if folder_config == Config::ConfiguredInboxFolder {
621 session.last_full_folder_scan.lock().await.take();
622 }
623
624 if folder_config == Config::ConfiguredInboxFolder {
629 match connection
631 .scan_folders(ctx, &mut session)
632 .await
633 .context("scan_folders")
634 {
635 Err(err) => {
636 warn!(ctx, "{:#}", err);
639 }
640 Ok(true) => {
641 connection
648 .fetch_move_delete(ctx, &mut session, &watch_folder, folder_meaning)
649 .await
650 .context("fetch_move_delete after scan_folders")?;
651 }
652 Ok(false) => {}
653 }
654 }
655
656 session
658 .sync_seen_flags(ctx, &watch_folder)
659 .await
660 .context("sync_seen_flags")
661 .log_err(ctx)
662 .ok();
663
664 connection.connectivity.set_idle(ctx);
665
666 ctx.emit_event(EventType::ImapInboxIdle);
667
668 if !session.can_idle() {
669 info!(
670 ctx,
671 "IMAP session does not support IDLE, going to fake idle."
672 );
673 connection.fake_idle(ctx, watch_folder).await?;
674 return Ok(session);
675 }
676
677 if ctx
678 .get_config_bool(Config::DisableIdle)
679 .await
680 .context("Failed to get disable_idle config")
681 .log_err(ctx)
682 .unwrap_or_default()
683 {
684 info!(ctx, "IMAP IDLE is disabled, going to fake idle.");
685 connection.fake_idle(ctx, watch_folder).await?;
686 return Ok(session);
687 }
688
689 info!(
690 ctx,
691 "IMAP session in folder {watch_folder:?} supports IDLE, using it."
692 );
693 let session = session
694 .idle(
695 ctx,
696 connection.idle_interrupt_receiver.clone(),
697 &watch_folder,
698 )
699 .await
700 .context("idle")?;
701
702 Ok(session)
703}
704
705async fn simple_imap_loop(
706 ctx: Context,
707 started: oneshot::Sender<()>,
708 inbox_handlers: ImapConnectionHandlers,
709 folder_meaning: FolderMeaning,
710) {
711 use futures::future::FutureExt;
712
713 info!(ctx, "Starting simple loop for {folder_meaning}.");
714 let ImapConnectionHandlers {
715 mut connection,
716 stop_token,
717 } = inbox_handlers;
718
719 let ctx1 = ctx.clone();
720
721 let fut = async move {
722 let ctx = ctx1;
723 if let Err(()) = started.send(()) {
724 warn!(
725 ctx,
726 "Simple imap loop for {folder_meaning}, missing started receiver."
727 );
728 return;
729 }
730
731 let mut old_session: Option<Session> = None;
732 loop {
733 let session = if let Some(session) = old_session.take() {
734 session
735 } else {
736 info!(ctx, "Preparing new IMAP session for {folder_meaning}.");
737 match connection.prepare(&ctx).await {
738 Err(err) => {
739 warn!(
740 ctx,
741 "Failed to prepare {folder_meaning} connection: {err:#}."
742 );
743 continue;
744 }
745 Ok(session) => session,
746 }
747 };
748
749 match fetch_idle(&ctx, &mut connection, session, folder_meaning).await {
750 Err(err) => warn!(ctx, "Failed fetch_idle: {err:#}"),
751 Ok(session) => {
752 info!(
753 ctx,
754 "IMAP loop iteration for {folder_meaning} finished, keeping the session"
755 );
756 old_session = Some(session);
757 }
758 }
759 }
760 };
761
762 stop_token
763 .cancelled()
764 .map(|_| {
765 info!(ctx, "Shutting down IMAP loop for {folder_meaning}.");
766 })
767 .race(fut)
768 .await;
769}
770
771async fn smtp_loop(
772 ctx: Context,
773 started: oneshot::Sender<()>,
774 smtp_handlers: SmtpConnectionHandlers,
775) {
776 use futures::future::FutureExt;
777
778 info!(ctx, "Starting SMTP loop.");
779 let SmtpConnectionHandlers {
780 mut connection,
781 stop_token,
782 idle_interrupt_receiver,
783 } = smtp_handlers;
784
785 let ctx1 = ctx.clone();
786 let fut = async move {
787 let ctx = ctx1;
788 if let Err(()) = started.send(()) {
789 warn!(&ctx, "SMTP loop, missing started receiver.");
790 return;
791 }
792
793 let mut timeout = None;
794 loop {
795 if let Err(err) = send_smtp_messages(&ctx, &mut connection).await {
796 warn!(ctx, "send_smtp_messages failed: {:#}.", err);
797 timeout = Some(timeout.unwrap_or(30));
798 } else {
799 timeout = None;
800 let duration_until_can_send = ctx.ratelimit.read().await.until_can_send();
801 if !duration_until_can_send.is_zero() {
802 info!(
803 ctx,
804 "smtp got rate limited, waiting for {} until can send again",
805 duration_to_str(duration_until_can_send)
806 );
807 tokio::time::sleep(duration_until_can_send).await;
808 continue;
809 }
810 }
811
812 stats::maybe_update_message_stats(&ctx)
813 .await
814 .log_err(&ctx)
815 .ok();
816
817 info!(ctx, "SMTP fake idle started.");
819 match &connection.last_send_error {
820 None => connection.connectivity.set_idle(&ctx),
821 Some(err) => connection.connectivity.set_err(&ctx, err),
822 }
823
824 if let Some(t) = timeout {
829 let now = tools::Time::now();
830 info!(
831 ctx,
832 "SMTP has messages to retry, planning to retry {t} seconds later."
833 );
834 let duration = std::time::Duration::from_secs(t);
835 tokio::time::timeout(duration, async {
836 idle_interrupt_receiver.recv().await.unwrap_or_default()
837 })
838 .await
839 .unwrap_or_default();
840 let slept = time_elapsed(&now).as_secs();
841 timeout = Some(cmp::max(
842 t,
843 slept.saturating_add(rand::random_range((slept / 2)..=slept)),
844 ));
845 } else {
846 info!(ctx, "SMTP has no messages to retry, waiting for interrupt.");
847 idle_interrupt_receiver.recv().await.unwrap_or_default();
848 };
849
850 info!(ctx, "SMTP fake idle interrupted.")
851 }
852 };
853
854 stop_token
855 .cancelled()
856 .map(|_| {
857 info!(ctx, "Shutting down SMTP loop.");
858 })
859 .race(fut)
860 .await;
861}
862
863impl Scheduler {
864 pub async fn start(ctx: &Context) -> Result<Self> {
866 let (smtp, smtp_handlers) = SmtpConnectionState::new();
867
868 let (smtp_start_send, smtp_start_recv) = oneshot::channel();
869 let (ephemeral_interrupt_send, ephemeral_interrupt_recv) = channel::bounded(1);
870 let (location_interrupt_send, location_interrupt_recv) = channel::bounded(1);
871
872 let mut inboxes = Vec::new();
873 let mut oboxes = Vec::new();
874 let mut start_recvs = Vec::new();
875
876 for (transport_id, configured_login_param) in ConfiguredLoginParam::load_all(ctx).await? {
877 let (conn_state, inbox_handlers) =
878 ImapConnectionState::new(ctx, transport_id, configured_login_param.clone()).await?;
879 let (inbox_start_send, inbox_start_recv) = oneshot::channel();
880 let handle = {
881 let ctx = ctx.clone();
882 task::spawn(inbox_loop(ctx, inbox_start_send, inbox_handlers))
883 };
884 let inbox = SchedBox {
885 meaning: FolderMeaning::Inbox,
886 conn_state,
887 handle,
888 };
889 inboxes.push(inbox);
890 start_recvs.push(inbox_start_recv);
891
892 if ctx.should_watch_mvbox().await? {
893 let (conn_state, handlers) =
894 ImapConnectionState::new(ctx, transport_id, configured_login_param).await?;
895 let (start_send, start_recv) = oneshot::channel();
896 let ctx = ctx.clone();
897 let meaning = FolderMeaning::Mvbox;
898 let handle = task::spawn(simple_imap_loop(ctx, start_send, handlers, meaning));
899 oboxes.push(SchedBox {
900 meaning,
901 conn_state,
902 handle,
903 });
904 start_recvs.push(start_recv);
905 }
906 }
907
908 let smtp_handle = {
909 let ctx = ctx.clone();
910 task::spawn(smtp_loop(ctx, smtp_start_send, smtp_handlers))
911 };
912 start_recvs.push(smtp_start_recv);
913
914 let ephemeral_handle = {
915 let ctx = ctx.clone();
916 task::spawn(async move {
917 ephemeral::ephemeral_loop(&ctx, ephemeral_interrupt_recv).await;
918 })
919 };
920
921 let location_handle = {
922 let ctx = ctx.clone();
923 task::spawn(async move {
924 location::location_loop(&ctx, location_interrupt_recv).await;
925 })
926 };
927
928 let recently_seen_loop = RecentlySeenLoop::new(ctx.clone());
929
930 let res = Self {
931 inboxes,
932 oboxes,
933 smtp,
934 smtp_handle,
935 ephemeral_handle,
936 ephemeral_interrupt_send,
937 location_handle,
938 location_interrupt_send,
939 recently_seen_loop,
940 };
941
942 if let Err(err) = try_join_all(start_recvs).await {
944 bail!("failed to start scheduler: {err}");
945 }
946
947 info!(ctx, "scheduler is running");
948 Ok(res)
949 }
950
951 fn boxes(&self) -> impl Iterator<Item = &SchedBox> {
952 self.inboxes.iter().chain(self.oboxes.iter())
953 }
954
955 fn maybe_network(&self) {
956 for b in self.boxes() {
957 b.conn_state.interrupt();
958 }
959 self.interrupt_smtp();
960 }
961
962 fn maybe_network_lost(&self) {
963 for b in self.boxes() {
964 b.conn_state.interrupt();
965 }
966 self.interrupt_smtp();
967 }
968
969 fn interrupt_inbox(&self) {
970 for b in &self.inboxes {
971 b.conn_state.interrupt();
972 }
973 }
974
975 fn interrupt_oboxes(&self) {
976 for b in &self.oboxes {
977 b.conn_state.interrupt();
978 }
979 }
980
981 fn interrupt_smtp(&self) {
982 self.smtp.interrupt();
983 }
984
985 fn interrupt_ephemeral_task(&self) {
986 self.ephemeral_interrupt_send.try_send(()).ok();
987 }
988
989 fn interrupt_location(&self) {
990 self.location_interrupt_send.try_send(()).ok();
991 }
992
993 fn interrupt_recently_seen(&self, contact_id: ContactId, timestamp: i64) {
994 self.recently_seen_loop.try_interrupt(contact_id, timestamp);
995 }
996
997 pub(crate) async fn stop(self, context: &Context) {
1002 for b in self.boxes() {
1004 b.conn_state.stop();
1005 }
1006 self.smtp.stop();
1007
1008 let timeout_duration = std::time::Duration::from_secs(30);
1010
1011 let tracker = TaskTracker::new();
1012 for b in self.inboxes.into_iter().chain(self.oboxes.into_iter()) {
1013 let context = context.clone();
1014 tracker.spawn(async move {
1015 tokio::time::timeout(timeout_duration, b.handle)
1016 .await
1017 .log_err(&context)
1018 });
1019 }
1020 {
1021 let context = context.clone();
1022 tracker.spawn(async move {
1023 tokio::time::timeout(timeout_duration, self.smtp_handle)
1024 .await
1025 .log_err(&context)
1026 });
1027 }
1028 tracker.close();
1029 tracker.wait().await;
1030
1031 self.ephemeral_handle.abort();
1036 self.ephemeral_handle.await.ok();
1037 self.location_handle.abort();
1038 self.location_handle.await.ok();
1039 self.recently_seen_loop.abort().await;
1040 }
1041}
1042
1043#[derive(Debug)]
1045struct ConnectionState {
1046 stop_token: CancellationToken,
1048 idle_interrupt_sender: Sender<()>,
1050 connectivity: ConnectivityStore,
1052}
1053
1054impl ConnectionState {
1055 fn stop(&self) {
1057 self.stop_token.cancel();
1059 }
1060
1061 fn interrupt(&self) {
1062 self.idle_interrupt_sender.try_send(()).ok();
1064 }
1065}
1066
1067#[derive(Debug)]
1068pub(crate) struct SmtpConnectionState {
1069 state: ConnectionState,
1070}
1071
1072impl SmtpConnectionState {
1073 fn new() -> (Self, SmtpConnectionHandlers) {
1074 let stop_token = CancellationToken::new();
1075 let (idle_interrupt_sender, idle_interrupt_receiver) = channel::bounded(1);
1076
1077 let handlers = SmtpConnectionHandlers {
1078 connection: Smtp::new(),
1079 stop_token: stop_token.clone(),
1080 idle_interrupt_receiver,
1081 };
1082
1083 let state = ConnectionState {
1084 stop_token,
1085 idle_interrupt_sender,
1086 connectivity: handlers.connection.connectivity.clone(),
1087 };
1088
1089 let conn = SmtpConnectionState { state };
1090
1091 (conn, handlers)
1092 }
1093
1094 fn interrupt(&self) {
1096 self.state.interrupt();
1097 }
1098
1099 fn stop(&self) {
1101 self.state.stop();
1102 }
1103}
1104
1105struct SmtpConnectionHandlers {
1106 connection: Smtp,
1107 stop_token: CancellationToken,
1108 idle_interrupt_receiver: Receiver<()>,
1109}
1110
1111#[derive(Debug)]
1112pub(crate) struct ImapConnectionState {
1113 state: ConnectionState,
1114}
1115
1116impl ImapConnectionState {
1117 async fn new(
1119 context: &Context,
1120 transport_id: u32,
1121 login_param: ConfiguredLoginParam,
1122 ) -> Result<(Self, ImapConnectionHandlers)> {
1123 let stop_token = CancellationToken::new();
1124 let (idle_interrupt_sender, idle_interrupt_receiver) = channel::bounded(1);
1125
1126 let handlers = ImapConnectionHandlers {
1127 connection: Imap::new(context, transport_id, login_param, idle_interrupt_receiver)
1128 .await?,
1129 stop_token: stop_token.clone(),
1130 };
1131
1132 let state = ConnectionState {
1133 stop_token,
1134 idle_interrupt_sender,
1135 connectivity: handlers.connection.connectivity.clone(),
1136 };
1137
1138 let conn = ImapConnectionState { state };
1139
1140 Ok((conn, handlers))
1141 }
1142
1143 fn interrupt(&self) {
1145 self.state.interrupt();
1146 }
1147
1148 fn stop(&self) {
1150 self.state.stop();
1151 }
1152}
1153
1154#[derive(Debug)]
1155struct ImapConnectionHandlers {
1156 connection: Imap,
1157 stop_token: CancellationToken,
1158}