Skip to content

Commit add2c9d

Browse files
committed
fix: Use SystemTime instead of Instant everywhere
If a time value doesn't need to be sent to another host, saved to the db or otherwise used across program restarts, a monotonically nondecreasing clock (`Instant`) should be used. But as `Instant` may use `libc::clock_gettime(CLOCK_MONOTONIC)`, e.g. on Android, and does not advance while being in deep sleep mode, get rid of `Instant` in favor of using `SystemTime`, but add `tools::Time` as an alias for it with the appropriate comment so that it's clear why `Instant` isn't used in those places and to protect from unwanted usages of `Instant` in the future. Also this can help to switch to another clock impl if we find any.
1 parent 55cdbdc commit add2c9d

File tree

9 files changed

+49
-41
lines changed

9 files changed

+49
-41
lines changed

src/context.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::ops::Deref;
66
use std::path::{Path, PathBuf};
77
use std::sync::atomic::{AtomicBool, Ordering};
88
use std::sync::Arc;
9-
use std::time::{Duration, Instant, SystemTime};
9+
use std::time::Duration;
1010

1111
use anyhow::{bail, ensure, Context as _, Result};
1212
use async_channel::{self as channel, Receiver, Sender};
@@ -27,7 +27,7 @@ use crate::scheduler::SchedulerState;
2727
use crate::sql::Sql;
2828
use crate::stock_str::StockStrings;
2929
use crate::timesmearing::SmearedTimestamp;
30-
use crate::tools::{duration_to_str, time};
30+
use crate::tools::{self, duration_to_str, time, time_elapsed};
3131

3232
/// Builder for the [`Context`].
3333
///
@@ -224,15 +224,15 @@ pub struct InnerContext {
224224
/// <https://datatracker.ietf.org/doc/html/rfc2971>
225225
pub(crate) server_id: RwLock<Option<HashMap<String, String>>>,
226226

227-
pub(crate) last_full_folder_scan: Mutex<Option<Instant>>,
227+
pub(crate) last_full_folder_scan: Mutex<Option<tools::Time>>,
228228

229229
/// ID for this `Context` in the current process.
230230
///
231231
/// This allows for multiple `Context`s open in a single process where each context can
232232
/// be identified by this ID.
233233
pub(crate) id: u32,
234234

235-
creation_time: SystemTime,
235+
creation_time: tools::Time,
236236

237237
/// The text of the last error logged and emitted as an event.
238238
/// If the ui wants to display an error after a failure,
@@ -253,7 +253,7 @@ enum RunningState {
253253
Running { cancel_sender: Sender<()> },
254254

255255
/// Cancel signal has been sent, waiting for ongoing process to be freed.
256-
ShallStop { request: Instant },
256+
ShallStop { request: tools::Time },
257257

258258
/// There is no ongoing process, a new one can be allocated.
259259
Stopped,
@@ -384,7 +384,7 @@ impl Context {
384384
resync_request: AtomicBool::new(false),
385385
new_msgs_notify,
386386
server_id: RwLock::new(None),
387-
creation_time: std::time::SystemTime::now(),
387+
creation_time: tools::Time::now(),
388388
last_full_folder_scan: Mutex::new(None),
389389
last_error: std::sync::RwLock::new("".to_string()),
390390
debug_logging: std::sync::RwLock::new(None),
@@ -532,7 +532,7 @@ impl Context {
532532
pub(crate) async fn free_ongoing(&self) {
533533
let mut s = self.running_state.write().await;
534534
if let RunningState::ShallStop { request } = *s {
535-
info!(self, "Ongoing stopped in {:?}", request.elapsed());
535+
info!(self, "Ongoing stopped in {:?}", time_elapsed(&request));
536536
}
537537
*s = RunningState::Stopped;
538538
}
@@ -547,7 +547,7 @@ impl Context {
547547
}
548548
info!(self, "Signaling the ongoing process to stop ASAP.",);
549549
*s = RunningState::ShallStop {
550-
request: Instant::now(),
550+
request: tools::Time::now(),
551551
};
552552
}
553553
RunningState::ShallStop { .. } | RunningState::Stopped => {
@@ -789,8 +789,8 @@ impl Context {
789789
.to_string(),
790790
);
791791

792-
let elapsed = self.creation_time.elapsed();
793-
res.insert("uptime", duration_to_str(elapsed.unwrap_or_default()));
792+
let elapsed = time_elapsed(&self.creation_time);
793+
res.insert("uptime", duration_to_str(elapsed));
794794

795795
Ok(res)
796796
}
@@ -1051,7 +1051,7 @@ pub fn get_version_str() -> &'static str {
10511051

10521052
#[cfg(test)]
10531053
mod tests {
1054-
use std::time::Duration;
1054+
use std::time::{Duration, SystemTime};
10551055

10561056
use anyhow::Context as _;
10571057
use strum::IntoEnumIterator;

src/imap/idle.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::time::{Duration, SystemTime};
1+
use std::time::Duration;
22

33
use anyhow::{bail, Context as _, Result};
44
use async_channel::Receiver;
@@ -11,6 +11,7 @@ use crate::config::Config;
1111
use crate::context::Context;
1212
use crate::imap::{client::IMAP_TIMEOUT, FolderMeaning};
1313
use crate::log::LogExt;
14+
use crate::tools::{self, time_elapsed};
1415

1516
/// Timeout after which IDLE is finished
1617
/// if there are no responses from the server.
@@ -106,7 +107,7 @@ impl Imap {
106107
// Idle using polling. This is also needed if we're not yet configured -
107108
// in this case, we're waiting for a configure job (and an interrupt).
108109

109-
let fake_idle_start_time = SystemTime::now();
110+
let fake_idle_start_time = tools::Time::now();
110111

111112
// Do not poll, just wait for an interrupt when no folder is passed in.
112113
let watch_folder = if let Some(watch_folder) = watch_folder {
@@ -196,11 +197,7 @@ impl Imap {
196197
info!(
197198
context,
198199
"IMAP-fake-IDLE done after {:.4}s",
199-
SystemTime::now()
200-
.duration_since(fake_idle_start_time)
201-
.unwrap_or_default()
202-
.as_millis() as f64
203-
/ 1000.,
200+
time_elapsed(&fake_idle_start_time).as_millis() as f64 / 1000.,
204201
);
205202
}
206203
}

src/imap/scan_folders.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{collections::BTreeMap, time::Instant};
1+
use std::collections::BTreeMap;
22

33
use anyhow::{Context as _, Result};
44
use futures::stream::StreamExt;
@@ -7,6 +7,7 @@ use super::{get_folder_meaning_by_attrs, get_folder_meaning_by_name};
77
use crate::config::Config;
88
use crate::imap::Imap;
99
use crate::log::LogExt;
10+
use crate::tools::{self, time_elapsed};
1011
use crate::{context::Context, imap::FolderMeaning};
1112

1213
impl Imap {
@@ -15,7 +16,7 @@ impl Imap {
1516
// First of all, debounce to once per minute:
1617
let mut last_scan = context.last_full_folder_scan.lock().await;
1718
if let Some(last_scan) = *last_scan {
18-
let elapsed_secs = last_scan.elapsed().as_secs();
19+
let elapsed_secs = time_elapsed(&last_scan).as_secs();
1920
let debounce_secs = context
2021
.get_config_u64(Config::ScanAllFoldersDebounceSecs)
2122
.await?;
@@ -93,7 +94,7 @@ impl Imap {
9394
.await?;
9495
}
9596

96-
last_scan.replace(Instant::now());
97+
last_scan.replace(tools::Time::now());
9798
Ok(true)
9899
}
99100

src/key.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::constants::KeyGenType;
1818
use crate::context::Context;
1919
use crate::log::LogExt;
2020
use crate::pgp::KeyPair;
21-
use crate::tools::EmailAddress;
21+
use crate::tools::{self, time_elapsed, EmailAddress};
2222

2323
/// Convenience trait for working with keys.
2424
///
@@ -204,7 +204,7 @@ async fn generate_keypair(context: &Context) -> Result<KeyPair> {
204204
match load_keypair(context, &addr).await? {
205205
Some(key_pair) => Ok(key_pair),
206206
None => {
207-
let start = std::time::SystemTime::now();
207+
let start = tools::Time::now();
208208
let keytype = KeyGenType::from_i32(context.get_config_int(Config::KeyGenType).await?)
209209
.unwrap_or_default();
210210
info!(context, "Generating keypair with type {}", keytype);
@@ -216,7 +216,7 @@ async fn generate_keypair(context: &Context) -> Result<KeyPair> {
216216
info!(
217217
context,
218218
"Keypair generated in {:.3}s.",
219-
start.elapsed().unwrap_or_default().as_secs()
219+
time_elapsed(&start).as_secs(),
220220
);
221221
Ok(keypair)
222222
}

src/quota.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::imap::scan_folders::get_watched_folders;
1212
use crate::imap::session::Session as ImapSession;
1313
use crate::imap::Imap;
1414
use crate::message::{Message, Viewtype};
15-
use crate::tools::time;
15+
use crate::tools;
1616
use crate::{stock_str, EventType};
1717

1818
/// warn about a nearly full mailbox after this usage percentage is reached.
@@ -40,8 +40,8 @@ pub struct QuotaInfo {
4040
/// set to `Ok()` for valid quota information.
4141
pub(crate) recent: Result<BTreeMap<String, Vec<QuotaResource>>>,
4242

43-
/// Timestamp when structure was modified.
44-
pub(crate) modified: i64,
43+
/// When the structure was modified.
44+
pub(crate) modified: tools::Time,
4545
}
4646

4747
async fn get_unique_quota_roots_and_usage(
@@ -147,7 +147,7 @@ impl Context {
147147

148148
*self.quota.write().await = Some(QuotaInfo {
149149
recent: quota,
150-
modified: time(),
150+
modified: tools::Time::now(),
151151
});
152152

153153
self.emit_event(EventType::ConnectivityChanged);

src/scheduler.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::cmp;
22
use std::iter::{self, once};
33
use std::num::NonZeroUsize;
44
use std::sync::atomic::Ordering;
5+
use std::time::Duration;
56

67
use anyhow::{bail, Context as _, Error, Result};
78
use async_channel::{self as channel, Receiver, Sender};
@@ -24,7 +25,7 @@ use crate::log::LogExt;
2425
use crate::message::MsgId;
2526
use crate::smtp::{send_smtp_messages, Smtp};
2627
use crate::sql;
27-
use crate::tools::{duration_to_str, maybe_add_time_based_warnings, time};
28+
use crate::tools::{self, duration_to_str, maybe_add_time_based_warnings, time, time_elapsed};
2829

2930
pub(crate) mod connectivity;
3031

@@ -384,7 +385,7 @@ async fn inbox_loop(
384385
let quota = ctx.quota.read().await;
385386
quota
386387
.as_ref()
387-
.filter(|quota| quota.modified + 60 > time())
388+
.filter(|quota| time_elapsed(&quota.modified) > Duration::from_secs(60))
388389
.is_none()
389390
};
390391

@@ -736,7 +737,7 @@ async fn smtp_loop(
736737
// again, we increase the timeout exponentially, in order not to do lots of
737738
// unnecessary retries.
738739
if let Some(t) = timeout {
739-
let now = tokio::time::Instant::now();
740+
let now = tools::Time::now();
740741
info!(
741742
ctx,
742743
"smtp has messages to retry, planning to retry {} seconds later", t,
@@ -747,7 +748,7 @@ async fn smtp_loop(
747748
})
748749
.await
749750
.unwrap_or_default();
750-
let slept = (tokio::time::Instant::now() - now).as_secs();
751+
let slept = time_elapsed(&now).as_secs();
751752
timeout = Some(cmp::max(
752753
t,
753754
slept.saturating_add(rand::thread_rng().gen_range((slept / 2)..=slept)),

src/smtp.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
pub mod send;
44

5-
use std::time::{Duration, SystemTime};
5+
use std::time::Duration;
66

77
use anyhow::{bail, format_err, Context as _, Error, Result};
88
use async_smtp::response::{Category, Code, Detail};
@@ -26,6 +26,7 @@ use crate::provider::Socket;
2626
use crate::scheduler::connectivity::ConnectivityStore;
2727
use crate::socks::Socks5Config;
2828
use crate::sql;
29+
use crate::tools::{self, time_elapsed};
2930

3031
/// SMTP connection, write and read timeout.
3132
const SMTP_TIMEOUT: Duration = Duration::from_secs(60);
@@ -41,7 +42,7 @@ pub(crate) struct Smtp {
4142
/// Timestamp of last successful send/receive network interaction
4243
/// (eg connect or send succeeded). On initialization and disconnect
4344
/// it is set to None.
44-
last_success: Option<SystemTime>,
45+
last_success: Option<tools::Time>,
4546

4647
pub(crate) connectivity: ConnectivityStore,
4748

@@ -70,11 +71,7 @@ impl Smtp {
7071
/// have been successfully used the last 60 seconds
7172
pub fn has_maybe_stale_connection(&self) -> bool {
7273
if let Some(last_success) = self.last_success {
73-
SystemTime::now()
74-
.duration_since(last_success)
75-
.unwrap_or_default()
76-
.as_secs()
77-
> 60
74+
time_elapsed(&last_success).as_secs() > 60
7875
} else {
7976
false
8077
}
@@ -334,7 +331,7 @@ impl Smtp {
334331
}
335332

336333
self.transport = Some(transport);
337-
self.last_success = Some(SystemTime::now());
334+
self.last_success = Some(tools::Time::now());
338335

339336
context.emit_event(EventType::SmtpConnected(format!(
340337
"SMTP-LOGIN as {} ok",

src/smtp/send.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use super::Smtp;
66
use crate::config::Config;
77
use crate::context::Context;
88
use crate::events::EventType;
9+
use crate::tools;
910

1011
pub type Result<T> = std::result::Result<T, Error>;
1112

@@ -69,7 +70,7 @@ impl Smtp {
6970
);
7071
info!(context, "{info_msg}.");
7172
context.emit_event(EventType::SmtpMessageSent(info_msg));
72-
self.last_success = Some(std::time::SystemTime::now());
73+
self.last_success = Some(tools::Time::now());
7374
} else {
7475
warn!(
7576
context,

src/tools.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@ use std::io::{Cursor, Write};
99
use std::mem;
1010
use std::path::{Path, PathBuf};
1111
use std::str::from_utf8;
12+
// If a time value doesn't need to be sent to another host, saved to the db or otherwise used across
13+
// program restarts, a monotonically nondecreasing clock (`Instant`) should be used. But as
14+
// `Instant` may use `libc::clock_gettime(CLOCK_MONOTONIC)`, e.g. on Android, and does not advance
15+
// while being in deep sleep mode, we use `SystemTime` instead, but add an alias for it to document
16+
// why `Instant` isn't used in those places. Also this can help to switch to another clock impl if
17+
// we find any.
18+
pub use std::time::SystemTime as Time;
1219
use std::time::{Duration, SystemTime};
1320

1421
use anyhow::{bail, Context as _, Result};
@@ -482,6 +489,10 @@ pub(crate) fn time() -> i64 {
482489
.as_secs() as i64
483490
}
484491

492+
pub(crate) fn time_elapsed(time: &Time) -> Duration {
493+
time.elapsed().unwrap_or_default()
494+
}
495+
485496
/// Struct containing all mailto information
486497
#[derive(Debug, Default, Eq, PartialEq)]
487498
pub struct MailTo {

0 commit comments

Comments
 (0)