diff --git a/lambda/src/aws.rs b/lambda/src/aws.rs index b8b13bd..56f1dde 100644 --- a/lambda/src/aws.rs +++ b/lambda/src/aws.rs @@ -143,31 +143,23 @@ impl MetricsApi for Clients { Ok(db_instances) } - async fn list_functions(&self) -> Result, Error> { - let mut pages = self.lambda.list_functions().into_paginator().send(); - let mut functions = Vec::new(); - while let Some(page) = pages.next().await { - for function in page.map_err(sdk_error!(aws_sdk_lambda))?.functions() { - if let Some(name) = function.function_name() { - functions.push((name.to_string(), lambda_function_properties(function))); - } + async fn get_function(&self, name: &str) -> Result, Error> { + match self.lambda.get_function().function_name(name).send().await { + Ok(output) => Ok(Some( + output + .configuration() + .map(lambda_function_properties) + .unwrap_or_default(), + )), + Err(err) + if err + .as_service_error() + .is_some_and(|e| e.is_resource_not_found_exception()) => + { + Ok(None) } + Err(err) => Err(sdk_error!(aws_sdk_lambda)(err)), } - Ok(functions) - } - - async fn get_function(&self, name: &str) -> Result { - let output = self - .lambda - .get_function() - .function_name(name) - .send() - .await - .map_err(sdk_error!(aws_sdk_lambda))?; - Ok(output - .configuration() - .map(lambda_function_properties) - .unwrap_or_default()) } } diff --git a/lambda/src/fake.rs b/lambda/src/fake.rs index b8d8d2f..383b504 100644 --- a/lambda/src/fake.rs +++ b/lambda/src/fake.rs @@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Mutex; +use std::time::Duration; use serde_json::Value; @@ -29,9 +30,9 @@ struct State { instances: HashMap, Vec<(String, Fields)>>, volumes: HashMap, Vec<(String, Fields)>>, db_instances: HashMap, Vec<(String, Fields)>>, - functions: Vec<(String, Fields)>, function: HashMap, failing: HashSet<&'static str>, + delays: HashMap<&'static str, Duration>, calls: HashMap<&'static str, usize>, } @@ -72,6 +73,14 @@ impl FakeApi { self.state.lock().unwrap().failing.insert(api); } + pub fn recover(&self, api: &'static str) { + self.state.lock().unwrap().failing.remove(api); + } + + pub fn delay(&self, api: &'static str, delay: Duration) { + self.state.lock().unwrap().delays.insert(api, delay); + } + pub fn calls(&self, api: &'static str) -> usize { self.state .lock() @@ -135,17 +144,17 @@ impl MetricsApi for FakeApi { .unwrap_or_default()) } - async fn list_functions(&self) -> Result, Error> { - let state = self.call("list_functions")?; - Ok(state.functions.clone()) - } - - async fn get_function(&self, name: &str) -> Result { - let state = self.call("get_function")?; - state - .function - .get(name) - .cloned() - .ok_or_else(|| format!("ResourceNotFoundException: {name}").into()) + async fn get_function(&self, name: &str) -> Result, Error> { + let (delay, result) = { + let state = self.call("get_function")?; + ( + state.delays.get("get_function").copied(), + state.function.get(name).cloned(), + ) + }; + if let Some(delay) = delay { + std::thread::sleep(delay); + } + Ok(result) } } diff --git a/lambda/src/metrics.rs b/lambda/src/metrics.rs index 6788cfe..05ffdcf 100644 --- a/lambda/src/metrics.rs +++ b/lambda/src/metrics.rs @@ -1,8 +1,8 @@ //! Enriches CloudWatch Metric Stream records with the tags and properties of the resource they //! measure. Each Firehose record is newline-delimited JSON, one metric per line. Tags come from the -//! Resource Groups Tagging API; properties (instance type, engine, runtime, ...) for EC2, EBS, RDS -//! and Lambda come from bulk listings cached in memory, with one-off lookups for resources the -//! listing missed. +//! Resource Groups Tagging API; properties (instance type, engine, runtime, ...) for EC2, EBS and +//! RDS come from bulk listings cached in memory, with one-off lookups for resources the listing +//! missed, while Lambda functions are fetched on demand per function name and cached in memory. use std::collections::HashMap; use std::future::Future; @@ -17,8 +17,10 @@ use crate::firehose::{Event, InputRecord, OutputRecord, Response}; use crate::tags::{TagApi, TagCache, add_tags, unique}; use crate::{Error, Fields}; -/// After a listing fails it is not retried for this long, to avoid a retry storm. +/// After a listing or lookup fails it is not retried for this long, to avoid a retry storm. const ERROR_TTL: Duration = Duration::from_secs(60); +/// Time budget per Firehose invocation for uncached Lambda `GetFunction` lookups. +const FUNCTION_LOOKUP_BUDGET: Duration = Duration::from_secs(30); /// Each call returns `(resource id, properties)` pairs. `id: None` lists every running instance, /// in-use volume or DB instance; `Some` looks up that one resource. @@ -35,8 +37,11 @@ pub trait MetricsApi: TagApi { &self, id: Option<&str>, ) -> impl Future, Error>> + Send; - fn list_functions(&self) -> impl Future, Error>> + Send; - fn get_function(&self, name: &str) -> impl Future> + Send; + /// Returns `Ok(None)` when AWS reports `ResourceNotFoundException`. + fn get_function( + &self, + name: &str, + ) -> impl Future, Error>> + Send; } /// Properties by resource id. A failed one-off lookup caches empty properties, so it is not repeated. @@ -53,6 +58,50 @@ impl PropertyCache { } } +/// Lambda properties cached per function name, each with its own expiry. +#[derive(Default)] +pub struct FunctionCache { + entries: HashMap, +} + +struct FunctionEntry { + properties: Fields, + expires: Instant, +} + +impl FunctionCache { + pub fn get(&self, name: &str) -> Option<&Fields> { + self.entries + .get(name) + .filter(|entry| entry.expires > Instant::now()) + .map(|entry| &entry.properties) + } + + pub fn stale(&self, name: &str) -> Option<&Fields> { + self.entries.get(name).map(|entry| &entry.properties) + } + + pub fn insert(&mut self, name: String, properties: Fields, expires: Instant) { + self.entries.insert( + name, + FunctionEntry { + properties, + expires, + }, + ); + } + + pub fn record_error(&mut self, name: &str, expires: Instant) -> Fields { + if let Some(entry) = self.entries.get_mut(name) { + entry.expires = expires; + entry.properties.clone() + } else { + self.insert(name.to_string(), Fields::new(), expires); + Fields::new() + } + } +} + pub struct MetricsEnrichment { pub config: Config, pub tags: TagCache, @@ -60,7 +109,8 @@ pub struct MetricsEnrichment { pub instances: PropertyCache, pub volumes: PropertyCache, pub db_instances: PropertyCache, - pub functions: PropertyCache, + pub functions: FunctionCache, + pub function_lookup_budget: Duration, } enum Decoded { @@ -79,7 +129,8 @@ impl MetricsEnrichment { instances: PropertyCache::default(), volumes: PropertyCache::default(), db_instances: PropertyCache::default(), - functions: PropertyCache::default(), + functions: FunctionCache::default(), + function_lookup_budget: FUNCTION_LOOKUP_BUDGET, } } @@ -100,6 +151,7 @@ impl MetricsEnrichment { .log(format!("Fetching tags for {} unique ARNs", arns.len())); self.tags.prefetch(api, &arns, &self.config).await; + let lookup_deadline = Instant::now() + self.function_lookup_budget; let mut records = Vec::with_capacity(decoded.len()); for d in decoded { records.push(match d { @@ -107,7 +159,13 @@ impl MetricsEnrichment { Decoded::Enrich { record, metrics } => { let mut lines = String::new(); for (mut metric, arn) in metrics { - self.enrich_record(api, &mut metric, arn.as_deref()).await; + self.enrich_record_until( + api, + &mut metric, + arn.as_deref(), + Some(lookup_deadline), + ) + .await; lines.push_str(&Value::Object(metric).to_string()); lines.push('\n'); } @@ -160,10 +218,20 @@ impl MetricsEnrichment { api: &impl MetricsApi, metric: &mut Fields, arn: Option<&str>, + ) { + self.enrich_record_until(api, metric, arn, None).await; + } + + async fn enrich_record_until( + &mut self, + api: &impl MetricsApi, + metric: &mut Fields, + arn: Option<&str>, + lookup_deadline: Option, ) { add_tags(metric, self.tags.get(arn)); if let Some(properties) = self - .properties_for_metric(api, metric) + .properties_for_metric_until(api, metric, lookup_deadline) .await .filter(|p| !p.is_empty()) { @@ -175,6 +243,15 @@ impl MetricsEnrichment { &mut self, api: &impl MetricsApi, metric: &Fields, + ) -> Option { + self.properties_for_metric_until(api, metric, None).await + } + + async fn properties_for_metric_until( + &mut self, + api: &impl MetricsApi, + metric: &Fields, + lookup_deadline: Option, ) -> Option { let namespace = metric .get("namespace") @@ -208,9 +285,7 @@ impl MetricsEnrichment { } "AWS/Lambda" => { let name = dimension("FunctionName")?; - self.load_functions(api).await; - self.backfill_function(api, &name).await; - self.functions.items.get(&name).cloned() + Some(self.function_properties(api, &name, lookup_deadline).await) } _ => None, } @@ -259,17 +334,6 @@ impl MetricsEnrichment { .await; } - pub async fn load_functions(&mut self, api: &impl MetricsApi) { - let config = self.config.clone(); - load( - &mut self.functions, - &config, - "Lambda functions", - api.list_functions(), - ) - .await; - } - pub async fn backfill_instance(&mut self, api: &impl MetricsApi, id: &str) { let config = self.config.clone(); backfill(&mut self.instances, &config, id, |id| { @@ -294,12 +358,47 @@ impl MetricsEnrichment { .await; } - pub async fn backfill_function(&mut self, api: &impl MetricsApi, name: &str) { - let config = self.config.clone(); - backfill(&mut self.functions, &config, name, |name| async move { - Ok(vec![(name.to_string(), api.get_function(name).await?)]) - }) - .await; + pub async fn function_properties( + &mut self, + api: &impl MetricsApi, + name: &str, + lookup_deadline: Option, + ) -> Fields { + if let Some(properties) = self.functions.get(name) { + return properties.clone(); + } + if lookup_deadline.is_some_and(|deadline| Instant::now() >= deadline) { + self.config.log(format!( + "Skipping Lambda function lookup for {name}: invocation budget reached" + )); + return self.functions.stale(name).cloned().unwrap_or_default(); + } + self.config + .log(format!("Fetching Lambda function properties for {name}")); + match api.get_function(name).await { + Ok(Some(properties)) => { + self.functions.insert( + name.to_string(), + properties.clone(), + Instant::now() + self.config.cache_ttl, + ); + properties + } + Ok(None) => { + self.functions.insert( + name.to_string(), + Fields::new(), + Instant::now() + self.config.cache_ttl, + ); + Fields::new() + } + Err(e) => { + self.config + .log(format!("Error fetching Lambda function {name}: {e}")); + self.functions + .record_error(name, Instant::now() + ERROR_TTL) + } + } } } @@ -521,20 +620,283 @@ mod tests { } #[tokio::test] - async fn backfills_a_function_the_listing_missed() { + async fn fetches_and_caches_function_properties_on_demand() { + let api = FakeApi::default(); + api.function("my-function", fields(&[("Runtime", "provided.al2023")])); + let mut enrichment = MetricsEnrichment::new(test_config()); + let record = metric( + json!({ "namespace": "AWS/Lambda", "dimensions": { "FunctionName": "my-function" } }), + ); + + let first = enrichment.properties_for_metric(&api, &record).await; + let second = enrichment.properties_for_metric(&api, &record).await; + + assert_eq!(first, Some(fields(&[("Runtime", "provided.al2023")]))); + assert_eq!(second, Some(fields(&[("Runtime", "provided.al2023")]))); + assert_eq!(api.calls("get_function"), 1); + } + + #[tokio::test] + async fn refreshes_expired_function_properties() { let api = FakeApi::default(); api.function("my-function", fields(&[("Runtime", "provided.al2023")])); let mut enrichment = MetricsEnrichment::new(test_config()); + enrichment.functions.insert( + "my-function".to_string(), + fields(&[("Runtime", "ruby3.3")]), + Instant::now() - Duration::from_secs(1), + ); let properties = enrichment .properties_for_metric( &api, - &metric(json!({ "namespace": "AWS/Lambda", "dimensions": { "FunctionName": "my-function" } })), + &metric( + json!({ "namespace": "AWS/Lambda", "dimensions": { "FunctionName": "my-function" } }), + ), ) .await; assert_eq!(properties, Some(fields(&[("Runtime", "provided.al2023")]))); - assert_eq!(api.calls("list_functions"), 1); + assert_eq!(api.calls("get_function"), 1); + } + + #[tokio::test] + async fn caches_function_lookup_errors_for_error_ttl_and_recovers() { + let api = FakeApi::default(); + api.function("my-function", fields(&[("Runtime", "provided.al2023")])); + api.fail("get_function"); + let mut enrichment = MetricsEnrichment::new(test_config()); + let record = metric( + json!({ "namespace": "AWS/Lambda", "dimensions": { "FunctionName": "my-function" } }), + ); + + assert_eq!( + enrichment.properties_for_metric(&api, &record).await, + Some(Fields::new()) + ); + let left = enrichment.functions.entries["my-function"].expires - Instant::now(); + assert!( + left > Duration::from_secs(55) && left <= Duration::from_secs(60), + "{left:?}" + ); + + assert_eq!( + enrichment.properties_for_metric(&api, &record).await, + Some(Fields::new()) + ); + assert_eq!(api.calls("get_function"), 1); + + enrichment.functions.insert( + "my-function".to_string(), + Fields::new(), + Instant::now() - Duration::from_secs(1), + ); + api.recover("get_function"); + assert_eq!( + enrichment.properties_for_metric(&api, &record).await, + Some(fields(&[("Runtime", "provided.al2023")])) + ); + assert_eq!(api.calls("get_function"), 2); + } + + #[tokio::test] + async fn keeps_stale_function_properties_when_refresh_fails() { + let api = FakeApi::default(); + api.function("my-function", fields(&[("Runtime", "nodejs22.x")])); + api.fail("get_function"); + let mut enrichment = MetricsEnrichment::new(test_config()); + enrichment.functions.insert( + "my-function".to_string(), + fields(&[("Runtime", "provided.al2023")]), + Instant::now() - Duration::from_secs(1), + ); + let record = metric( + json!({ "namespace": "AWS/Lambda", "dimensions": { "FunctionName": "my-function" } }), + ); + + assert_eq!( + enrichment.properties_for_metric(&api, &record).await, + Some(fields(&[("Runtime", "provided.al2023")])) + ); + let left = enrichment.functions.entries["my-function"].expires - Instant::now(); + assert!( + left > Duration::from_secs(55) && left <= Duration::from_secs(60), + "{left:?}" + ); + assert_eq!( + enrichment.properties_for_metric(&api, &record).await, + Some(fields(&[("Runtime", "provided.al2023")])) + ); + assert_eq!(api.calls("get_function"), 1); + + enrichment.functions.insert( + "my-function".to_string(), + fields(&[("Runtime", "provided.al2023")]), + Instant::now() - Duration::from_secs(1), + ); + api.recover("get_function"); + assert_eq!( + enrichment.properties_for_metric(&api, &record).await, + Some(fields(&[("Runtime", "nodejs22.x")])) + ); + assert_eq!(api.calls("get_function"), 2); + } + + #[tokio::test] + async fn clears_stale_properties_when_function_is_deleted() { + let api = FakeApi::default(); + let mut enrichment = MetricsEnrichment::new(test_config()); + enrichment.functions.insert( + "deleted-fn".to_string(), + fields(&[("Runtime", "provided.al2023")]), + Instant::now() - Duration::from_secs(1), + ); + let mut payload = metric( + json!({ "namespace": "AWS/Lambda", "dimensions": { "FunctionName": "deleted-fn" } }), + ); + + enrichment.enrich_record(&api, &mut payload, None).await; + + assert!(!payload.contains_key("properties")); + let left = enrichment.functions.entries["deleted-fn"].expires - Instant::now(); + assert!( + left > Duration::from_secs(595) && left <= Duration::from_secs(600), + "{left:?}" + ); + enrichment.enrich_record(&api, &mut payload, None).await; + assert_eq!(api.calls("get_function"), 1); + } + + #[tokio::test] + async fn skips_lambda_lookup_without_function_name_dimension() { + let api = FakeApi::default(); + let mut enrichment = MetricsEnrichment::new(test_config()); + + let properties = enrichment + .properties_for_metric( + &api, + &metric(json!({ "namespace": "AWS/Lambda", "dimensions": {} })), + ) + .await; + + assert_eq!(properties, None); + assert_eq!(api.calls("get_function"), 0); + } + + #[tokio::test] + async fn stops_function_lookups_when_invocation_budget_expires() { + let api = FakeApi::default(); + api.tags( + "arn:aws:lambda:us-east-1:123456789012:function:fn-1", + &[("Team", "core")], + ); + api.tags( + "arn:aws:lambda:us-east-1:123456789012:function:fn-3", + &[("Team", "core")], + ); + api.function("fn-1", fields(&[("Runtime", "provided.al2023")])); + api.function("fn-2", fields(&[("Runtime", "nodejs22.x")])); + api.function("fn-3", fields(&[("Runtime", "python3.13")])); + api.delay("get_function", Duration::from_millis(150)); + + let mut enrichment = MetricsEnrichment::new(test_config()); + enrichment.function_lookup_budget = Duration::from_millis(100); + enrichment.functions.insert( + "fn-2".to_string(), + fields(&[("Runtime", "ruby3.3")]), + Instant::now() - Duration::from_secs(1), + ); + + let lines = concat!( + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-1"}}"#, + "\n", + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-2"}}"#, + "\n", + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-3"}}"#, + "\n" + ); + let event = Event { + records: vec![InputRecord { + record_id: "1".to_string(), + data: BASE64.encode(lines), + }], + }; + + let response = enrichment.handle(&api, event).await; + + assert_eq!(response.records[0].result, "Ok"); + assert_eq!(api.calls("get_function"), 1); + assert_eq!( + String::from_utf8(BASE64.decode(&response.records[0].data).unwrap()).unwrap(), + concat!( + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-1"},"tags":{"Team":"core"},"team":"core","properties":{"Runtime":"provided.al2023"}}"#, + "\n", + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-2"},"properties":{"Runtime":"ruby3.3"}}"#, + "\n", + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-3"},"tags":{"Team":"core"},"team":"core"}"#, + "\n" + ) + ); + assert!(enrichment.functions.get("fn-3").is_none()); + + api.delay("get_function", Duration::ZERO); + let retry_event = Event { + records: vec![InputRecord { + record_id: "2".to_string(), + data: BASE64.encode( + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-3"}}"#, + ), + }], + }; + let retry_response = enrichment.handle(&api, retry_event).await; + assert_eq!(api.calls("get_function"), 2); + assert_eq!( + String::from_utf8(BASE64.decode(&retry_response.records[0].data).unwrap()).unwrap(), + concat!( + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"fn-3"},"tags":{"Team":"core"},"team":"core","properties":{"Runtime":"python3.13"}}"#, + "\n" + ) + ); + } + + #[tokio::test] + async fn enriches_lambda_metrics_with_tags_and_properties() { + let api = FakeApi::default(); + api.tags( + "arn:aws:lambda:us-east-1:123456789012:function:my-function", + &[("Environment", "production")], + ); + api.function( + "my-function", + fields(&[("Runtime", "provided.al2023"), ("Architecture", "arm64")]), + ); + let mut enrichment = MetricsEnrichment::new(test_config()); + let lines = concat!( + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"my-function"},"value":{"sum":3.0}}"#, + "\n", + r#"{"namespace":"AWS/Lambda","metric_name":"Duration","dimensions":{"FunctionName":"my-function"},"value":{"avg":12.5}}"#, + "\n" + ); + let event = Event { + records: vec![InputRecord { + record_id: "1".to_string(), + data: BASE64.encode(lines), + }], + }; + + let response = enrichment.handle(&api, event).await; + + assert_eq!(response.records[0].result, "Ok"); + assert_eq!(api.calls("get_function"), 1); + assert_eq!( + String::from_utf8(BASE64.decode(&response.records[0].data).unwrap()).unwrap(), + concat!( + r#"{"namespace":"AWS/Lambda","metric_name":"Invocations","dimensions":{"FunctionName":"my-function"},"value":{"sum":3.0},"tags":{"Environment":"production"},"environment":"production","properties":{"Runtime":"provided.al2023","Architecture":"arm64"}}"#, + "\n", + r#"{"namespace":"AWS/Lambda","metric_name":"Duration","dimensions":{"FunctionName":"my-function"},"value":{"avg":12.5},"tags":{"Environment":"production"},"environment":"production","properties":{"Runtime":"provided.al2023","Architecture":"arm64"}}"#, + "\n" + ) + ); } #[tokio::test]