@@ -37,18 +37,33 @@ impl BackgroundJob for SendTokenExpiryNotifications {
37
37
38
38
/// Find tokens that are about to expire and send notifications to their owners.
39
39
fn check ( emails : & Emails , conn : & mut PgConnection ) -> anyhow:: Result < ( ) > {
40
- info ! ( "Checking if tokens are about to expire" ) ;
41
40
let before = chrono:: Utc :: now ( ) + EXPIRY_THRESHOLD ;
41
+ info ! ( "Searching for tokens that will expire before {before}…" ) ;
42
+
42
43
let expired_tokens = find_expiring_tokens ( conn, before) ?;
43
- if expired_tokens. len ( ) == MAX_ROWS as usize {
44
+ let num_tokens = expired_tokens. len ( ) ;
45
+ if num_tokens == 0 {
46
+ info ! ( "Found no tokens that will expire before {before}. Skipping expiry notifications." ) ;
47
+ return Ok ( ( ) ) ;
48
+ }
49
+
50
+ info ! ( "Found {num_tokens} tokens that will expire before {before}. Sending out expiry notifications…" ) ;
51
+
52
+ if num_tokens == MAX_ROWS as usize {
44
53
warn ! ( "The maximum number of API tokens per query has been reached. More API tokens might be processed on the next run." ) ;
45
54
}
55
+
56
+ let mut success = 0 ;
46
57
for token in & expired_tokens {
47
58
if let Err ( e) = handle_expiring_token ( conn, token, emails) {
48
59
error ! ( ?e, "Failed to handle expiring token" ) ;
60
+ } else {
61
+ success += 1 ;
49
62
}
50
63
}
51
64
65
+ info ! ( "Sent expiry notifications for {success} of {num_tokens} expiring tokens." ) ;
66
+
52
67
Ok ( ( ) )
53
68
}
54
69
@@ -58,20 +73,28 @@ fn handle_expiring_token(
58
73
token : & ApiToken ,
59
74
emails : & Emails ,
60
75
) -> Result < ( ) , anyhow:: Error > {
76
+ debug ! ( "Looking up user {} for token {}…" , token. user_id, token. id) ;
61
77
let user = User :: find ( conn, token. user_id ) ?;
78
+
79
+ debug ! ( "Looking up email address for user {}…" , user. id) ;
62
80
let recipient = user
63
81
. email ( conn) ?
64
82
. ok_or_else ( || anyhow ! ( "No address found" ) ) ?;
83
+
84
+ debug ! ( "Sending expiry notification to {}…" , recipient) ;
65
85
let email = ExpiryNotificationEmail {
66
86
name : & user. gh_login ,
67
87
token_name : & token. name ,
68
88
expiry_date : token. expired_at . unwrap ( ) . and_utc ( ) ,
69
89
} ;
70
90
emails. send ( & recipient, email) ?;
91
+
71
92
// Update the token to prevent duplicate notifications.
93
+ debug ! ( "Marking token {} as notified…" , token. id) ;
72
94
diesel:: update ( token)
73
95
. set ( api_tokens:: expiry_notification_at. eq ( now. nullable ( ) ) )
74
96
. execute ( conn) ?;
97
+
75
98
Ok ( ( ) )
76
99
}
77
100
0 commit comments