1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
use std::time::Duration;

use anyhow::{bail, Context as _, Result};
use async_channel::Receiver;
use async_imap::extensions::idle::IdleResponse;
use futures_lite::FutureExt;
use tokio::time::timeout;

use super::session::Session;
use super::Imap;
use crate::context::Context;
use crate::net::TIMEOUT;
use crate::tools::{self, time_elapsed};

/// Timeout after which IDLE is finished
/// if there are no responses from the server.
///
/// If `* OK Still here` keepalives are sent more frequently
/// than this duration, timeout should never be triggered.
/// For example, Dovecot sends keepalives every 2 minutes by default.
const IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);

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

        self.select_with_uidvalidity(context, folder).await?;

        if self.drain_unsolicited_responses(context)? {
            self.new_mail = true;
        }

        if self.new_mail {
            return Ok(self);
        }

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

        let mut handle = self.inner.idle();
        if let Err(err) = handle.init().await {
            bail!("IMAP IDLE protocol failed to init/complete: {}", err);
        }

        // At this point IDLE command was sent and we received a "+ idling" response. We will now
        // read from the stream without getting any data for up to `IDLE_TIMEOUT`. If we don't
        // disable read timeout, we would get a timeout after `crate::net::TIMEOUT`, which is a lot
        // shorter than `IDLE_TIMEOUT`.
        handle.as_mut().set_read_timeout(None);
        let (idle_wait, interrupt) = handle.wait_with_timeout(IDLE_TIMEOUT);

        enum Event {
            IdleResponse(IdleResponse),
            Interrupt,
        }

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

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

            Ok(Event::Interrupt)
        });

        match fut.await {
            Ok(Event::IdleResponse(IdleResponse::NewData(x))) => {
                info!(context, "{folder}: Idle has NewData {:?}", x);
            }
            Ok(Event::IdleResponse(IdleResponse::Timeout)) => {
                info!(context, "{folder}: Idle-wait timeout or interruption");
            }
            Ok(Event::IdleResponse(IdleResponse::ManualInterrupt)) => {
                info!(context, "{folder}: Idle wait was interrupted manually");
            }
            Ok(Event::Interrupt) => {
                info!(context, "{folder}: Idle wait was interrupted");
            }
            Err(err) => {
                warn!(context, "{folder}: Idle wait errored: {err:?}");
            }
        }

        let mut session = tokio::time::timeout(Duration::from_secs(15), handle.done())
            .await
            .with_context(|| format!("{folder}: IMAP IDLE protocol timed out"))?
            .with_context(|| format!("{folder}: IMAP IDLE failed"))?;
        session.as_mut().set_read_timeout(Some(TIMEOUT));
        self.inner = session;

        // Fetch mail once we exit IDLE.
        self.new_mail = true;

        Ok(self)
    }
}

impl Imap {
    /// Idle using polling.
    pub(crate) async fn fake_idle(
        &mut self,
        context: &Context,
        watch_folder: String,
    ) -> Result<()> {
        let fake_idle_start_time = tools::Time::now();

        info!(context, "IMAP-fake-IDLEing folder={:?}", watch_folder);

        // Wait for 60 seconds or until we are interrupted.
        match timeout(Duration::from_secs(60), self.idle_interrupt_receiver.recv()).await {
            Err(_) => info!(context, "Fake IDLE finished."),
            Ok(_) => info!(context, "Fake IDLE interrupted."),
        }

        info!(
            context,
            "IMAP-fake-IDLE done after {:.4}s",
            time_elapsed(&fake_idle_start_time).as_millis() as f64 / 1000.,
        );
        Ok(())
    }
}