saluki_components/common/datadog/
retry.rs1use std::{
2 path::{Path, PathBuf},
3 sync::{
4 atomic::{AtomicBool, Ordering},
5 Arc,
6 },
7 time::Duration,
8};
9
10use http::{Response, StatusCode};
11use saluki_common::sync::live::Live;
12use saluki_core::runtime::{self, ShutdownStrategy};
13use saluki_io::net::util::retry::{
14 ExponentialBackoff, RetryCauseTelemetry, RetryClassifier, RollingExponentialBackoffRetryPolicy,
15 StandardHttpClassifier, StandardHttpRetryLifecycle,
16};
17use tracing::debug;
18
19const RETRY_TXN_DIR: &str = "transactions_to_retry";
20const RETRY_QUEUE_CAPACITY_MIN_HISTORY_DURATION_SECS: u64 = 10;
21
22pub(crate) type SecretsHttpRetryPolicy<B = ()> =
23 RollingExponentialBackoffRetryPolicy<SecretsHttpClassifier<B>, StandardHttpRetryLifecycle>;
24
25#[derive(Clone)]
31pub(crate) struct SecretsGate {
32 in_use: Arc<AtomicBool>,
33}
34
35impl SecretsGate {
36 pub(crate) fn new_fixed(secrets_in_use: bool) -> Self {
38 Self {
39 in_use: Arc::new(AtomicBool::new(secrets_in_use)),
40 }
41 }
42
43 fn store(&self, secrets_in_use: bool) {
44 self.in_use.store(secrets_in_use, Ordering::Relaxed);
45 }
46
47 fn is_open(&self) -> bool {
48 self.in_use.load(Ordering::Relaxed)
49 }
50}
51
52pub(crate) struct SecretsGateRefresher {
54 secrets_in_use: Live<bool>,
55
56 pub(crate) gate: SecretsGate,
58}
59
60impl SecretsGateRefresher {
61 pub(crate) fn new(secrets_in_use: Live<bool>) -> Self {
67 let gate = SecretsGate::new_fixed(*secrets_in_use);
68
69 Self { secrets_in_use, gate }
70 }
71
72 pub(crate) fn spawn(self) {
82 let Self { secrets_in_use, gate } = self;
83
84 runtime::worker("secrets_gate_refresher", follow_secrets(secrets_in_use, gate))
85 .with_shutdown_strategy(ShutdownStrategy::Brutal)
86 .spawn();
87 }
88}
89
90async fn follow_secrets(mut secrets_in_use: Live<bool>, gate: SecretsGate) {
92 loop {
93 let in_use = secrets_in_use.changed().await;
94 gate.store(in_use);
95 }
96}
97
98pub(crate) struct SecretsHttpClassifier<B = ()> {
99 standard: StandardHttpClassifier<B>,
100 secrets: SecretsGate,
101}
102
103impl<B> Clone for SecretsHttpClassifier<B> {
104 fn clone(&self) -> Self {
105 Self {
106 standard: self.standard.clone(),
107 secrets: self.secrets.clone(),
108 }
109 }
110}
111
112impl<B, Error> RetryClassifier<Response<B>, Error> for SecretsHttpClassifier<B> {
113 fn should_retry(&self, response: &Result<Response<B>, Error>) -> bool {
114 if let Ok(response) = response {
115 if response.status() == StatusCode::FORBIDDEN && self.secrets.is_open() {
116 return true;
117 }
118 }
119
120 self.standard.should_retry(response)
121 }
122}
123
124#[derive(Clone)]
126#[cfg_attr(test, derive(Debug, PartialEq))]
127pub struct RetryConfiguration {
128 pub backoff_factor: f64,
134
135 pub backoff_base: f64,
137
138 pub backoff_max: f64,
140
141 pub recovery_error_decrease_factor: u32,
146
147 pub recovery_reset: bool,
149
150 pub queue_max_size_bytes: u64,
152
153 pub storage_max_size_bytes: u64,
157
158 pub flush_to_disk_mem_ratio: f64,
165
166 pub storage_path: PathBuf,
170
171 pub run_path: Option<PathBuf>,
175
176 pub storage_max_disk_ratio: f64,
182
183 pub outdated_file_in_days: u32,
190
191 pub capacity_time_interval_secs: u64,
197}
198
199impl RetryConfiguration {
200 pub(crate) fn resolved_storage_path(&self) -> PathBuf {
205 resolve_storage_path(&self.storage_path, self.run_path.as_deref())
206 }
207
208 pub(crate) fn effective_capacity_time_interval_secs(&self) -> u64 {
210 self.capacity_time_interval_secs
211 .max(RETRY_QUEUE_CAPACITY_MIN_HISTORY_DURATION_SECS)
212 }
213
214 pub(crate) fn to_default_http_retry_policy<B: 'static>(
223 &self, secrets: SecretsGate, retry_causes: RetryCauseTelemetry,
224 ) -> SecretsHttpRetryPolicy<B> {
225 let retry_backoff = ExponentialBackoff::with_jitter(
226 Duration::from_secs_f64(self.backoff_base),
227 Duration::from_secs_f64(self.backoff_max),
228 self.backoff_factor,
229 );
230 let classifier = SecretsHttpClassifier {
231 standard: StandardHttpClassifier::new(),
232 secrets,
233 };
234
235 let recovery_error_decrease_factor = (!self.recovery_reset).then_some(self.recovery_error_decrease_factor);
236 RollingExponentialBackoffRetryPolicy::new(classifier, retry_backoff)
237 .with_retry_lifecycle(StandardHttpRetryLifecycle::new().with_telemetry(retry_causes))
238 .with_recovery_error_decrease_factor(recovery_error_decrease_factor)
239 }
240}
241
242fn resolve_storage_path(configured: &Path, run_path: Option<&Path>) -> PathBuf {
247 if configured.parent().is_some() {
248 return configured.to_path_buf();
249 }
250
251 match run_path {
252 Some(run_path) => run_path.join(RETRY_TXN_DIR),
253 None => {
254 debug!("`forwarder_storage_path` and `run_path` were empty. Cannot calculate default storage path for forwarder.");
255 PathBuf::new()
256 }
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use http::{Request, Response};
263 use metrics::{Key, Label};
264 use saluki_core::runtime::test_util::TestSupervisor;
265 use saluki_metrics::{test::TestRecorder, MetricsBuilder};
266 use tower::retry::Policy;
267
268 use super::*;
269 use crate::common::datadog::test_util::{retry_configuration, LiveConfiguration, LiveRoot};
270
271 type BoxError = Box<dyn std::error::Error + Send + Sync>;
272 type TestRequest = Request<()>;
273 type TestResponse = Result<Response<()>, BoxError>;
274
275 const RUN_PATH: &str = "/my/little/run_path";
276
277 fn ok_response(status: StatusCode) -> TestResponse {
278 Ok(Response::builder().status(status).body(()).unwrap())
279 }
280
281 fn test_request() -> TestRequest {
282 Request::builder()
283 .method("POST")
284 .uri("http://localhost/intake")
285 .body(())
286 .unwrap()
287 }
288
289 fn would_retry(policy: &mut SecretsHttpRetryPolicy, mut response: TestResponse) -> bool {
290 let mut request = test_request();
291 Policy::<TestRequest, Response<()>, BoxError>::retry(policy, &mut request, &mut response).is_some()
292 }
293
294 fn test_retry_config() -> RetryConfiguration {
295 RetryConfiguration {
297 backoff_base: 0.001,
298 backoff_max: 0.01,
299 backoff_factor: 2.0,
300 ..retry_configuration()
301 }
302 }
303
304 fn test_retry_causes() -> RetryCauseTelemetry {
305 RetryCauseTelemetry::from_builder(&MetricsBuilder::default(), "http://localhost")
306 }
307
308 #[test]
309 fn storage_path_is_derived_from_run_path_when_not_configured() {
310 let retry_config = RetryConfiguration {
311 storage_path: PathBuf::new(),
312 run_path: Some(PathBuf::from(RUN_PATH)),
313 ..retry_configuration()
314 };
315
316 assert_eq!(
317 Path::new(RUN_PATH).join(RETRY_TXN_DIR),
318 retry_config.resolved_storage_path()
319 );
320 }
321
322 #[test]
323 fn a_configured_storage_path_wins_over_run_path() {
324 const FORWARDER_STORAGE_PATH: &str = "/custom/path/to/storage";
325
326 let retry_config = RetryConfiguration {
327 storage_path: PathBuf::from(FORWARDER_STORAGE_PATH),
328 run_path: Some(PathBuf::from(RUN_PATH)),
329 ..retry_configuration()
330 };
331
332 assert_eq!(
333 PathBuf::from(FORWARDER_STORAGE_PATH),
334 retry_config.resolved_storage_path()
335 );
336 }
337
338 #[test]
339 fn there_is_no_storage_path_without_a_run_path() {
340 let retry_config = RetryConfiguration {
342 storage_path: PathBuf::new(),
343 run_path: None,
344 ..retry_configuration()
345 };
346
347 assert_eq!(PathBuf::new(), retry_config.resolved_storage_path());
348 }
349
350 #[test]
351 fn capacity_time_interval_secs_is_clamped_to_the_bucket_size() {
352 let cases = [
353 (900, 900),
354 (60, 60),
355 (1, RETRY_QUEUE_CAPACITY_MIN_HISTORY_DURATION_SECS),
356 ];
357
358 for (configured, expected) in cases {
359 let retry_config = RetryConfiguration {
360 capacity_time_interval_secs: configured,
361 ..retry_configuration()
362 };
363
364 assert_eq!(
365 expected,
366 retry_config.effective_capacity_time_interval_secs(),
367 "{configured}"
368 );
369 }
370 }
371
372 #[test]
373 fn policy_without_secrets_management_configured_does_not_retry_403() {
374 let retry_config = test_retry_config();
375 let mut policy = retry_config.to_default_http_retry_policy(SecretsGate::new_fixed(false), test_retry_causes());
376
377 assert!(!would_retry(&mut policy, ok_response(StatusCode::FORBIDDEN)));
378 }
379
380 #[tokio::test]
381 async fn retry_policy_counts_the_cause_when_it_retries() {
382 let recorder = TestRecorder::default();
384 let builder = MetricsBuilder::default();
385 let retry_causes = RetryCauseTelemetry::from_builder(&builder, "https://example.com");
386 let retry_config = test_retry_config();
387 let mut policy = retry_config.to_default_http_retry_policy(SecretsGate::new_fixed(false), retry_causes);
388
389 let retried = metrics::with_local_recorder(&recorder, || {
390 would_retry(&mut policy, ok_response(StatusCode::SERVICE_UNAVAILABLE))
391 });
392
393 assert!(retried);
394 let key = Key::from_parts(
395 "network_http_requests_retry_causes_total",
396 vec![
397 Label::new("domain", "https://example.com"),
398 Label::new("cause", "http_status"),
399 ],
400 );
401 assert_eq!(recorder.counter(key), Some(1));
402 }
403
404 #[tokio::test]
405 async fn policy_with_secrets_management_retries_403() {
406 let retry_config = test_retry_config();
407 let mut policy = retry_config.to_default_http_retry_policy(SecretsGate::new_fixed(true), test_retry_causes());
408
409 assert!(would_retry(&mut policy, ok_response(StatusCode::FORBIDDEN)));
410 }
411
412 #[tokio::test]
413 async fn the_secrets_gate_does_not_affect_other_status_codes() {
414 let retry_config = test_retry_config();
415 let mut policy = retry_config.to_default_http_retry_policy(SecretsGate::new_fixed(true), test_retry_causes());
416
417 assert!(!would_retry(&mut policy, ok_response(StatusCode::OK)));
418 assert!(!would_retry(&mut policy, ok_response(StatusCode::BAD_REQUEST)));
419 assert!(!would_retry(&mut policy, ok_response(StatusCode::UNAUTHORIZED)));
420 assert!(!would_retry(&mut policy, ok_response(StatusCode::PAYLOAD_TOO_LARGE)));
421 assert!(would_retry(&mut policy, ok_response(StatusCode::INTERNAL_SERVER_ERROR)));
422 assert!(would_retry(&mut policy, ok_response(StatusCode::TOO_MANY_REQUESTS)));
423 }
424
425 #[tokio::test]
426 async fn the_403_gate_follows_a_secrets_configuration_change() {
427 let mut live_config = LiveConfiguration::new(LiveRoot::default());
428 let refresher = SecretsGateRefresher::new(live_config.source.live(|root| &root.secrets_in_use));
429 let gate = refresher.gate.clone();
430
431 let supervisor = TestSupervisor::start("test_forwarder").await;
434 supervisor.scope(async move { refresher.spawn() }).await;
435
436 let retry_config = test_retry_config();
437 let mut policy = retry_config.to_default_http_retry_policy(gate.clone(), test_retry_causes());
438
439 assert!(!would_retry(&mut policy, ok_response(StatusCode::FORBIDDEN)));
441
442 live_config.publisher.publish(LiveRoot {
445 secrets_in_use: true,
446 ..LiveRoot::default()
447 });
448 await_gate(&gate, true).await;
449 assert!(would_retry(&mut policy, ok_response(StatusCode::FORBIDDEN)));
450
451 live_config.publisher.publish(LiveRoot::default());
452 await_gate(&gate, false).await;
453 assert!(!would_retry(&mut policy, ok_response(StatusCode::FORBIDDEN)));
454 }
455
456 async fn await_gate(gate: &SecretsGate, expected: bool) {
458 let observed = tokio::time::timeout(Duration::from_secs(2), async {
459 while gate.is_open() != expected {
460 tokio::task::yield_now().await;
461 }
462 })
463 .await;
464
465 assert!(observed.is_ok(), "the gate should report {expected}");
466 }
467}