Skip to main content

saluki_components/common/datadog/
retry.rs

1use 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/// Whether secret resolution might replace a rejected API key.
26///
27/// The retry classifier reads this on every `403 Forbidden` response, and a [`SecretsGateRefresher`]
28/// writes it when configuration changes. Cloning shares the gate, so every endpoint's classifier
29/// follows the same setting.
30#[derive(Clone)]
31pub(crate) struct SecretsGate {
32    in_use: Arc<AtomicBool>,
33}
34
35impl SecretsGate {
36    /// Creates a gate reporting `secrets_in_use`, which nothing updates.
37    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
52/// Updates a [`SecretsGate`] when configuration changes.
53pub(crate) struct SecretsGateRefresher {
54    secrets_in_use: Live<bool>,
55
56    /// The gate the classifiers read. Clone it before spawning.
57    pub(crate) gate: SecretsGate,
58}
59
60impl SecretsGateRefresher {
61    /// Creates a refresher whose gate reports what `secrets_in_use` holds now.
62    ///
63    /// Seeding here rather than in the task closes the same gap `ApiKeyRefresher` closes: a configuration
64    /// store between view creation and the first `changed` would otherwise leave the gate reporting the
65    /// older setting.
66    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    /// Spawns the supervised child that follows the view.
73    ///
74    /// The child follows its view forever and has no terminal condition, so it is spawned as a
75    /// [`Brutal`][ShutdownStrategy::Brutal] child: waiting for it at shutdown would hold the drain open until the
76    /// supervisor's budget elapsed, and there is nothing in flight to preserve.
77    ///
78    /// # Panics
79    ///
80    /// Panics if called outside of a supervision tree.
81    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
90/// Stores what `secrets_in_use` holds into `gate` for as long as the view keeps reporting changes.
91async 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/// Datadog Agent-specific forwarder retry configuration.
125#[derive(Clone)]
126#[cfg_attr(test, derive(Debug, PartialEq))]
127pub struct RetryConfiguration {
128    /// The minimum backoff factor to use when retrying requests.
129    ///
130    /// Controls the interval range that a calculated backoff duration can fall within, such that with a minimum
131    /// backoff factor of 2.0, calculated backoff durations will fall between `d/2` and `d`, where `d` is the calculated
132    /// backoff duration using a purely exponential growth strategy.
133    pub backoff_factor: f64,
134
135    /// The base growth rate of the backoff duration when retrying requests, in seconds.
136    pub backoff_base: f64,
137
138    /// The upper bound of the backoff duration when retrying requests, in seconds.
139    pub backoff_max: f64,
140
141    /// The amount to decrease the error count by when a request is successful.
142    ///
143    /// This essentially controls how quickly we forget about the number of previous errors when calculating the next
144    /// backoff duration for a request that must be retried.
145    pub recovery_error_decrease_factor: u32,
146
147    /// Whether or not a successful request should completely reset the error count.
148    pub recovery_reset: bool,
149
150    /// The maximum in-memory size of the retry queue, in bytes.
151    pub queue_max_size_bytes: u64,
152
153    /// The maximum size of the retry queue on disk, in bytes.
154    ///
155    /// A value of `0` disables disk persistence.
156    pub storage_max_size_bytes: u64,
157
158    /// The ratio of in-memory retry queue bytes to flush to disk when the queue is full.
159    ///
160    /// When disk persistence is enabled and the in-memory retry queue does not have enough room for a new transaction,
161    /// this controls how much in-memory data ADP moves to disk. For example, `0.5` moves at least half of the configured
162    /// in-memory retry queue size to disk during each overflow. If set to `0`, ADP moves only enough old transactions to
163    /// disk to make room for the new transaction.
164    pub flush_to_disk_mem_ratio: f64,
165
166    /// The configured path to the directory where the retry queue will be stored on disk.
167    ///
168    /// If this has no parent, such as when it is empty, the path is derived from `run_path` instead.
169    pub storage_path: PathBuf,
170
171    /// The base directory for runtime-state files, used to derive the storage path when none is configured.
172    ///
173    /// If neither is set, there is no storage path, and disk persistence has nowhere to write.
174    pub run_path: Option<PathBuf>,
175
176    /// The maximum disk usage ratio for storing transactions on disk.
177    ///
178    /// `0.8` means the Agent can store transactions on disk until `forwarder_storage_max_size_in_bytes`
179    /// is reached or when the disk mount for `forwarder_storage_path` exceeds 80% of the disk capacity,
180    /// whichever is lower.
181    pub storage_max_disk_ratio: f64,
182
183    /// Maximum age in days for retry files on disk before they are deleted at startup.
184    ///
185    /// When disk persistence is enabled, ADP removes any `retry-*.json` files in the
186    /// per-queue subdirectory of the storage path that are older than this many days
187    /// each time it starts. This prevents unbounded disk growth from stale retry data left
188    /// behind after long outages.
189    pub outdated_file_in_days: u32,
190
191    /// The time window used to estimate retry queue capacity, in seconds.
192    ///
193    /// ADP records incoming transaction payload bytes over this window and uses that rate to estimate how many seconds
194    /// of data the retry queue can buffer. Values below 10 seconds are clamped to 10 seconds, matching the fixed retry
195    /// queue capacity bucket size.
196    pub capacity_time_interval_secs: u64,
197}
198
199impl RetryConfiguration {
200    /// Returns the path to the directory where the retry queue will be stored on disk.
201    ///
202    /// A configured storage path is used as-is. Otherwise the path is derived from `run_path`, matching the Datadog
203    /// Agent's own layout. If neither is configured, the path is empty.
204    pub(crate) fn resolved_storage_path(&self) -> PathBuf {
205        resolve_storage_path(&self.storage_path, self.run_path.as_deref())
206    }
207
208    /// Returns the time window used to estimate retry queue capacity, in seconds, clamped to the bucket size.
209    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    /// Creates a new HTTP retry policy based on the forwarder configuration.
215    ///
216    /// A `403 Forbidden` response is retriable only when `secrets` reports that secret resolution might replace the
217    /// rejected API key. The gate is updated as configuration changes, so turning secrets management on or off while the
218    /// process runs changes the gate without rebuilding the service. A gate reporting nothing configured leaves a 403
219    /// non-retriable, which is the default behavior.
220    ///
221    /// Retries are counted by cause through `retry_causes`, which is scoped to the domain the policy sends to.
222    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
242/// Resolves the directory where retry payloads are persisted to disk.
243///
244/// A configured `forwarder_storage_path` is used as-is. Otherwise the path is derived from
245/// `run_path`. If neither is configured, no storage path is available.
246fn 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        // Use small backoffs so that any returned `Sleep` futures are cheap; we never await them, but build them.
296        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        // With neither setting, no valid path can be constructed, so disk persistence has nowhere to go.
341        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        // Exercise telemetry through the policy used by the forwarder, rather than calling the lifecycle hook directly.
383        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        // The refresher spawns on the ambient supervisor, and the supervisor is what keeps it running for the rest of
432        // the test.
433        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        // Before secrets management is configured, a 403 must not be retried.
440        assert!(!would_retry(&mut policy, ok_response(StatusCode::FORBIDDEN)));
441
442        // The same policy instance reads the gate on every response, so turning secrets management on
443        // changes the gate without rebuilding the service.
444        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    /// Waits for the refresher to bring `gate` to `expected`, failing if it never does.
457    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}