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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::time::Instant;
use crate::client::CortexClient;
use crate::error::{CortexError, CortexResult};
use crate::health::{HealthMonitor, HealthStatus};
use super::{ClientState, ConnectionEvent, ResilientClient};
impl ResilientClient {
/// Start the background health monitor.
pub(super) async fn start_health_monitor(&self) {
let client = self.client().await;
let (monitor, mut rx) = HealthMonitor::start(client, &self.config.health);
// Spawn a task to process health events
let event_tx = self.event_tx.clone();
let reconnecting = Arc::clone(&self.reconnecting);
tokio::spawn(async move {
while let Some(status) = rx.recv().await {
if let HealthStatus::Unhealthy { .. } = status {
if !reconnecting.load(Ordering::SeqCst) {
tracing::warn!("Health monitor detected unhealthy connection");
let _ = event_tx.send(ConnectionEvent::Disconnected {
reason: "Health check failures exceeded threshold".into(),
});
}
}
}
});
if let Ok(mut guard) = self.health_monitor.lock() {
*guard = Some(monitor);
}
}
/// Attempt to reconnect the client that produced a connection error.
///
/// If another operation has already replaced `failed_client`, this is a
/// stale failure: the active connection is left untouched and the caller
/// retries on that connection.
pub(super) async fn reconnect(&self, failed_client: &Arc<CortexClient>) -> CortexResult<()> {
let Some(_guard) = self.claim_reconnect(failed_client).await? else {
return Ok(());
};
let _ = self.event_tx.send(ConnectionEvent::Disconnected {
reason: "Connection lost, initiating reconnection".into(),
});
// Stop health monitor during reconnection
if let Ok(mut guard) = self.health_monitor.lock() {
if let Some(mut monitor) = guard.take() {
tokio::spawn(async move { monitor.stop().await });
}
}
let reconnect = &self.config.reconnect;
let mut delay = Duration::from_secs(reconnect.base_delay_secs);
let max_delay = Duration::from_secs(reconnect.max_delay_secs);
let max_attempts = if reconnect.max_attempts == 0 {
u32::MAX // unlimited
} else {
reconnect.max_attempts
};
for attempt in 1..=max_attempts {
let _ = self
.event_tx
.send(ConnectionEvent::Reconnecting { attempt });
tracing::info!(
attempt,
max_attempts = if reconnect.max_attempts == 0 {
"unlimited".to_string()
} else {
max_attempts.to_string()
},
"Attempting reconnection"
);
match CortexClient::connect(&self.config).await {
Ok(new_client) => {
let warning_rx = new_client.warning_receiver();
match new_client
.authenticate(&self.config.client_id, &self.config.client_secret)
.await
{
Ok(new_token) => {
if !self
.install_reconnected_client(
failed_client,
new_client,
warning_rx,
new_token,
attempt,
)
.await
{
return Ok(());
}
return Ok(());
}
Err(e) => {
tracing::warn!(
attempt,
error_category = e.category(),
api_code = ?e.api_code(),
"Connected but authentication failed"
);
// Close the failed attempt's connection instead
// of leaking its reader task/socket.
new_client.shutdown().await;
}
}
}
Err(e) => {
tracing::warn!(
attempt,
error_category = e.category(),
api_code = ?e.api_code(),
"Reconnection attempt failed"
);
}
}
if attempt < max_attempts {
let delay_ms = u64::try_from(delay.as_millis()).unwrap_or(u64::MAX);
tracing::debug!(delay_ms, "Backing off before retry");
tokio::time::sleep(delay).await;
delay = std::cmp::min(delay * 2, max_delay);
}
}
let _ = self.event_tx.send(ConnectionEvent::ReconnectFailed {
attempts: max_attempts,
last_error: "All reconnection attempts exhausted".into(),
});
Err(CortexError::RetriesExhausted {
attempts: max_attempts,
last_error: Box::new(CortexError::ConnectionLost {
reason: "All reconnection attempts exhausted".into(),
}),
})
}
/// Claim the reconnect slot only for the currently active failed client.
async fn claim_reconnect<'a>(
&'a self,
failed_client: &Arc<CortexClient>,
) -> CortexResult<Option<ReconnectGuard<'a>>> {
if !Arc::ptr_eq(&self.client().await, failed_client) {
return Ok(None);
}
if self
.reconnecting
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
while self.reconnecting.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(100)).await;
}
if self.client().await.is_connected() {
return Ok(None);
}
return Err(CortexError::ConnectionLost {
reason: "Concurrent reconnection failed".into(),
});
}
let guard = ReconnectGuard(&self.reconnecting);
if !Arc::ptr_eq(&self.client().await, failed_client) {
return Ok(None);
}
Ok(Some(guard))
}
/// Swap a freshly authenticated client into the shared state, shut down
/// the connection it replaces, and restart supporting tasks.
async fn install_reconnected_client(
&self,
failed_client: &Arc<CortexClient>,
new_client: CortexClient,
warning_rx: tokio::sync::broadcast::Receiver<crate::protocol::warnings::CortexWarning>,
new_token: String,
attempt: u32,
) -> bool {
let new_client = Arc::new(new_client);
// Install only if the failed generation is still active. This
// compare-and-swap invariant prevents a late reconnect result from
// replacing and shutting down a healthy client.
let old_client = {
let mut state = self.state.write().await;
if !Arc::ptr_eq(&state.client, failed_client) {
drop(state);
new_client.shutdown().await;
return false;
}
let old_client = Arc::clone(&state.client);
*state = ClientState {
client: Arc::clone(&new_client),
cortex_token: new_token,
token_obtained_at: Instant::now(),
};
old_client
};
Self::spawn_warning_relay(&self.warning_tx, warning_rx);
// Explicitly shut down the replaced connection — dropping the Arc
// alone would leave its reader task and socket alive until the
// server closes.
old_client.shutdown().await;
let _ = self.event_tx.send(ConnectionEvent::Reconnected);
tracing::info!(attempt, "Reconnected and re-authenticated");
if self.config.health.enabled {
self.start_health_monitor().await;
}
true
}
/// Returns whether the underlying connection is alive.
pub async fn is_connected(&self) -> bool {
self.client().await.is_connected()
}
/// Get a reference to the underlying `CortexClient` (for advanced use).
///
/// The returned `Arc` keeps the client alive even if a reconnection
/// replaces the internal client. Use with care.
pub async fn inner_client(&self) -> Arc<CortexClient> {
self.client().await
}
/// Gracefully disconnect from the Cortex service.
///
/// Stops the health monitor and drops the connection. The
/// `ResilientClient` cannot be used after this call.
///
/// # Errors
/// Returns any error produced by shutting down background health monitoring.
pub async fn disconnect(self) -> CortexResult<()> {
// Take the monitor out of the mutex, then drop the guard before awaiting
let monitor = self
.health_monitor
.lock()
.ok()
.and_then(|mut guard| guard.take());
if let Some(mut monitor) = monitor {
monitor.stop().await;
}
let _ = self.event_tx.send(ConnectionEvent::Disconnected {
reason: "Graceful disconnect".into(),
});
// Explicitly shut down the active connection. Dropping the Arc is
// not sufficient: the reader task owns clones of its state and
// would keep the socket alive until the server closes it.
let client = Arc::clone(&self.state.read().await.client);
client.shutdown().await;
Ok(())
}
}
/// Guard that resets the reconnecting flag when dropped.
struct ReconnectGuard<'a>(&'a AtomicBool);
impl Drop for ReconnectGuard<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}