Skip to content

Commit 1b90492

Browse files
committed
worker/jobs/expiry_notification: Replace TimeDelta with DateTime
We can calculate the cut-off datetime on the application side instead of relying on `.num_days().day()`, which was slightly error-prone for intervals that are not full days.
1 parent f710bfb commit 1b90492

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/worker/jobs/expiry_notification.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::{email::Email, models::User, worker::Environment, Emails};
44
use anyhow::anyhow;
55
use chrono::SecondsFormat;
66
use crates_io_worker::BackgroundJob;
7-
use diesel::dsl::{now, IntervalDsl};
7+
use diesel::dsl::now;
88
use diesel::prelude::*;
99
use std::sync::Arc;
1010

@@ -43,7 +43,8 @@ impl BackgroundJob for SendTokenExpiryNotifications {
4343
// Check if the token is about to expire and send a notification if it is.
4444
fn check(emails: &Emails, conn: &mut PgConnection) -> anyhow::Result<()> {
4545
info!("Checking if tokens are about to expire");
46-
let expired_tokens = find_tokens_expiring_within_days(conn, EXPIRY_THRESHOLD)?;
46+
let before = chrono::Utc::now() + EXPIRY_THRESHOLD;
47+
let expired_tokens = find_expiring_tokens(conn, before)?;
4748
if expired_tokens.len() == MAX_ROWS as usize {
4849
warn!("The maximum number of API tokens per query has been reached. More API tokens might be processed on the next run.");
4950
}
@@ -79,10 +80,14 @@ fn handle_expiring_token(
7980
Ok(())
8081
}
8182

82-
/// Find all tokens that are not revoked and will expire within the specified number of days.
83-
pub fn find_tokens_expiring_within_days(
83+
/// Find tokens that will expire before the given date, but haven't expired yet
84+
/// and haven't been notified about their impending expiry. Revoked tokens are
85+
/// also ignored.
86+
///
87+
/// This function returns at most `MAX_ROWS` tokens.
88+
pub fn find_expiring_tokens(
8489
conn: &mut PgConnection,
85-
days_until_expiry: chrono::TimeDelta,
90+
before: chrono::DateTime<chrono::Utc>,
8691
) -> QueryResult<Vec<ApiToken>> {
8792
api_tokens::table
8893
.filter(api_tokens::revoked.eq(false))
@@ -92,7 +97,7 @@ pub fn find_tokens_expiring_within_days(
9297
.filter(
9398
api_tokens::expired_at
9499
.assume_not_null()
95-
.lt(now + days_until_expiry.num_days().day()),
100+
.lt(before.naive_utc()),
96101
)
97102
.filter(api_tokens::expiry_notification_at.is_null())
98103
.select(ApiToken::as_select())

0 commit comments

Comments
 (0)