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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! Authentication monitoring and observability.
//!
//! Provides [`AuthEvent`] for structured event logging, [`AuthMetrics`] for
//! in-process counters, and [`OperationTimer`] for latency measurement.
use std::time::Instant;
use serde::Serialize;
use tracing::{Level, info, span, warn};
/// A structured log record for a single authentication event.
///
/// Constructed with [`AuthEvent::new`] and populated via builder methods.
/// Call [`AuthEvent::log`] to emit the record through `tracing`.
///
/// # Example
///
/// ```rust
/// use fraiseql_auth::AuthEvent;
/// let event = AuthEvent::new("login")
/// .with_user_id("user123".to_string())
/// .with_provider("google".to_string())
/// .success(42.5);
/// event.log();
/// ```
#[derive(Debug, Serialize)]
pub struct AuthEvent {
/// Name of the authentication event (e.g., `"login"`, `"token_refresh"`).
pub event: String,
/// Optional authenticated user ID associated with this event.
pub user_id: Option<String>,
/// OAuth provider name (e.g., `"google"`, `"okta"`).
pub provider: Option<String>,
/// Outcome: `"started"`, `"success"`, or `"error"`.
pub status: String,
/// Duration of the operation in milliseconds.
pub duration_ms: f64,
/// Error message if the operation failed.
pub error: Option<String>,
/// RFC 3339 timestamp of when this event was created.
pub timestamp: String,
/// Optional correlation ID for tracing a request across services.
pub request_id: Option<String>,
}
impl AuthEvent {
/// Create a new event record in the `"started"` state.
#[must_use]
pub fn new(event: &str) -> Self {
Self {
event: event.to_string(),
user_id: None,
provider: None,
status: "started".to_string(),
duration_ms: 0.0,
error: None,
timestamp: chrono::Utc::now().to_rfc3339(),
request_id: None,
}
}
/// Set the user ID associated with this event.
#[must_use]
pub fn with_user_id(mut self, user_id: String) -> Self {
self.user_id = Some(user_id);
self
}
/// Set the OAuth provider name for this event.
#[must_use]
pub fn with_provider(mut self, provider: String) -> Self {
self.provider = Some(provider);
self
}
/// Set the request correlation ID for distributed tracing.
#[must_use]
pub fn with_request_id(mut self, request_id: String) -> Self {
self.request_id = Some(request_id);
self
}
/// Mark the event as successful and record its duration.
#[must_use]
pub fn success(mut self, duration_ms: f64) -> Self {
self.status = "success".to_string();
self.duration_ms = duration_ms;
self
}
/// Mark the event as failed, recording the error and duration.
#[must_use]
pub fn error(mut self, error: String, duration_ms: f64) -> Self {
self.status = "error".to_string();
self.error = Some(error);
self.duration_ms = duration_ms;
self
}
/// Emit this event through `tracing` at the appropriate level.
///
/// Successful events are logged at `INFO`; errors at `WARN`.
/// Events in the `"started"` state are silently dropped.
pub fn log(&self) {
match self.status.as_str() {
"success" => {
info!(
event = %self.event,
user_id = ?self.user_id,
provider = ?self.provider,
duration_ms = self.duration_ms,
"Authentication event",
);
},
"error" => {
warn!(
event = %self.event,
error = ?self.error,
duration_ms = self.duration_ms,
"Authentication error",
);
},
_ => {},
}
}
}
/// In-process counters for authentication operations.
///
/// These counters are for lightweight observability within a single process.
/// For production monitoring, export these values to a metrics system such as
/// Prometheus. All fields are plain `u64`; thread-safe mutation requires an
/// outer `Mutex` or `RwLock`.
#[derive(Debug, Clone)]
pub struct AuthMetrics {
/// Total number of authentication attempts (successful + failed).
pub total_auth_attempts: u64,
/// Number of authentication attempts that succeeded.
pub successful_authentications: u64,
/// Number of authentication attempts that failed.
pub failed_authentications: u64,
/// Number of access tokens issued since startup.
pub tokens_issued: u64,
/// Number of access tokens refreshed since startup.
pub tokens_refreshed: u64,
/// Number of sessions explicitly revoked since startup.
pub sessions_revoked: u64,
}
impl AuthMetrics {
/// Create a new `AuthMetrics` with all counters initialized to zero.
#[must_use]
pub const fn new() -> Self {
Self {
total_auth_attempts: 0,
successful_authentications: 0,
failed_authentications: 0,
tokens_issued: 0,
tokens_refreshed: 0,
sessions_revoked: 0,
}
}
/// Increment the total authentication attempts counter.
pub const fn record_attempt(&mut self) {
self.total_auth_attempts += 1;
}
/// Increment the successful authentications counter.
pub const fn record_success(&mut self) {
self.successful_authentications += 1;
}
/// Increment the failed authentications counter.
pub const fn record_failure(&mut self) {
self.failed_authentications += 1;
}
/// Increment the tokens issued counter.
pub const fn record_token_issued(&mut self) {
self.tokens_issued += 1;
}
/// Increment the tokens refreshed counter.
pub const fn record_token_refreshed(&mut self) {
self.tokens_refreshed += 1;
}
/// Increment the sessions revoked counter.
pub const fn record_session_revoked(&mut self) {
self.sessions_revoked += 1;
}
/// Return the success rate as a percentage (0–100).
///
/// Returns `0.0` when no attempts have been recorded yet.
#[must_use]
pub fn success_rate(&self) -> f64 {
if self.total_auth_attempts == 0 {
0.0
} else {
#[allow(clippy::cast_precision_loss)] // Reason: acceptable precision for metrics/timing
let result = (self.successful_authentications as f64)
/ (self.total_auth_attempts as f64)
* 100.0;
result
}
}
}
impl Default for AuthMetrics {
fn default() -> Self {
Self::new()
}
}
/// A wall-clock timer for measuring the duration of authentication operations.
///
/// The timer starts immediately on construction via [`OperationTimer::start`].
/// Call [`OperationTimer::finish`] to log the elapsed time and discard the timer,
/// or read [`OperationTimer::elapsed_ms`] to sample without consuming.
pub struct OperationTimer {
start: Instant,
operation: String,
}
impl OperationTimer {
/// Start timing `operation` and open a tracing span at `DEBUG` level.
pub fn start(operation: &str) -> Self {
let span = span!(Level::DEBUG, "operation", %operation);
let _guard = span.enter();
Self {
start: Instant::now(),
operation: operation.to_string(),
}
}
/// Return the elapsed time in milliseconds since this timer was started.
#[must_use]
pub fn elapsed_ms(&self) -> f64 {
self.start.elapsed().as_secs_f64() * 1000.0
}
/// Log the completed operation at `INFO` level with its elapsed duration.
pub fn finish(self) {
let elapsed = self.elapsed_ms();
info!(
operation = %self.operation,
duration_ms = elapsed,
"Operation completed",
);
}
}