diff --git a/bottlecap/src/config/mod.rs b/bottlecap/src/config/mod.rs index bd27a54ff..ec9e740ae 100644 --- a/bottlecap/src/config/mod.rs +++ b/bottlecap/src/config/mod.rs @@ -115,6 +115,21 @@ pub struct LambdaConfig { pub api_security_sample_delay: Duration, pub custom_metrics_exclude_tags: Vec, + /// `DD_FEATURE_FLAGS_EXTENSION_CACHE_ENABLED`: serve the feature flag + /// configuration route from a cache in this execution environment. + pub feature_flags_extension_cache_enabled: bool, + /// Serve the cached configuration without contacting Datadog while it is + /// this young. + pub feature_flags_extension_cache_ttl_seconds: Duration, + /// When a refresh fails, keep serving a configuration up to this age. + pub feature_flags_extension_cache_max_stale_seconds: Duration, + /// Longest a read waits for the first configuration. + pub feature_flags_extension_cache_startup_wait_ms: u64, + /// Longest a read waits for a refresh before it gets the stale configuration. + pub feature_flags_extension_cache_refresh_wait_ms: u64, + /// Configuration file shipped with the function, used until Datadog answers. + pub feature_flags_extension_cache_bootstrap_file: Option, + /// When true, inferred (synthetic) event-source spans report the function's /// base service (`DD_SERVICE`) instead of the AWS resource/instance /// representation. An explicit `DD_SERVICE_MAPPING` entry still wins. @@ -182,6 +197,12 @@ impl Default for LambdaConfig { api_security_enabled: true, api_security_sample_delay: Duration::from_secs(30), custom_metrics_exclude_tags: Vec::new(), + feature_flags_extension_cache_enabled: false, + feature_flags_extension_cache_ttl_seconds: Duration::from_secs(30), + feature_flags_extension_cache_max_stale_seconds: Duration::from_secs(300), + feature_flags_extension_cache_startup_wait_ms: 3000, + feature_flags_extension_cache_refresh_wait_ms: 500, + feature_flags_extension_cache_bootstrap_file: None, trace_remove_integration_service_names_enabled: false, lambda_durable_function_log_buffer_size: 5, dsm_consume_enabled: false, @@ -296,6 +317,19 @@ pub struct LambdaConfigSource { #[serde(deserialize_with = "deser_dur_secs")] pub api_security_sample_delay: Option, + #[serde(deserialize_with = "deser_opt_bool")] + pub feature_flags_extension_cache_enabled: Option, + #[serde(deserialize_with = "deser_dur_secs")] + pub feature_flags_extension_cache_ttl_seconds: Option, + #[serde(deserialize_with = "deser_dur_secs")] + pub feature_flags_extension_cache_max_stale_seconds: Option, + #[serde(deserialize_with = "deser_opt_lossless")] + pub feature_flags_extension_cache_startup_wait_ms: Option, + #[serde(deserialize_with = "deser_opt_lossless")] + pub feature_flags_extension_cache_refresh_wait_ms: Option, + #[serde(deserialize_with = "deser_opt_str")] + pub feature_flags_extension_cache_bootstrap_file: Option, + /// `DD_LAMBDA_CUSTOMER_METRICS_EXCLUDE_TAGS` — comma-separated list of tag /// names to drop from customer `DogStatsD` metrics. Source field name /// matches the env var; merges into `custom_metrics_exclude_tags`. @@ -368,8 +402,13 @@ impl DatadogConfigExtension for LambdaConfig { trace_remove_integration_service_names_enabled, lambda_durable_function_log_buffer_size, trace_experimental_features_enabled, + feature_flags_extension_cache_enabled, + feature_flags_extension_cache_ttl_seconds, + feature_flags_extension_cache_max_stale_seconds, + feature_flags_extension_cache_startup_wait_ms, + feature_flags_extension_cache_refresh_wait_ms, ], - option: [span_dedup_timeout, api_key_secret_reload_interval, appsec_rules, serverless_error_sampler_enabled, dsm_exchange_name, dsm_kafka_group], + option: [feature_flags_extension_cache_bootstrap_file, span_dedup_timeout, api_key_secret_reload_interval, appsec_rules, serverless_error_sampler_enabled, dsm_exchange_name, dsm_kafka_group], ); if let Some(tps) = source.apm_config.errors_per_second { @@ -1327,6 +1366,44 @@ mod lambda_config_tests { ); } + #[test] + fn feature_flags_extension_cache_from_env() { + let config = load(|jail| { + jail.set_env("DD_FEATURE_FLAGS_EXTENSION_CACHE_ENABLED", "true"); + jail.set_env("DD_FEATURE_FLAGS_EXTENSION_CACHE_TTL_SECONDS", "60"); + jail.set_env("DD_FEATURE_FLAGS_EXTENSION_CACHE_MAX_STALE_SECONDS", "600"); + jail.set_env("DD_FEATURE_FLAGS_EXTENSION_CACHE_STARTUP_WAIT_MS", "1500"); + jail.set_env("DD_FEATURE_FLAGS_EXTENSION_CACHE_REFRESH_WAIT_MS", "0"); + jail.set_env( + "DD_FEATURE_FLAGS_EXTENSION_CACHE_BOOTSTRAP_FILE", + "/var/task/flags.json", + ); + Ok(()) + }); + let ext = &config.ext; + assert!(ext.feature_flags_extension_cache_enabled); + assert_eq!( + ext.feature_flags_extension_cache_ttl_seconds, + Duration::from_secs(60) + ); + assert_eq!( + ext.feature_flags_extension_cache_max_stale_seconds, + Duration::from_secs(600) + ); + assert_eq!(ext.feature_flags_extension_cache_startup_wait_ms, 1500); + assert_eq!(ext.feature_flags_extension_cache_refresh_wait_ms, 0); + assert_eq!( + ext.feature_flags_extension_cache_bootstrap_file.as_deref(), + Some("/var/task/flags.json") + ); + } + + #[test] + fn feature_flags_extension_cache_is_off_by_default() { + let config = load(|_| Ok(())); + assert!(!config.ext.feature_flags_extension_cache_enabled); + } + #[test] fn appsec_waf_timeout_from_env_microseconds() { let config = load(|jail| { diff --git a/bottlecap/src/startup.rs b/bottlecap/src/startup.rs index fdc079463..8bc679a5f 100644 --- a/bottlecap/src/startup.rs +++ b/bottlecap/src/startup.rs @@ -208,8 +208,9 @@ pub fn build_trace_agent( // Without a client that refuses redirects, leave the route out (404) // rather than risk sending the API key elsewhere. if let Some(client) = crate::http::get_client_without_redirects(config) { - trace_agent = - trace_agent.with_passthrough(Passthrough::new(config, api_key_factory.clone(), client)); + let passthrough = Passthrough::new(config, api_key_factory.clone(), client); + passthrough.prefetch(); + trace_agent = trace_agent.with_passthrough(passthrough); } let pipeline = TraceAgentPipeline { trace_tx: trace_agent.get_sender_copy(), diff --git a/bottlecap/src/traces/flag_config_cache.rs b/bottlecap/src/traces/flag_config_cache.rs new file mode 100644 index 000000000..079d5093e --- /dev/null +++ b/bottlecap/src/traces/flag_config_cache.rs @@ -0,0 +1,718 @@ +//! Execution-environment cache for the feature flag configuration route. +//! +//! The Extension owns the refresh from Datadog. The tracer reads from this +//! cache over localhost, so local reads do not reach the CDN while the cached +//! configuration is fresh. Freshness uses the wall clock at read time, not a +//! background timer: Lambda freezes the environment between invocations, so +//! the first read after a thaw sees the full elapsed time and refreshes. +//! +//! The cache lives and dies with the execution environment. Each new +//! environment fetches its own copy unless a bootstrap file is fresh. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime}; + +use axum::http::{HeaderValue, StatusCode}; +use bytes::Bytes; +use futures::future::BoxFuture; +use sha2::{Digest, Sha256}; +use tokio::sync::watch; +use tracing::{debug, error, warn}; + +use crate::config::Config; + +/// Wall clock, injectable so tests can simulate a freeze. +pub type Clock = Arc SystemTime + Send + Sync>; + +#[derive(Clone, Copy, Debug)] +pub struct CacheSettings { + /// Serve without contacting Datadog while the configuration is this young. + pub ttl: Duration, + /// Serve an older configuration only while it is this young, when a + /// refresh fails or does not finish within `refresh_wait`. + pub max_stale: Duration, + /// Longest a read waits for the first configuration of its scope. + pub startup_wait: Duration, + /// Longest a read waits for a refresh when a stale configuration exists. + pub refresh_wait: Duration, + /// After a failed refresh, wait this long before contacting Datadog again. + pub failure_backoff: Duration, +} + +impl CacheSettings { + #[must_use] + pub fn from_config(config: &Config) -> Option { + let ext = &config.ext; + ext.feature_flags_extension_cache_enabled.then(|| Self { + ttl: ext.feature_flags_extension_cache_ttl_seconds, + max_stale: ext.feature_flags_extension_cache_max_stale_seconds, + startup_wait: Duration::from_millis(ext.feature_flags_extension_cache_startup_wait_ms), + refresh_wait: Duration::from_millis(ext.feature_flags_extension_cache_refresh_wait_ms), + failure_backoff: FAILURE_BACKOFF, + }) + } +} + +const FAILURE_BACKOFF: Duration = Duration::from_secs(5); + +/// What a refresh got from Datadog. +pub enum Fetched { + Config { + body: Bytes, + etag: Option, + }, + NotModified, + /// Datadog's status, or 502 when Datadog was unreachable. + Failed(StatusCode), +} + +/// Fetches from Datadog, sending the cached `ETag` (if any) as `If-None-Match`. +pub type Fetch = Box) -> BoxFuture<'static, Fetched> + Send>; + +#[derive(Clone)] +pub struct Entry { + pub body: Bytes, + pub etag: String, + accepted_at: SystemTime, + bootstrap: bool, +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum Freshness { + Fresh, + Stale, + Bootstrap, +} + +impl Freshness { + #[must_use] + pub fn as_header(self) -> HeaderValue { + HeaderValue::from_static(match self { + Freshness::Fresh => "fresh", + Freshness::Stale => "stale", + Freshness::Bootstrap => "bootstrap", + }) + } +} + +pub enum Lookup { + Serve { + entry: Entry, + freshness: Freshness, + age: Duration, + }, + Unavailable(StatusCode), +} + +#[derive(Default)] +struct ScopeState { + entry: Option, + /// Set while a refresh runs; flips to `true` when it ends. + refreshing: Option>, + last_failure: Option<(SystemTime, StatusCode)>, +} + +#[derive(Clone)] +pub struct FlagConfigCache { + settings: CacheSettings, + clock: Clock, + scopes: Arc>>>>, + bootstrap: Option<(String, Entry)>, + upstream_requests: Arc, +} + +impl FlagConfigCache { + #[must_use] + pub fn new(settings: CacheSettings, clock: Clock) -> Self { + Self { + settings, + clock, + scopes: Arc::default(), + bootstrap: None, + upstream_requests: Arc::default(), + } + } + + /// Seeds the scope for `query` (what the Extension sends Datadog when the + /// tracer adds no query) with a configuration shipped with the function. + /// Its age counts from its `createdAt`, so an old file is only a fallback. + #[must_use] + pub fn with_bootstrap(mut self, query: String, body: Bytes) -> Self { + let Some(created_at) = valid_config(&body).and_then(|v| { + let created = v.get("createdAt")?.as_str()?.to_string(); + chrono::DateTime::parse_from_rfc3339(&created).ok() + }) else { + error!( + "TRACE_AGENT | Ignoring the flag config bootstrap file: not a valid configuration" + ); + return self; + }; + let entry = Entry { + etag: etag_for(&body), + body, + accepted_at: created_at.into(), + bootstrap: true, + }; + self.bootstrap = Some((query, entry)); + self + } + + /// Requests made to Datadog since the cache was created. + #[must_use] + pub fn upstream_requests(&self) -> u64 { + self.upstream_requests.load(Ordering::Relaxed) + } + + /// `scope` must identify everything that changes Datadog's answer (API + /// key and query), so scopes never see each other's configuration. + pub async fn get(&self, scope: &str, query: &str, fetch: Fetch) -> Lookup { + let state = self.scope(scope, query); + let (mut done, wait) = { + let mut s = state.lock().expect("lock poisoned"); + let now = (self.clock)(); + if let Some(lookup) = self.usable(&s, now, true) { + return lookup; + } + let backing_off = s.last_failure.is_some_and(|(at, _)| { + now.duration_since(at).unwrap_or_default() < self.settings.failure_backoff + }); + if backing_off && s.refreshing.is_none() { + return self.usable(&s, now, false).unwrap_or_else(|| { + Lookup::Unavailable(s.last_failure.map_or(StatusCode::BAD_GATEWAY, |f| f.1)) + }); + } + let done = if let Some(done) = &s.refreshing { + done.clone() + } else { + let done = self.spawn_refresh(&state, &s, fetch); + s.refreshing = Some(done.clone()); + done + }; + let wait = if s.entry.is_some() { + self.settings.refresh_wait + } else { + self.settings.startup_wait + }; + (done, wait) + }; + + // A timeout here leaves the refresh running for later readers. + let _ = tokio::time::timeout(wait, done.wait_for(|d| *d)).await; + + let s = state.lock().expect("lock poisoned"); + self.usable(&s, (self.clock)(), false).unwrap_or_else(|| { + Lookup::Unavailable(match (s.refreshing.is_some(), s.last_failure) { + (true, _) => StatusCode::GATEWAY_TIMEOUT, + (false, Some((_, status))) => status, + (false, None) => StatusCode::BAD_GATEWAY, + }) + }) + } + + fn scope(&self, scope: &str, query: &str) -> Arc> { + let mut scopes = self.scopes.lock().expect("lock poisoned"); + Arc::clone(scopes.entry(scope.to_string()).or_insert_with(|| { + let entry = self + .bootstrap + .as_ref() + .filter(|(q, _)| q == query) + .map(|(_, e)| e.clone()); + Arc::new(Mutex::new(ScopeState { + entry, + ..ScopeState::default() + })) + })) + } + + /// With `fresh_only`, returns only a configuration within the TTL. + fn usable(&self, s: &ScopeState, now: SystemTime, fresh_only: bool) -> Option { + let entry = s.entry.as_ref()?; + let age = now.duration_since(entry.accepted_at).unwrap_or_default(); + let freshness = if age <= self.settings.ttl { + Freshness::Fresh + } else if fresh_only { + return None; + } else if entry.bootstrap { + Freshness::Bootstrap + } else if age <= self.settings.max_stale { + Freshness::Stale + } else { + return None; + }; + Some(Lookup::Serve { + entry: entry.clone(), + freshness, + age, + }) + } + + fn spawn_refresh( + &self, + state: &Arc>, + s: &ScopeState, + fetch: Fetch, + ) -> watch::Receiver { + let (tx, rx) = watch::channel(false); + // Revalidate only a configuration Datadog sent, not the bootstrap file. + let etag = s + .entry + .as_ref() + .filter(|e| !e.bootstrap) + .map(|e| e.etag.clone()); + let state = Arc::clone(state); + let clock = Arc::clone(&self.clock); + self.upstream_requests.fetch_add(1, Ordering::Relaxed); + // Its own task: a tracer that disconnects must not cancel the refresh + // that other readers wait on. + tokio::spawn(async move { + let fetched = fetch(etag).await; + let mut s = state.lock().expect("lock poisoned"); + let now = clock(); + match fetched { + Fetched::Config { body, etag } if valid_config(&body).is_some() => { + debug!("TRACE_AGENT | Accepted a new flag config"); + s.entry = Some(Entry { + etag: etag.unwrap_or_else(|| etag_for(&body)), + body, + accepted_at: now, + bootstrap: false, + }); + s.last_failure = None; + } + Fetched::Config { .. } => { + warn!( + "TRACE_AGENT | Rejected an invalid flag config, keeping the previous one" + ); + s.last_failure = Some((now, StatusCode::BAD_GATEWAY)); + } + Fetched::NotModified => { + if let Some(entry) = s.entry.as_mut().filter(|e| !e.bootstrap) { + entry.accepted_at = now; + s.last_failure = None; + } else { + s.last_failure = Some((now, StatusCode::BAD_GATEWAY)); + } + } + Fetched::Failed(status) => { + warn!("TRACE_AGENT | Flag config refresh failed: {status}"); + s.last_failure = Some((now, status)); + } + } + s.refreshing = None; + let _ = tx.send(true); + }); + rx + } +} + +/// Same scope for the same API key and query; the key itself is not kept. +#[must_use] +pub fn scope_key(api_key: &str, query: &str) -> String { + let digest = Sha256::digest(api_key.as_bytes()); + format!("{}|{query}", hex(&digest[..8])) +} + +/// The CDN's JSON:API envelope around a Universal Flag Configuration; returns +/// the configuration. +fn valid_config(body: &[u8]) -> Option { + let mut value: serde_json::Value = serde_json::from_slice(body).ok()?; + let data = value.get_mut("data")?; + if data.get("type")?.as_str()? != "universal-flag-configuration" { + return None; + } + let config = data.get_mut("attributes")?.take(); + config.get("flags")?.is_object().then_some(config) +} + +fn etag_for(body: &[u8]) -> String { + format!("\"{}\"", hex(&Sha256::digest(body)[..16])) +} + +fn hex(bytes: &[u8]) -> String { + use std::fmt::Write; + bytes.iter().fold(String::new(), |mut s, b| { + let _ = write!(s, "{b:02x}"); + s + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::VecDeque; + use std::sync::atomic::AtomicUsize; + use tokio::time::Instant; + + const V1: &str = r#"{"data":{"type":"universal-flag-configuration","attributes":{"createdAt":"2026-11-17T00:00:00Z","format":"SERVER","environment":{"name":"prod"},"flags":{"a":{}}}}}"#; + const V2: &str = r#"{"data":{"type":"universal-flag-configuration","attributes":{"createdAt":"2026-11-17T00:01:00Z","format":"SERVER","environment":{"name":"prod"},"flags":{"b":{}}}}}"#; + + fn settings() -> CacheSettings { + CacheSettings { + ttl: Duration::from_secs(30), + max_stale: Duration::from_secs(300), + startup_wait: Duration::from_secs(3), + refresh_wait: Duration::from_millis(500), + failure_backoff: Duration::from_secs(5), + } + } + + /// A wall clock that only moves when the test says so, like a frozen + /// environment whose clock jumps when it thaws. + #[derive(Clone)] + struct TestClock(Arc>); + + impl TestClock { + fn new() -> Self { + Self(Arc::new(Mutex::new( + SystemTime::UNIX_EPOCH + Duration::from_secs(1_794_960_000), + ))) + } + fn advance(&self, by: Duration) { + *self.0.lock().expect("lock") += by; + } + fn clock(&self) -> Clock { + let now = Arc::clone(&self.0); + Arc::new(move || *now.lock().expect("lock")) + } + } + + /// Answers fetches in order and counts them. + #[derive(Clone)] + struct Upstream { + replies: Arc>>, + calls: Arc, + etags: Arc>>>, + } + + impl Upstream { + fn new(replies: Vec<(Duration, Fetched)>) -> Self { + Self { + replies: Arc::new(Mutex::new(replies.into())), + calls: Arc::default(), + etags: Arc::default(), + } + } + fn fetch(&self) -> Fetch { + let this = self.clone(); + Box::new(move |etag| { + this.calls.fetch_add(1, Ordering::SeqCst); + this.etags.lock().expect("lock").push(etag); + let (delay, reply) = this + .replies + .lock() + .expect("lock") + .pop_front() + .expect("unexpected fetch"); + Box::pin(async move { + tokio::time::sleep(delay).await; + reply + }) + }) + } + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } + } + + fn config(body: &str) -> (Duration, Fetched) { + ( + Duration::from_millis(10), + Fetched::Config { + body: Bytes::from(body.to_string()), + etag: None, + }, + ) + } + + fn served(lookup: Lookup) -> (String, Freshness) { + match lookup { + Lookup::Serve { + entry, freshness, .. + } => ( + String::from_utf8(entry.body.to_vec()).expect("utf8"), + freshness, + ), + Lookup::Unavailable(status) => panic!("unavailable: {status}"), + } + } + + fn unavailable(lookup: Lookup) -> StatusCode { + match lookup { + Lookup::Unavailable(status) => status, + Lookup::Serve { freshness, .. } => panic!("served {freshness:?}"), + } + } + + #[tokio::test(start_paused = true)] + async fn repeated_reads_reuse_one_fresh_fetch() { + let clock = TestClock::new(); + let cache = FlagConfigCache::new(settings(), clock.clock()); + let upstream = Upstream::new(vec![config(V1)]); + + for _ in 0..100 { + assert_eq!(served(cache.get("s", "", upstream.fetch()).await).0, V1); + clock.advance(Duration::from_millis(100)); + } + + assert_eq!(upstream.calls(), 1); + assert_eq!(cache.upstream_requests(), 1); + } + + #[tokio::test(start_paused = true)] + async fn concurrent_reads_share_one_refresh() { + let cache = FlagConfigCache::new(settings(), TestClock::new().clock()); + let upstream = Upstream::new(vec![( + Duration::from_millis(200), + Fetched::Config { + body: Bytes::from(V1), + etag: None, + }, + )]); + + let reads = (0..32).map(|_| { + let cache = cache.clone(); + let fetch = upstream.fetch(); + tokio::spawn(async move { served(cache.get("s", "", fetch).await).0 }) + }); + for read in futures::future::join_all(reads).await { + assert_eq!(read.expect("task"), V1); + } + + assert_eq!(upstream.calls(), 1); + } + + #[tokio::test(start_paused = true)] + async fn the_first_read_after_a_freeze_refreshes() { + let clock = TestClock::new(); + let cache = FlagConfigCache::new(settings(), clock.clock()); + let upstream = Upstream::new(vec![config(V1), config(V2)]); + served(cache.get("s", "", upstream.fetch()).await); + + // Frozen for less than the TTL: no timer ran, and none is needed. + clock.advance(Duration::from_secs(29)); + assert_eq!(served(cache.get("s", "", upstream.fetch()).await).0, V1); + assert_eq!(upstream.calls(), 1); + + // Frozen past the TTL: the read itself sees the elapsed time. + clock.advance(Duration::from_secs(600)); + assert_eq!( + served(cache.get("s", "", upstream.fetch()).await), + (V2.to_string(), Freshness::Fresh) + ); + assert_eq!(upstream.calls(), 2); + } + + #[tokio::test(start_paused = true)] + async fn an_invalid_refresh_keeps_the_accepted_config() { + let clock = TestClock::new(); + let cache = FlagConfigCache::new(settings(), clock.clock()); + let upstream = Upstream::new(vec![ + config(V1), + config(r#"{"data":{"type":"universal-flag-configuration","attributes":{"flags":[]}}}"#), + config("truncated"), + ]); + served(cache.get("s", "", upstream.fetch()).await); + + clock.advance(Duration::from_secs(31)); + assert_eq!( + served(cache.get("s", "", upstream.fetch()).await), + (V1.to_string(), Freshness::Stale) + ); + // Backs off instead of asking Datadog on every read. + assert_eq!( + served(cache.get("s", "", upstream.fetch()).await).1, + Freshness::Stale + ); + assert_eq!(upstream.calls(), 2); + + clock.advance(Duration::from_secs(6)); + assert_eq!(served(cache.get("s", "", upstream.fetch()).await).0, V1); + assert_eq!(upstream.calls(), 3); + } + + #[tokio::test(start_paused = true)] + async fn a_failed_refresh_serves_stale_only_until_max_stale() { + let clock = TestClock::new(); + let cache = FlagConfigCache::new(settings(), clock.clock()); + let failed = || { + ( + Duration::ZERO, + Fetched::Failed(StatusCode::SERVICE_UNAVAILABLE), + ) + }; + let upstream = Upstream::new(vec![config(V1), failed(), failed()]); + served(cache.get("s", "", upstream.fetch()).await); + + clock.advance(Duration::from_secs(299)); + assert_eq!( + served(cache.get("s", "", upstream.fetch()).await), + (V1.to_string(), Freshness::Stale) + ); + + clock.advance(Duration::from_secs(10)); + assert_eq!( + unavailable(cache.get("s", "", upstream.fetch()).await), + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!(upstream.calls(), 3); + } + + #[tokio::test(start_paused = true)] + async fn the_startup_wait_is_bounded() { + let cache = FlagConfigCache::new(settings(), TestClock::new().clock()); + let upstream = Upstream::new(vec![( + Duration::from_secs(3600), + Fetched::Config { + body: Bytes::from(V1), + etag: None, + }, + )]); + + let started = Instant::now(); + let status = unavailable(cache.get("s", "", upstream.fetch()).await); + + assert_eq!(status, StatusCode::GATEWAY_TIMEOUT); + assert_eq!(started.elapsed(), settings().startup_wait); + } + + #[tokio::test(start_paused = true)] + async fn the_refresh_wait_is_bounded_and_the_refresh_finishes_later() { + let clock = TestClock::new(); + let cache = FlagConfigCache::new(settings(), clock.clock()); + let slow = ( + Duration::from_secs(2), + Fetched::Config { + body: Bytes::from(V2), + etag: None, + }, + ); + let upstream = Upstream::new(vec![config(V1), slow]); + served(cache.get("s", "", upstream.fetch()).await); + clock.advance(Duration::from_secs(31)); + + let started = Instant::now(); + assert_eq!( + served(cache.get("s", "", upstream.fetch()).await), + (V1.to_string(), Freshness::Stale) + ); + assert_eq!(started.elapsed(), settings().refresh_wait); + + tokio::time::sleep(Duration::from_secs(2)).await; + assert_eq!( + served(cache.get("s", "", upstream.fetch()).await), + (V2.to_string(), Freshness::Fresh) + ); + assert_eq!(upstream.calls(), 2); + } + + #[tokio::test(start_paused = true)] + async fn not_modified_renews_the_config_and_sends_its_etag() { + let clock = TestClock::new(); + let cache = FlagConfigCache::new(settings(), clock.clock()); + let upstream = Upstream::new(vec![ + ( + Duration::ZERO, + Fetched::Config { + body: Bytes::from(V1), + etag: Some("\"v1\"".to_string()), + }, + ), + (Duration::ZERO, Fetched::NotModified), + ]); + served(cache.get("s", "", upstream.fetch()).await); + clock.advance(Duration::from_secs(31)); + + assert_eq!( + served(cache.get("s", "", upstream.fetch()).await), + (V1.to_string(), Freshness::Fresh) + ); + clock.advance(Duration::from_secs(29)); + served(cache.get("s", "", upstream.fetch()).await); + + assert_eq!(upstream.calls(), 2); + assert_eq!( + *upstream.etags.lock().expect("lock"), + vec![None, Some("\"v1\"".to_string())] + ); + } + + #[tokio::test(start_paused = true)] + async fn scopes_never_see_each_other() { + let cache = FlagConfigCache::new(settings(), TestClock::new().clock()); + let prod = Upstream::new(vec![config(V1)]); + let staging = Upstream::new(vec![config(V2)]); + let prod_scope = scope_key("key", "dd_env=prod"); + let staging_scope = scope_key("key", "dd_env=staging"); + let other_key = scope_key("other-key", "dd_env=prod"); + + assert_eq!( + served(cache.get(&prod_scope, "dd_env=prod", prod.fetch()).await).0, + V1 + ); + assert_eq!( + served( + cache + .get(&staging_scope, "dd_env=staging", staging.fetch()) + .await + ) + .0, + V2 + ); + assert_ne!(prod_scope, other_key); + assert!(!prod_scope.contains("key|"), "the API key is not kept"); + assert_eq!((prod.calls(), staging.calls()), (1, 1)); + } + + #[tokio::test(start_paused = true)] + async fn each_new_environment_fetches_its_own_config() { + let upstream = Upstream::new((0..16).map(|_| config(V1)).collect()); + for _ in 0..16 { + // A cold start: new process, new cache. + let cache = FlagConfigCache::new(settings(), TestClock::new().clock()); + served(cache.get("s", "", upstream.fetch()).await); + } + assert_eq!(upstream.calls(), 16); + } + + #[tokio::test(start_paused = true)] + async fn a_fresh_bootstrap_file_avoids_the_initial_fetch() { + let clock = TestClock::new(); + let created = + chrono::DateTime::::from((clock.clock())() - Duration::from_secs(10)) + .to_rfc3339(); + let body = V1.replace("2026-11-17T00:00:00Z", &created); + let cache = FlagConfigCache::new(settings(), clock.clock()) + .with_bootstrap("dd_env=prod".to_string(), Bytes::from(body.clone())); + let upstream = Upstream::new(vec![]); + + assert_eq!( + served(cache.get("s", "dd_env=prod", upstream.fetch()).await), + (body, Freshness::Fresh) + ); + assert_eq!(upstream.calls(), 0); + } + + #[tokio::test(start_paused = true)] + async fn an_old_bootstrap_file_is_only_a_fallback() { + let cache = FlagConfigCache::new(settings(), TestClock::new().clock()) + .with_bootstrap("dd_env=prod".to_string(), Bytes::from(V1)); + let upstream = Upstream::new(vec![ + (Duration::ZERO, Fetched::Failed(StatusCode::BAD_GATEWAY)), + config(V2), + ]); + + // Datadog is tried first; its failure falls back to the file. + assert_eq!( + served(cache.get("s", "dd_env=prod", upstream.fetch()).await), + (V1.to_string(), Freshness::Bootstrap) + ); + // Another scope never gets the file. + assert_eq!( + served(cache.get("t", "dd_env=staging", upstream.fetch()).await).0, + V2 + ); + assert_eq!(upstream.calls(), 2); + } +} diff --git a/bottlecap/src/traces/mod.rs b/bottlecap/src/traces/mod.rs index 331f9c650..e88bc2cec 100644 --- a/bottlecap/src/traces/mod.rs +++ b/bottlecap/src/traces/mod.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 pub mod data_streams; +pub mod flag_config_cache; pub mod http_client; pub mod passthrough; pub mod propagation; diff --git a/bottlecap/src/traces/passthrough.rs b/bottlecap/src/traces/passthrough.rs index e4488d9f1..00009413c 100644 --- a/bottlecap/src/traces/passthrough.rs +++ b/bottlecap/src/traces/passthrough.rs @@ -6,12 +6,12 @@ //! Extension can read the key (for example `DD_API_KEY_SECRET_ARN`). use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, SystemTime}; use axum::{ Router, extract::{RawQuery, State}, - http::{HeaderMap, HeaderName, StatusCode, header}, + http::{HeaderMap, HeaderName, HeaderValue, StatusCode, header}, response::{IntoResponse, Response}, routing::get, }; @@ -20,10 +20,15 @@ use tokio::time::{Instant, timeout_at}; use tracing::{debug, error}; use crate::config::Config; +use crate::traces::flag_config_cache::{ + CacheSettings, Fetch, Fetched, FlagConfigCache, Lookup, scope_key, +}; /// Feature flag configuration (rules) used by the tracers' flag providers. pub const FLAG_CONFIG_PATH: &str = "/api/v2/feature-flagging/config/rules-based/server"; const FLAG_CONFIG_SUBDOMAIN: &str = "ufc-server.ff-cdn"; +/// Tells the tracer whether a cached reply was fresh, stale or the bootstrap file. +pub const CACHE_STATUS_HEADER: &str = "x-datadog-flag-config-cache"; /// Covers resolving the API key and the request to Datadog. Below the tracers' /// default 5 second request timeout, so the tracer sees our error instead of @@ -50,6 +55,8 @@ pub struct Passthrough { flag_config_base_url: String, env: Option, timeout: Duration, + /// When set, flag config is served from the execution environment's cache. + cache: Option, } impl Passthrough { @@ -59,17 +66,45 @@ impl Passthrough { api_key_factory: Arc, client: reqwest::Client, ) -> Self { - Self { + #[allow(unused_mut)] + let mut flag_config_base_url = format!("https://{FLAG_CONFIG_SUBDOMAIN}.{}", config.site); + // Lets the local test harness stand in for the CDN. + #[cfg(feature = "test-mode")] + if let Ok(url) = std::env::var("DD_TESTMODE_FEATURE_FLAGS_CDN_URL") { + flag_config_base_url = url; + } + let mut passthrough = Self { api_key_factory, client, - flag_config_base_url: format!("https://{FLAG_CONFIG_SUBDOMAIN}.{}", config.site), + flag_config_base_url, // `DD_ENV` wins over an `env` tag in `DD_TAGS`, like in the tracers. env: config .env .clone() .or_else(|| config.tags.get("env").cloned()), timeout: UPSTREAM_TIMEOUT, + cache: None, + }; + if let Some(settings) = CacheSettings::from_config(config) { + let mut cache = FlagConfigCache::new(settings, Arc::new(SystemTime::now)); + if let Some(path) = &config.ext.feature_flags_extension_cache_bootstrap_file { + match std::fs::read(path) { + Ok(body) => { + let query = passthrough + .upstream_url(None) + .query() + .unwrap_or("") + .to_string(); + cache = cache.with_bootstrap(query, body.into()); + } + Err(e) => { + error!("TRACE_AGENT | Can't read the flag config bootstrap file: {e}"); + } + } + } + passthrough.cache = Some(cache); } + passthrough } pub fn router(self) -> Router { @@ -77,6 +112,33 @@ impl Passthrough { .route(FLAG_CONFIG_PATH, get(flag_config)) .with_state(self) } + + /// With the cache on, starts fetching the default configuration now, so + /// it can arrive while the runtime initializes. + pub fn prefetch(&self) { + if self.cache.is_none() { + return; + } + let passthrough = self.clone(); + tokio::spawn(async move { + let _ = flag_config(State(passthrough), RawQuery(None), HeaderMap::new()).await; + }); + } + + /// The tracer drops `dd_env` when it uses a custom base URL, so add ours. + fn upstream_url(&self, query: Option<&str>) -> reqwest::Url { + let mut url = + reqwest::Url::parse(&format!("{}{FLAG_CONFIG_PATH}", self.flag_config_base_url)) + .unwrap_or_else(|_| { + reqwest::Url::parse("https://invalid.invalid").expect("valid url") + }); + url.set_query(query); + let has_env = url.query_pairs().any(|(k, _)| k == "dd_env"); + if let (Some(env), false) = (&self.env, has_env) { + url.query_pairs_mut().append_pair("dd_env", env); + } + url + } } async fn flag_config( @@ -114,10 +176,9 @@ async fn flag_config( } }; - let mut url = format!("{}{FLAG_CONFIG_PATH}", passthrough.flag_config_base_url); - if let Some(query) = &query { - url.push('?'); - url.push_str(query); + let url = passthrough.upstream_url(query.as_deref()); + if let Some(cache) = &passthrough.cache { + return cached(&passthrough, cache, url, api_key, &headers).await; } let mut request = passthrough @@ -125,14 +186,6 @@ async fn flag_config( .get(url) .timeout(deadline.saturating_duration_since(Instant::now())) .header("DD-API-KEY", api_key); - // The tracer drops `dd_env` when it uses a custom base URL. - let has_env = query.as_deref().is_some_and(|q| { - q.split('&') - .any(|pair| pair == "dd_env" || pair.starts_with("dd_env=")) - }); - if let (Some(env), false) = (&passthrough.env, has_env) { - request = request.query(&[("dd_env", env)]); - } for name in FORWARDED_REQUEST_HEADERS { if let Some(value) = headers.get(&name) { request = request.header(name, value); @@ -166,6 +219,79 @@ async fn flag_config( } } +async fn cached( + passthrough: &Passthrough, + cache: &FlagConfigCache, + url: reqwest::Url, + api_key: String, + headers: &HeaderMap, +) -> Response { + let query = url.query().unwrap_or("").to_string(); + let scope = scope_key(&api_key, &query); + let client = passthrough.client.clone(); + let fetch: Fetch = Box::new(move |etag| { + Box::pin(async move { + let mut request = client + .get(url) + .timeout(UPSTREAM_TIMEOUT) + .header("DD-API-KEY", api_key) + .header(header::ACCEPT, "application/json"); + if let Some(etag) = etag { + request = request.header(header::IF_NONE_MATCH, etag); + } + let upstream = match request.send().await { + Ok(upstream) => upstream, + Err(e) => { + error!("TRACE_AGENT | Flag config request to Datadog failed: {e}"); + return Fetched::Failed(StatusCode::BAD_GATEWAY); + } + }; + match upstream.status() { + StatusCode::NOT_MODIFIED => Fetched::NotModified, + status if status.is_success() => { + let etag = upstream + .headers() + .get(header::ETAG) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + match upstream.bytes().await { + Ok(body) => Fetched::Config { body, etag }, + Err(_) => Fetched::Failed(StatusCode::BAD_GATEWAY), + } + } + status => Fetched::Failed(status), + } + }) + }); + + match cache.get(&scope, &query, fetch).await { + Lookup::Serve { + entry, + freshness, + age, + } => { + let mut response_headers = HeaderMap::new(); + if let Ok(etag) = HeaderValue::from_str(&entry.etag) { + response_headers.insert(header::ETAG, etag); + } + response_headers.insert(header::AGE, HeaderValue::from(age.as_secs())); + response_headers.insert(CACHE_STATUS_HEADER, freshness.as_header()); + let unchanged = headers + .get(header::IF_NONE_MATCH) + .is_some_and(|v| v.as_bytes() == entry.etag.as_bytes()); + if unchanged { + return (StatusCode::NOT_MODIFIED, response_headers).into_response(); + } + response_headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + (StatusCode::OK, response_headers, entry.body).into_response() + } + Lookup::Unavailable(status) => status.into_response(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -185,6 +311,7 @@ mod tests { flag_config_base_url: base_url, env: Some("prod".to_string()), timeout: UPSTREAM_TIMEOUT, + cache: None, } } @@ -397,6 +524,109 @@ mod tests { mock.assert_async().await; } + const UFC: &str = r#"{"data":{"type":"universal-flag-configuration","attributes":{"flags":{},"environment":{"name":"prod"}}}}"#; + + fn cached(passthrough: Passthrough) -> Passthrough { + let settings = CacheSettings { + ttl: Duration::from_secs(30), + max_stale: Duration::from_secs(300), + startup_wait: Duration::from_secs(3), + refresh_wait: Duration::from_millis(500), + failure_backoff: Duration::from_secs(5), + }; + Passthrough { + cache: Some(FlagConfigCache::new(settings, Arc::new(SystemTime::now))), + ..passthrough + } + } + + #[tokio::test] + async fn cache_serves_repeated_reads_from_one_request() { + let server = MockServer::start_async().await; + let mock = server + .mock_async(|when, then| { + when.method(GET) + .path(FLAG_CONFIG_PATH) + .header("DD-API-KEY", "test-key") + .query_param("dd_env", "prod"); + then.status(200).header("ETag", "\"v1\"").body(UFC); + }) + .await; + let passthrough = cached(passthrough( + server.base_url(), + ApiKeyFactory::new("test-key"), + )); + + for _ in 0..10 { + let response = call(passthrough.clone(), FLAG_CONFIG_PATH, None).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[CACHE_STATUS_HEADER], "fresh"); + let body = to_bytes(response.into_body(), usize::MAX) + .await + .expect("body"); + assert_eq!(&body[..], UFC.as_bytes()); + } + let unchanged = call(passthrough, FLAG_CONFIG_PATH, Some("\"v1\"")).await; + + assert_eq!(unchanged.status(), StatusCode::NOT_MODIFIED); + assert_eq!(mock.hits_async().await, 1); + } + + #[tokio::test] + async fn cache_keeps_environments_apart() { + let server = MockServer::start_async().await; + for env in ["prod", "staging"] { + server + .mock_async(|when, then| { + when.method(GET) + .path(FLAG_CONFIG_PATH) + .query_param("dd_env", env); + then.status(200) + .body(UFC.replace("\"prod\"", &format!("\"{env}\""))); + }) + .await; + } + let passthrough = cached(passthrough( + server.base_url(), + ApiKeyFactory::new("test-key"), + )); + + for env in ["prod", "staging", "prod"] { + let response = call( + passthrough.clone(), + &format!("{FLAG_CONFIG_PATH}?dd_env={env}"), + None, + ) + .await; + let body = to_bytes(response.into_body(), usize::MAX) + .await + .expect("body"); + assert!( + String::from_utf8_lossy(&body).contains(&format!(r#""name":"{env}""#)), + "{env} got {body:?}" + ); + } + } + + #[tokio::test] + async fn cache_passes_an_auth_failure_through() { + let server = MockServer::start_async().await; + server + .mock_async(|when, then| { + when.method(GET).path(FLAG_CONFIG_PATH); + then.status(403); + }) + .await; + let passthrough = cached(passthrough( + server.base_url(), + ApiKeyFactory::new("bad-key"), + )); + + let response = call(passthrough, FLAG_CONFIG_PATH, None).await; + + assert_eq!(response.status(), StatusCode::FORBIDDEN); + } + #[tokio::test] async fn does_not_forward_other_paths() { let response = call( diff --git a/examples/feature-flags-config-cache/.gitignore b/examples/feature-flags-config-cache/.gitignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/examples/feature-flags-config-cache/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/examples/feature-flags-config-cache/README.md b/examples/feature-flags-config-cache/README.md new file mode 100644 index 000000000..fe81c641f --- /dev/null +++ b/examples/feature-flags-config-cache/README.md @@ -0,0 +1,65 @@ +# Feature flags from the Extension's configuration cache + +A Lambda-style Node handler that evaluates Datadog feature flags with the real +dd-trace flag provider (`dd-trace@6.25.0`, `tracer.openfeature`). The +configuration comes from the Extension, which caches it per execution +environment and is the only process that contacts the Datadog CDN. + +This is a prototype. Nothing here has run in AWS Lambda. + +## How it fits together + +```mermaid +flowchart LR + H[handler.js
dd-trace flag provider] -- "GET 127.0.0.1:8126
If-None-Match" --> X[Extension cache] + X -- "only when stale:
DD-API-KEY, dd_env" --> CDN[(Datadog CDN)] + H -- exposures --> X +``` + +- `handler.js`: initializes the tracer once per environment. At the start of + each invocation it reloads from the Extension, then evaluates `kill-switch`. +- `extension-config.js`: the local reload. A `304` keeps the provider's + snapshot; a `200` replaces it. +- `fixtures/`: the CDN's JSON:API envelope around the `kill-switch` flag from + [ffe-system-test-data](https://github.com/DataDog/ffe-system-test-data) + (`ufc-config.json` at `84689ad6`). `ufc-v2.json` turns the flag on for everyone. + +## Two ways to keep the SDK off the CDN + +| Mode | SDK settings | Code | After a thaw | +|---|---|---|---| +| Reload per invocation (this handler) | `DD_FEATURE_FLAGS_CONFIGURATION_SOURCE=remote_config`, `DD_REMOTE_CONFIGURATION_ENABLED=false` | `extension-config.js` | The first invocation reads the Extension before it evaluates | +| SDK polls the Extension | `DD_FEATURE_FLAGS_CONFIGURATION_SOURCE=agentless`, `DD_FEATURE_FLAGS_CONFIGURATION_SOURCE_AGENTLESS_BASE_URL=http://127.0.0.1:8126` | None | The SDK's poll timer fires late, so the first invocation can evaluate the old snapshot | + +The first mode uses `setConfiguration`, which `tracer.openfeature` has at +runtime but dd-trace does not type or document. It also unwraps the CDN +envelope itself and has to wait for OpenFeature's ready state after the first +load. A supported version needs an SDK API for this, for example a +`local` source that reloads on demand. + +## Extension settings + +| Variable | Default | Meaning | +|---|---|---| +| `DD_FEATURE_FLAGS_EXTENSION_CACHE_ENABLED` | `false` | Serve the route from the cache. Off: the route forwards each request, as before. | +| `DD_FEATURE_FLAGS_EXTENSION_CACHE_TTL_SECONDS` | `30` | Serve without contacting Datadog while the configuration is this young. | +| `DD_FEATURE_FLAGS_EXTENSION_CACHE_MAX_STALE_SECONDS` | `300` | If a refresh fails, keep serving the configuration up to this age, then answer `5xx`. | +| `DD_FEATURE_FLAGS_EXTENSION_CACHE_STARTUP_WAIT_MS` | `3000` | Longest a read waits for the first configuration. | +| `DD_FEATURE_FLAGS_EXTENSION_CACHE_REFRESH_WAIT_MS` | `500` | Longest a read waits for a refresh before it gets the stale configuration. | +| `DD_FEATURE_FLAGS_EXTENSION_CACHE_BOOTSTRAP_FILE` | unset | A CDN response shipped with the function. Used as fresh only while its `createdAt` is within the TTL, otherwise only as a fallback. | + +Replies carry `ETag`, `Age` and `X-Datadog-Flag-Config-Cache: fresh | stale | bootstrap`. + +## Run the tests + +```bash +(cd ../../bottlecap && cargo build --features test-mode --bin bottlecap-test-mode) +npm ci +npm test +``` + +The tests start the real Extension (test-mode build, which reads +`DD_TESTMODE_FEATURE_FLAGS_CDN_URL`), a fake CDN, a fake trace agent, and one +Node process per simulated execution environment. Time-sensitive cache rules +(freeze and thaw, bounded waits) are tested with a fake clock in +`bottlecap/src/traces/flag_config_cache.rs`. diff --git a/examples/feature-flags-config-cache/extension-config.js b/examples/feature-flags-config-cache/extension-config.js new file mode 100644 index 000000000..bb9ed67f9 --- /dev/null +++ b/examples/feature-flags-config-cache/extension-config.js @@ -0,0 +1,65 @@ +'use strict' + +const http = require('node:http') + +const FLAG_CONFIG_PATH = '/api/v2/feature-flagging/config/rules-based/server' + +/** + * Loads the flag configuration from the Datadog Extension into the tracer's + * flag provider. Call `reload()` at the start of each invocation: the + * Extension answers from its cache (or `304` when nothing changed), and only + * the Extension contacts Datadog. + * + * Prototype glue: `setConfiguration` exists on `tracer.openfeature` at runtime + * but is not in dd-trace's public types, and unwrapping the envelope repeats + * what dd-trace's private agentless source does. + */ +class ExtensionConfig { + /** + * @param {{ setConfiguration: (configuration: object) => void }} provider + * @param {{ url?: string, timeoutMs?: number }} [options] + */ + constructor (provider, options = {}) { + this.provider = provider + this.url = (options.url ?? process.env.DD_FEATURE_FLAGS_EXTENSION_URL ?? 'http://127.0.0.1:8126') + + FLAG_CONFIG_PATH + // Above the Extension's startup wait, so the Extension decides the outcome. + this.timeoutMs = options.timeoutMs ?? 3500 + this.etag = undefined + this.last = undefined + } + + async reload () { + const reply = await get(this.url, this.etag, this.timeoutMs) + this.last = { status: reply.status, cache: reply.headers['x-datadog-flag-config-cache'] } + if (reply.status !== 200) return this.last + + try { + // The Extension relays the CDN's JSON:API envelope. + const { data } = JSON.parse(reply.body) + if (data?.type !== 'universal-flag-configuration') throw new Error('not a flag configuration') + this.provider.setConfiguration(data.attributes) + this.etag = reply.headers.etag + } catch { + // Keep the configuration the provider already has. + this.last.status = 'rejected' + } + return this.last + } +} + +function get (url, etag, timeoutMs) { + return new Promise(resolve => { + const headers = etag ? { 'If-None-Match': etag } : {} + const req = http.get(url, { headers, timeout: timeoutMs }, res => { + let body = '' + res.setEncoding('utf8') + res.on('data', chunk => { body += chunk }) + res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body })) + }) + req.on('timeout', () => req.destroy(new Error('timeout'))) + req.on('error', () => resolve({ status: 0, headers: {}, body: '' })) + }) +} + +module.exports = { ExtensionConfig, FLAG_CONFIG_PATH } diff --git a/examples/feature-flags-config-cache/fixtures/ufc-v1.json b/examples/feature-flags-config-cache/fixtures/ufc-v1.json new file mode 100644 index 000000000..b17ffa228 --- /dev/null +++ b/examples/feature-flags-config-cache/fixtures/ufc-v1.json @@ -0,0 +1,111 @@ +{ + "data": { + "id": "1", + "type": "universal-flag-configuration", + "attributes": { + "createdAt": "2026-11-17T12:00:00.000Z", + "format": "SERVER", + "environment": { + "name": "prod" + }, + "flags": { + "kill-switch": { + "key": "kill-switch", + "enabled": true, + "variationType": "BOOLEAN", + "variations": { + "on": { + "key": "on", + "value": true + }, + "off": { + "key": "off", + "value": false + } + }, + "allocations": [ + { + "key": "on-for-NA", + "rules": [ + { + "conditions": [ + { + "attribute": "country", + "operator": "ONE_OF", + "value": [ + "US", + "Canada", + "Mexico" + ] + } + ] + } + ], + "splits": [ + { + "variationKey": "on", + "shards": [ + { + "salt": "some-salt", + "totalShards": 10000, + "ranges": [ + { + "start": 0, + "end": 10000 + } + ] + } + ] + } + ], + "doLog": true + }, + { + "key": "on-for-age-50+", + "rules": [ + { + "conditions": [ + { + "attribute": "age", + "operator": "GTE", + "value": 50 + } + ] + } + ], + "splits": [ + { + "variationKey": "on", + "shards": [ + { + "salt": "some-salt", + "totalShards": 10000, + "ranges": [ + { + "start": 0, + "end": 10000 + } + ] + } + ] + } + ], + "doLog": true + }, + { + "key": "off-for-all", + "rules": [], + "splits": [ + { + "variationKey": "off", + "shards": [] + } + ], + "doLog": true + } + ] + } + } + } + } +} diff --git a/examples/feature-flags-config-cache/fixtures/ufc-v2.json b/examples/feature-flags-config-cache/fixtures/ufc-v2.json new file mode 100644 index 000000000..3f801a0b6 --- /dev/null +++ b/examples/feature-flags-config-cache/fixtures/ufc-v2.json @@ -0,0 +1,111 @@ +{ + "data": { + "id": "1", + "type": "universal-flag-configuration", + "attributes": { + "createdAt": "2026-11-17T12:05:00.000Z", + "format": "SERVER", + "environment": { + "name": "prod" + }, + "flags": { + "kill-switch": { + "key": "kill-switch", + "enabled": true, + "variationType": "BOOLEAN", + "variations": { + "on": { + "key": "on", + "value": true + }, + "off": { + "key": "off", + "value": false + } + }, + "allocations": [ + { + "key": "on-for-NA", + "rules": [ + { + "conditions": [ + { + "attribute": "country", + "operator": "ONE_OF", + "value": [ + "US", + "Canada", + "Mexico" + ] + } + ] + } + ], + "splits": [ + { + "variationKey": "on", + "shards": [ + { + "salt": "some-salt", + "totalShards": 10000, + "ranges": [ + { + "start": 0, + "end": 10000 + } + ] + } + ] + } + ], + "doLog": true + }, + { + "key": "on-for-age-50+", + "rules": [ + { + "conditions": [ + { + "attribute": "age", + "operator": "GTE", + "value": 50 + } + ] + } + ], + "splits": [ + { + "variationKey": "on", + "shards": [ + { + "salt": "some-salt", + "totalShards": 10000, + "ranges": [ + { + "start": 0, + "end": 10000 + } + ] + } + ] + } + ], + "doLog": true + }, + { + "key": "on-for-all", + "rules": [], + "splits": [ + { + "variationKey": "on", + "shards": [] + } + ], + "doLog": true + } + ] + } + } + } + } +} diff --git a/examples/feature-flags-config-cache/handler.js b/examples/feature-flags-config-cache/handler.js new file mode 100644 index 000000000..a7bd00da6 --- /dev/null +++ b/examples/feature-flags-config-cache/handler.js @@ -0,0 +1,29 @@ +'use strict' + +// Runs once per execution environment (the Lambda Init phase). +const tracer = require('dd-trace').init() +const { OpenFeature } = require('@openfeature/server-sdk') +const { ExtensionConfig } = require('./extension-config') + +const provider = tracer.openfeature +// Resolves once the provider has a configuration. OpenFeature marks the +// client ready asynchronously, after `setConfiguration` returns. +const ready = OpenFeature.setProviderAndWait(provider).catch(() => {}) +const client = OpenFeature.getClient() + +// With DD_FEATURE_FLAGS_CONFIGURATION_SOURCE=agentless and the base URL set +// to the Extension, the tracer polls the Extension on its own timer. Otherwise +// the handler reloads from the Extension at the start of each invocation. +const extensionConfig = process.env.DD_FEATURE_FLAGS_CONFIGURATION_SOURCE === 'agentless' + ? undefined + : new ExtensionConfig(provider) + +exports.handler = async (event) => { + const config = await extensionConfig?.reload() + if (extensionConfig?.etag) await ready + const details = await client.getBooleanDetails('kill-switch', false, { + targetingKey: event.userId, + country: event.country, + }) + return { value: details.value, variant: details.variant, reason: details.reason, config } +} diff --git a/examples/feature-flags-config-cache/package-lock.json b/examples/feature-flags-config-cache/package-lock.json new file mode 100644 index 000000000..54ab7a769 --- /dev/null +++ b/examples/feature-flags-config-cache/package-lock.json @@ -0,0 +1,775 @@ +{ + "name": "feature-flags-config-cache-example", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "feature-flags-config-cache-example", + "dependencies": { + "@openfeature/server-sdk": "1.23.0", + "dd-trace": "6.25.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@datadog/libdatadog": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/@datadog/libdatadog/-/libdatadog-0.21.0.tgz", + "integrity": "sha512-6JQVv7LGBYG6uiY2wtno5paqP/G1UFXK1tA4LZEt2Bc9AzbCMtO2yrs1VfYDzMyVaFSj0+6QLdR8Hu5DQUODmw==", + "license": "Apache-2.0", + "optional": true, + "workspaces": [ + "wasm" + ], + "dependencies": { + "@datadog/libdatadog-wasm": "0.21.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@datadog/libdatadog-extras": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/@datadog/libdatadog-extras/-/libdatadog-extras-0.21.0.tgz", + "integrity": "sha512-VgAlNdNtilutWsEoDy6cAtn1iRLVQuj84lppjGlrwfvMwoCJ40B4pIttrZr0R7n01a6H83zv2SNt7SiH3smJRg==", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/@datadog/libdatadog-wasm": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/@datadog/libdatadog-wasm/-/libdatadog-wasm-0.21.0.tgz", + "integrity": "sha512-2wg5naOV+X7wyCNBJ/mRxE56fK22iz4ZwehzA/dSzuBO4/daNaVM6UgudRjkgXA9Pp0zEYcxmv4e1tNApQAEng==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@datadog/native-appsec": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@datadog/native-appsec/-/native-appsec-11.0.3.tgz", + "integrity": "sha512-IlB4IuL42rWVHmigMrWhtYW38Q7rQd5iH2Yf7HRkL51mP2ODiD52rwdrbTsJl9nt2msMR8/fsoySIs4d02xzEA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "node-gyp-build": "^3.9.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@datadog/native-iast-taint-tracking": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@datadog/native-iast-taint-tracking/-/native-iast-taint-tracking-4.2.1.tgz", + "integrity": "sha512-KRLu3aTXvyAusouAZGTw2w1Xo67cRTw93yG4C9vTMpIgN9FXiqhlcvtNHvUzaA/KRrwtNwbaUELubOtk/kxOFg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "node-gyp-build": "^3.9.0" + } + }, + "node_modules/@datadog/native-metrics": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@datadog/native-metrics/-/native-metrics-4.0.0.tgz", + "integrity": "sha512-rS6Qc8WAbOgbrtDYdqK15gi2xbuIEyfuquUH05g+2DOdiNAswNAGrlIuSdJZQF/qoJzjcFvxb9kCHu8BjiPfQQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "node-addon-api": "^6.1.0", + "node-gyp-build": "^3.9.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@datadog/pprof": { + "version": "5.20.1", + "resolved": "https://registry.npmjs.org/@datadog/pprof/-/pprof-5.20.1.tgz", + "integrity": "sha512-0mUaO8gSsX84cjWJ4VvJIDNj6tka5NnqQysg8emetQPYv5ClKdfiRFHWm2DzPBEhVnj4yWXzaOGMO1UNl9Av/Q==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "node-gyp-build": "^4.8.4", + "pprof-format": "^2.3.2", + "source-map": "^0.8.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@datadog/pprof/node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/@datadog/wasm-js-rewriter": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@datadog/wasm-js-rewriter/-/wasm-js-rewriter-5.0.4.tgz", + "integrity": "sha512-tSjbk51dkNzFMM3P/7y82tyrBj/9CWnPzcVb1JB8TUea/PIholdXSPuGC5F975YvvGB8KDujfmJIacN+EmuXMg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "js-yaml": "^4.3.1", + "lru-cache": "^7.14.0", + "module-details-from-path": "^1.0.4", + "node-gyp-build": "^4.8.4" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/@datadog/wasm-js-rewriter/node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/@emnapi/core": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", + "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", + "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" + } + }, + "node_modules/@openfeature/core": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@openfeature/core/-/core-1.12.0.tgz", + "integrity": "sha512-7PCPzyd1OC19begz30+CRknFB0ChtyaZUhk7YWrk+Bov1fpVw0HYkTXtoxxsvPfDZB9P9WsT7uixN+Z8f9+bcA==", + "license": "Apache-2.0", + "peer": true + }, + "node_modules/@openfeature/server-sdk": { + "version": "1.23.0", + "resolved": "https://registry.npmjs.org/@openfeature/server-sdk/-/server-sdk-1.23.0.tgz", + "integrity": "sha512-JWeLvltJIV0AFgOfbw7hK9b9Rw/5wWq+RMhCIU9sJtAqarxr8hSPglG+JAGGhYdElAz3Qwe9W3ApWyPNkQEyqg==", + "license": "Apache-2.0", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@openfeature/core": "^1.12.0" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/api-logs": { + "version": "0.223.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.223.0.tgz", + "integrity": "sha512-Oepm6etVPFCn0VWB1t833iOTgz1eYBDUPxcrOR/XvwzD1+Ag9VzSPSrrKAFNJ/haatj+8CXbG47pZXvdNQKDJw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@oxc-parser/binding-android-arm-eabi": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.132.0.tgz", + "integrity": "sha512-KrLaPWa5c9Y7LkW+rKkaUE3y7DBDrQtaf7rlsSDfv6KAHUjgzAIRA761Lrrp6//Yd/Rlie/yEOt9YENCoJnOcw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-android-arm64": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm64/-/binding-android-arm64-0.132.0.tgz", + "integrity": "sha512-SThDrSeamB/kG2+NxcJ5/wSLcV6dUqDknrPLqFYQ0ST/55mtBP4M7Q/f3QbubH6aAd11wpzZn/nwbVRSdobOpg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-arm64": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-arm64/-/binding-darwin-arm64-0.132.0.tgz", + "integrity": "sha512-Lc0f/TYoKBghE5/2Gsv7bLXk+TJZunx2Tf61X8hG4ARXdc8UYI26dCGccFSd1AyFbK3jfaNXtMnupggDbjPXdQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-x64": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-x64/-/binding-darwin-x64-0.132.0.tgz", + "integrity": "sha512-RG2eJIpf7C21z9HSSXFw1bTArdpKe7Y4fwcJTwRq1yCSe1vSavaN9GA1sm9KqzemTLAGVktQ+7qBTGp0vQeUZg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-freebsd-x64": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-freebsd-x64/-/binding-freebsd-x64-0.132.0.tgz", + "integrity": "sha512-wQIPntPLtJ8NcBpvKPbEv3NqzV6k8eP8tP/jE9Rg8HTg/j7urZGFSsTCPCW5k77Qfw2DM4vRvc9p3I4yq/Shvw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-gnueabihf": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.132.0.tgz", + "integrity": "sha512-PixKEpeSe3yxQWqNyOCBALRYc72+Tj7ILDofUl3iXo25cVOzLA6jHUhmOINRtWIPh7dbUie3QNeabwaQpZTw6w==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-musleabihf": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.132.0.tgz", + "integrity": "sha512-sCR+DzGHlyHKnbA2z9zWjTUhIo8Sy0enJl4RDsBwPmkxYynPatpwOAWe8W5127SlW0boqUWHGtr1NWn5UwIhXQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-gnu": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.132.0.tgz", + "integrity": "sha512-sQBix5P2cW+IpzTcCwYxnh9yALrKSIkKJThspBvMGcygSMnbzkSvhN7SfuX1hvBk8y1XEChsdkU3ET0V5DmzUw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-musl": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.132.0.tgz", + "integrity": "sha512-WozHg3Kc//8Sk756HXXgMbEAvqtG+Lzb9JOojwQzIGDtN78Az2dLttkb71akWYUF/8IgYfDSlfKh4Uot8is5Vw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-ppc64-gnu": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.132.0.tgz", + "integrity": "sha512-CmX/ulNBOEwWTyVRmcpYKAcAizW6+OjtLJgo7fXoL9OqQvjF4VER8tPomv44vwzfSCy1BHbsB0ZlZYzYJNj4cA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-gnu": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.132.0.tgz", + "integrity": "sha512-j9oQS+hM90SdhviNGWbPgT4+Rlq+ac++q/zjgwPD1mVHgxHzATvoRGtDx0sXGmFOQ9J9YkwAhYGb5MAHL6TAsA==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-musl": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.132.0.tgz", + "integrity": "sha512-bLz+Xi+Agnfmd7kWPEsSVwCn2k4EyIalZkNBcQ0OGIv9rqn8VgCPLNd03tM9mKX/5TdlvDXalz0q71BIrOPNqg==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-s390x-gnu": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.132.0.tgz", + "integrity": "sha512-U6t2qbJU0ypTfyj9QV3W1Y6mITDTL8ai/OR6NUn85vyHthOvobKWgXzU4tu0EskSzlpuVFz1g0jFGulDIUKHxQ==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-gnu": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.132.0.tgz", + "integrity": "sha512-WcEaSNHFk8yz5YFlQQAlhq6jOFmZBB/RKE7uzhyCIf+pF1Lmv9gUH4221mle2Gd9iHyWT3ySNph8yZgb1xYdWg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-musl": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-musl/-/binding-linux-x64-musl-0.132.0.tgz", + "integrity": "sha512-iQrV4iJzQgRwK3BWRmQl1C3C6g3wYpXN2WLdQdyR+efoUnncdShZAVp9OgcojtlD3MDRbuOMGG3SjxF4fL4nlQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-openharmony-arm64": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-openharmony-arm64/-/binding-openharmony-arm64-0.132.0.tgz", + "integrity": "sha512-FWzmUGrZ6GUby4U7WIwcCtab6tdmlTO3xTRRKyb5kjIJVEiaUAT8animUG/nK8ZCA8gkRkPOTId4rl6uTqUmJQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-wasm32-wasi": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-wasm32-wasi/-/binding-wasm32-wasi-0.132.0.tgz", + "integrity": "sha512-TlbMppxJI5CjWDes0QaP6G3aneVg1yikBu5QYI+DUShF9WDL66ccgKFNNGmi/Wybtszw6hxwAvv76T4DaPKnHw==", + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.10.0", + "@emnapi/runtime": "1.10.0", + "@napi-rs/wasm-runtime": "^1.1.4" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-arm64-msvc": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.132.0.tgz", + "integrity": "sha512-RH/NbFjGKqdUAUi7Oh3LQPxUk2hsWFEEQ38HSnbRQT8QjBZFKqL1fMbmsB3N4jy/KPh9iX94+9dmkEMBBbambw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-ia32-msvc": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.132.0.tgz", + "integrity": "sha512-JUr4jQY9jxoIB/YTLXr6XofSi5xikj6p5/Ns1h0VOBDT0j1jKU+kMsv2xxv51RwnETcXpA1Yw/9oUAfcqfaqEA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-x64-msvc": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.132.0.tgz", + "integrity": "sha512-2dapgHpA5X8DSXF4AU36hJWYf6zP0tKjMXFRAZFBD62pkevW/uhFDXoFH9Y/3Fd2EtDrw5ByNnR1wVE9X9y0SQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.132.0.tgz", + "integrity": "sha512-FESMOxil5Se014ui/Eq8fT5uHJo6nIRwH0PfJrZJXs6Gek3ZVFOrpUv3YIZT20m+extU98Hg1Ym72U58rlsxUQ==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0", + "optional": true + }, + "node_modules/cjs-module-lexer": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.3.0.tgz", + "integrity": "sha512-lmNyBzi6iYiqyrExTctfmjd8tInx+dHu9PBomTfH5RXS53c27JMFJgzNv5TyAnm3PgGf+MLy0+Ws41/HlVxdKQ==", + "license": "MIT" + }, + "node_modules/dc-polyfill": { + "version": "0.1.11", + "resolved": "https://registry.npmjs.org/dc-polyfill/-/dc-polyfill-0.1.11.tgz", + "integrity": "sha512-TyyeGcjx0YeThAI9fTFtgsvj5qd4R+aGfVmXiUhevbgzWFDr7IK4tv4YjE6jaGzLHQTchk4h7DHdr5q4WGgaZw==", + "license": "MIT", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/dd-trace": { + "version": "6.25.0", + "resolved": "https://registry.npmjs.org/dd-trace/-/dd-trace-6.25.0.tgz", + "integrity": "sha512-Vu2h/S7OiU5BlS/grr4DRJLM8DOZYPEQE5qbYujo+KQXNE1GFW39uCRC5Zq6W4McscMzHd9C/Ur6eBZydwm82A==", + "license": "(Apache-2.0 OR BSD-3-Clause)", + "dependencies": { + "dc-polyfill": "^0.1.11", + "import-in-the-middle": "3.5.3", + "opentracing": ">=0.14.7" + }, + "engines": { + "node": ">=22" + }, + "optionalDependencies": { + "@datadog/libdatadog": "^0.21.0", + "@datadog/libdatadog-extras": "^0.21.0", + "@datadog/native-appsec": "11.0.3", + "@datadog/native-iast-taint-tracking": "4.2.1", + "@datadog/native-metrics": "4.0.0", + "@datadog/pprof": "5.20.1", + "@datadog/wasm-js-rewriter": "5.0.4", + "@opentelemetry/api": ">=1.4.1 <1.11.0", + "@opentelemetry/api-logs": "<1.0.0", + "oxc-parser": "^0.132.0" + } + }, + "node_modules/es-module-lexer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-3.0.5.tgz", + "integrity": "sha512-RNq2lKJw53c7z9QRHeiKeA6Ez0oikOqiBGdmxQhKDxEiOX1g5QJR4IoFVwicn8uCZcRWNrXC3NZaJihgK7aEbg==", + "license": "MIT" + }, + "node_modules/import-in-the-middle": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.5.3.tgz", + "integrity": "sha512-usm/IiY63VtOyx/dm7uEoZV+EsanCDmwRUroQZIkFLGu1NVXZ8mZqIOhaN4QIJ7EsbMTuQbJXwCySCx+ozMA8g==", + "license": "Apache-2.0", + "dependencies": { + "cjs-module-lexer": "^2.2.0", + "es-module-lexer": "^3.0.3", + "module-details-from-path": "^1.0.4" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", + "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==", + "license": "MIT" + }, + "node_modules/node-addon-api": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", + "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==", + "license": "MIT", + "optional": true + }, + "node_modules/node-gyp-build": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-3.9.0.tgz", + "integrity": "sha512-zLcTg6P4AbcHPq465ZMFNXx7XpKKJh+7kkN699NiQWisR2uWYOWNWqRHAmbnmKiL4e9aLSlmy5U7rEMUXV59+A==", + "license": "MIT", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/opentracing": { + "version": "0.14.7", + "resolved": "https://registry.npmjs.org/opentracing/-/opentracing-0.14.7.tgz", + "integrity": "sha512-vz9iS7MJ5+Bp1URw8Khvdyw1H/hGvzHWlKQ7eRrQojSCDL1/SrWfrY9QebLw97n2deyRtzHRC3MkQfVNUCo91Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/oxc-parser": { + "version": "0.132.0", + "resolved": "https://registry.npmjs.org/oxc-parser/-/oxc-parser-0.132.0.tgz", + "integrity": "sha512-+0LAPHaqtfQlvWdpaAa09SmOaZZgP8C552xosEkGJ4+ruEwP1Vgx+sqBgcBCNfR6KDCmagGOZTde8wmAvcI/Hg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@oxc-project/types": "^0.132.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "optionalDependencies": { + "@oxc-parser/binding-android-arm-eabi": "0.132.0", + "@oxc-parser/binding-android-arm64": "0.132.0", + "@oxc-parser/binding-darwin-arm64": "0.132.0", + "@oxc-parser/binding-darwin-x64": "0.132.0", + "@oxc-parser/binding-freebsd-x64": "0.132.0", + "@oxc-parser/binding-linux-arm-gnueabihf": "0.132.0", + "@oxc-parser/binding-linux-arm-musleabihf": "0.132.0", + "@oxc-parser/binding-linux-arm64-gnu": "0.132.0", + "@oxc-parser/binding-linux-arm64-musl": "0.132.0", + "@oxc-parser/binding-linux-ppc64-gnu": "0.132.0", + "@oxc-parser/binding-linux-riscv64-gnu": "0.132.0", + "@oxc-parser/binding-linux-riscv64-musl": "0.132.0", + "@oxc-parser/binding-linux-s390x-gnu": "0.132.0", + "@oxc-parser/binding-linux-x64-gnu": "0.132.0", + "@oxc-parser/binding-linux-x64-musl": "0.132.0", + "@oxc-parser/binding-openharmony-arm64": "0.132.0", + "@oxc-parser/binding-wasm32-wasi": "0.132.0", + "@oxc-parser/binding-win32-arm64-msvc": "0.132.0", + "@oxc-parser/binding-win32-ia32-msvc": "0.132.0", + "@oxc-parser/binding-win32-x64-msvc": "0.132.0" + } + }, + "node_modules/pprof-format": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/pprof-format/-/pprof-format-2.4.0.tgz", + "integrity": "sha512-7SDtSvsD996RFtlODgEmCR+GAfC3Dx6zlnef7duB1QNAkOStz+VAV60Ie/OQrkEijmBmcOZlKK0KQ/Oupd1frw==", + "license": "MIT", + "optional": true + }, + "node_modules/source-map": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0.tgz", + "integrity": "sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": ">= 12" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD", + "optional": true + } + } +} diff --git a/examples/feature-flags-config-cache/package.json b/examples/feature-flags-config-cache/package.json new file mode 100644 index 000000000..5f51de537 --- /dev/null +++ b/examples/feature-flags-config-cache/package.json @@ -0,0 +1,16 @@ +{ + "name": "feature-flags-config-cache-example", + "private": true, + "description": "Lambda-style handler that evaluates Datadog feature flags from the Extension's configuration cache", + "main": "handler.js", + "scripts": { + "test": "node --test --test-concurrency=1 test/*.test.js" + }, + "dependencies": { + "@openfeature/server-sdk": "1.23.0", + "dd-trace": "6.25.0" + }, + "engines": { + "node": ">=20" + } +} diff --git a/examples/feature-flags-config-cache/test/config-cache.test.js b/examples/feature-flags-config-cache/test/config-cache.test.js new file mode 100644 index 000000000..e83c6c8ff --- /dev/null +++ b/examples/feature-flags-config-cache/test/config-cache.test.js @@ -0,0 +1,347 @@ +'use strict' + +// Process-level tests: the real Extension binary (test-mode build) caches the +// configuration from a fake CDN, and the real dd-trace flag provider +// evaluates it in a separate process per simulated execution environment. +// Nothing here runs in AWS Lambda. + +const assert = require('node:assert/strict') +const { fork, spawn } = require('node:child_process') +const fs = require('node:fs') +const http = require('node:http') +const os = require('node:os') +const path = require('node:path') +const { setTimeout: sleep } = require('node:timers/promises') +const { afterEach, test } = require('node:test') + +const { FLAG_CONFIG_PATH } = require('../extension-config') + +const BOTTLECAP_BIN = process.env.BOTTLECAP_BIN ?? + path.join(__dirname, '../../../bottlecap/target/debug/bottlecap-test-mode') +const FIXTURES = { + v1: fs.readFileSync(path.join(__dirname, '../fixtures/ufc-v1.json'), 'utf8'), + v2: fs.readFileSync(path.join(__dirname, '../fixtures/ufc-v2.json'), 'utf8'), + invalid: '502 Bad Gateway', +} +const US_USER = { userId: 'user-1', country: 'US' } +const FR_USER = { userId: 'user-2', country: 'France' } + +const cleanups = [] +afterEach(async () => { + while (cleanups.length) await cleanups.pop()() +}) + +function listen (handler) { + const server = http.createServer(handler) + return new Promise(resolve => server.listen(0, '127.0.0.1', () => { + cleanups.push(() => new Promise(r => { server.closeAllConnections(); server.close(r) })) + resolve({ server, url: `http://127.0.0.1:${server.address().port}` }) + })) +} + +async function freePort () { + const server = http.createServer() + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const { port } = server.address() + await new Promise(resolve => server.close(resolve)) + return port +} + +/** Stands in for the Datadog CDN and records every request it gets. */ +async function startCdn () { + const cdn = { mode: 'v1', delayMs: 0, requests: [] } + const { url } = await listen(async (req, res) => { + const { pathname, searchParams } = new URL(req.url, 'http://x') + cdn.requests.push({ + path: pathname, + apiKey: req.headers['dd-api-key'], + env: searchParams.get('dd_env'), + ifNoneMatch: req.headers['if-none-match'], + }) + if (cdn.delayMs) await sleep(cdn.delayMs) + if (cdn.mode === 'down') return res.writeHead(503).end() + const etag = `"${cdn.mode}"` + if (req.headers['if-none-match'] === etag) return res.writeHead(304, { ETag: etag }).end() + res.writeHead(200, { 'Content-Type': 'application/json', ETag: etag }).end(FIXTURES[cdn.mode]) + }) + cdn.url = url + return cdn +} + +/** Stands in for the trace agent endpoints the tracer reports to. */ +async function startAgent () { + const agent = { requests: [] } + const { url } = await listen((req, res) => { + let body = '' + req.on('data', chunk => { body += chunk }) + req.on('end', () => { + agent.requests.push({ method: req.method, path: req.url, body }) + if (req.url.startsWith('/info')) { + return res.writeHead(200, { 'Content-Type': 'application/json' }) + .end(JSON.stringify({ endpoints: ['/v0.4/traces', '/evp_proxy/v2/'] })) + } + res.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') + }) + }) + agent.url = url + return agent +} + +/** Counts any request: the SDK's own upstream poller would land here. */ +async function startTrap () { + const trap = { hits: 0 } + const { url } = await listen((req, res) => { trap.hits++; res.writeHead(500).end() }) + trap.url = url + return trap +} + +/** The real Extension, built with `cargo build --features test-mode`. */ +async function startExtension (cdn, env = {}) { + assert.ok(fs.existsSync(BOTTLECAP_BIN), `build ${BOTTLECAP_BIN} first (see README)`) + const port = await freePort() + const child = spawn(BOTTLECAP_BIN, [], { + env: { + PATH: process.env.PATH, + DD_APM_RECEIVER_PORT: String(port), + DD_TESTMODE_FEATURE_FLAGS_CDN_URL: cdn.url, + DD_APM_DD_URL: 'http://127.0.0.1:9', + DD_ENV: 'prod', + DD_LOG_LEVEL: 'error', + // The fake CDN speaks plain HTTP/1.1. + DD_HTTP_PROTOCOL: 'http1', + DD_FEATURE_FLAGS_EXTENSION_CACHE_ENABLED: 'true', + ...env, + }, + stdio: ['ignore', 'ignore', 'pipe'], + }) + let stderr = '' + child.stderr.on('data', chunk => { stderr += chunk }) + cleanups.push(() => new Promise(resolve => { + if (child.exitCode !== null || child.signalCode !== null) return resolve() + child.once('exit', resolve) + child.kill('SIGKILL') + })) + const url = `http://127.0.0.1:${port}` + for (let i = 0; i < 100; i++) { + const status = await fetch(`${url}/info`).then(r => r.status, () => 0) + if (status === 200) return { url, child, stderr: () => stderr } + await sleep(50) + } + throw new Error(`extension did not start: ${stderr}`) +} + +/** A fresh Node process with the real tracer: one execution environment. */ +async function startEnvironment (extension, agent, trap, env = {}) { + const child = fork(path.join(__dirname, 'environment.js'), [], { + env: { + PATH: process.env.PATH, + DD_TRACE_AGENT_URL: agent.url, + DD_FEATURE_FLAGS_EXTENSION_URL: extension.url, + // No upstream poller in the SDK: Remote Config is off, and the + // agentless URL (unused for this source) points at the trap. + DD_FEATURE_FLAGS_CONFIGURATION_SOURCE: 'remote_config', + DD_REMOTE_CONFIGURATION_ENABLED: 'false', + DD_FEATURE_FLAGS_CONFIGURATION_SOURCE_AGENTLESS_BASE_URL: trap.url, + DD_ENV: 'prod', + DD_SERVICE: 'ffe-config-cache-example', + DD_TRACE_STARTUP_LOGS: 'false', + DD_INSTRUMENTATION_TELEMETRY_ENABLED: 'false', + ...env, + }, + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], + }) + cleanups.push(() => new Promise(resolve => { + if (child.exitCode !== null || child.signalCode !== null) return resolve() + child.once('exit', resolve) + child.kill('SIGKILL') + })) + await new Promise((resolve, reject) => { + child.once('message', resolve) + child.once('exit', code => reject(new Error(`environment exited ${code}`))) + }) + let next = 0 + const invoke = event => new Promise((resolve, reject) => { + const id = next++ + const onMessage = message => { + if (message.id !== id) return + child.off('message', onMessage) + message.error ? reject(new Error(message.error)) : resolve(message.result) + } + child.on('message', onMessage) + child.send({ id, event }) + }) + return { invoke, child } +} + +async function waitFor (predicate, timeoutMs, message) { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + if (predicate()) return + await sleep(25) + } + assert.fail(message()) +} + +async function fixtures () { + return { cdn: await startCdn(), agent: await startAgent(), trap: await startTrap() } +} + +const configRequests = cdn => cdn.requests.filter(r => r.path === FLAG_CONFIG_PATH) + +test('the real SDK evaluates extension config and makes no upstream config request', async () => { + const { cdn, agent, trap } = await fixtures() + const extension = await startExtension(cdn) + const env = await startEnvironment(extension, agent, trap) + + const us = await env.invoke(US_USER) + const fr = await env.invoke(FR_USER) + + assert.equal(us.value, true) + assert.equal(us.variant, 'on') + assert.equal(fr.value, false) + assert.equal(fr.variant, 'off') + assert.equal(trap.hits, 0, 'the SDK contacted its agentless endpoint') + assert.equal(agent.requests.filter(r => r.path.startsWith('/v0.7/config')).length, 0) + const requests = configRequests(cdn) + assert.equal(requests.length, 1, JSON.stringify(requests)) + assert.equal(requests[0].apiKey, 'stub-key') + assert.equal(requests[0].env, 'prod') +}) + +test('warm invocations reuse the fresh cached config', async () => { + const { cdn, agent, trap } = await fixtures() + const extension = await startExtension(cdn) + const env = await startEnvironment(extension, agent, trap) + + const statuses = [] + for (let i = 0; i < 50; i++) statuses.push((await env.invoke(US_USER)).config.status) + + assert.deepEqual(new Set(statuses.slice(1)), new Set([304])) + assert.equal(configRequests(cdn).length, 1) +}) + +test('concurrent reads consolidate the upstream fetch', async () => { + const { cdn } = await fixtures() + cdn.delayMs = 300 + const extension = await startExtension(cdn) + + const replies = await Promise.all(Array.from({ length: 32 }, () => + fetch(extension.url + FLAG_CONFIG_PATH).then(async r => ({ status: r.status, body: await r.text() })))) + + for (const reply of replies) { + assert.equal(reply.status, 200) + assert.equal(reply.body, FIXTURES.v1) + } + // The Extension's startup prefetch and all 32 reads share one request. + assert.equal(configRequests(cdn).length, 1) +}) + +test('an accepted update changes the real SDK evaluation', async () => { + const { cdn, agent, trap } = await fixtures() + const extension = await startExtension(cdn, { DD_FEATURE_FLAGS_EXTENSION_CACHE_TTL_SECONDS: '1' }) + const env = await startEnvironment(extension, agent, trap) + assert.equal((await env.invoke(FR_USER)).value, false) + + cdn.mode = 'v2' + // Idle past the TTL. The Extension runs no refresh timer, so for the cache + // this is the same as a frozen environment: the next read sees the age. + await sleep(1200) + const after = await env.invoke(FR_USER) + + assert.equal(after.value, true) + assert.equal(after.variant, 'on') + assert.equal(after.config.status, 200) + const requests = configRequests(cdn) + assert.equal(requests.length, 2) + assert.equal(requests[1].ifNoneMatch, '"v1"') +}) + +test('invalid and failed refreshes keep the accepted config until max stale', async () => { + const { cdn, agent, trap } = await fixtures() + const extension = await startExtension(cdn, { + DD_FEATURE_FLAGS_EXTENSION_CACHE_TTL_SECONDS: '1', + DD_FEATURE_FLAGS_EXTENSION_CACHE_MAX_STALE_SECONDS: '3', + }) + const env = await startEnvironment(extension, agent, trap) + assert.equal((await env.invoke(FR_USER)).value, false) + + cdn.mode = 'invalid' + await sleep(1200) + const corrupted = await env.invoke(FR_USER) + assert.equal(corrupted.value, false) + assert.equal(corrupted.config.cache, 'stale') + + cdn.mode = 'down' + await sleep(2500) + // Past max stale with Datadog down: the Extension stops serving the old + // config (5xx), and the SDK keeps evaluating with the snapshot it has. + const outage = await env.invoke(FR_USER) + assert.ok(outage.config.status >= 500, `status ${outage.config.status}`) + assert.equal(outage.value, false) + assert.equal(outage.variant, 'off') +}) + +test('each fresh execution environment acquires its own config', async () => { + const { cdn, agent, trap } = await fixtures() + for (let i = 0; i < 3; i++) { + const extension = await startExtension(cdn) + const env = await startEnvironment(extension, agent, trap) + assert.equal((await env.invoke(US_USER)).value, true) + extension.child.kill('SIGKILL') + env.child.kill('SIGKILL') + } + assert.equal(configRequests(cdn).length, 3) +}) + +test('a fresh bootstrap file replaces the initial acquisition', async () => { + const { cdn, agent, trap } = await fixtures() + const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'ffe-')), 'flags.json') + const bootstrap = JSON.parse(FIXTURES.v1) + bootstrap.data.attributes.createdAt = new Date().toISOString() + fs.writeFileSync(file, JSON.stringify(bootstrap)) + const extension = await startExtension(cdn, { DD_FEATURE_FLAGS_EXTENSION_CACHE_BOOTSTRAP_FILE: file }) + const env = await startEnvironment(extension, agent, trap) + + const us = await env.invoke(US_USER) + + assert.equal(us.value, true) + assert.equal(us.config.cache, 'fresh') + assert.equal(configRequests(cdn).length, 0) +}) + +test('exposures are still reported through the trace agent', async () => { + const { cdn, agent, trap } = await fixtures() + const extension = await startExtension(cdn) + const env = await startEnvironment(extension, agent, trap) + + await env.invoke(US_USER) + + const exposures = () => agent.requests.filter(r => r.path.includes('/api/v2/exposures')) + await waitFor(() => exposures().length > 0, 10_000, + () => `no exposure request: ${agent.requests.map(r => r.path).join(', ')}`) + const body = exposures().map(r => r.body).join('\n') + assert.match(body, /kill-switch/) + assert.match(body, /user-1/) +}) + +test('zero code: the SDK poller reads the Extension, not the CDN', async () => { + const { cdn, agent, trap } = await fixtures() + const extension = await startExtension(cdn) + const env = await startEnvironment(extension, agent, trap, { + DD_FEATURE_FLAGS_CONFIGURATION_SOURCE: 'agentless', + DD_FEATURE_FLAGS_CONFIGURATION_SOURCE_AGENTLESS_BASE_URL: extension.url, + DD_FEATURE_FLAGS_CONFIGURATION_SOURCE_AGENTLESS_POLL_INTERVAL_SECONDS: '1', + }) + + // The SDK's first poll of the Extension makes the provider ready. + let us + for (let i = 0; i < 50 && us?.value !== true; i++) { + us = await env.invoke(US_USER) + await sleep(100) + } + assert.equal(us.value, true, JSON.stringify(us)) + // Three SDK polls of the Extension, still one CDN request. + await sleep(3000) + assert.equal(configRequests(cdn).length, 1) + assert.equal(trap.hits, 0) +}) diff --git a/examples/feature-flags-config-cache/test/environment.js b/examples/feature-flags-config-cache/test/environment.js new file mode 100644 index 000000000..225062487 --- /dev/null +++ b/examples/feature-flags-config-cache/test/environment.js @@ -0,0 +1,14 @@ +'use strict' + +// One simulated execution environment: loads the handler once, then runs the +// invocations the test sends over IPC. +const { handler } = require('../handler') + +process.on('message', async ({ id, event }) => { + try { + process.send({ id, result: await handler(event) }) + } catch (error) { + process.send({ id, error: String(error) }) + } +}) +process.send({ ready: true })