Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
216 changes: 207 additions & 9 deletions bottlecap/src/traces/trace_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ const LLM_OBS_EVAL_METRIC_ENDPOINT_PATH: &str = "/evp_proxy/v2/api/intake/llm-ob
const LLM_OBS_EVAL_METRIC_ENDPOINT_PATH_V2: &str =
"/evp_proxy/v2/api/intake/llm-obs/v2/eval-metric";
const LLM_OBS_SPANS_ENDPOINT_PATH: &str = "/evp_proxy/v2/api/v2/llmobs";
// Agentless flag discovery and Java/Go LLM Obs find the EVP proxy by this base path
// in /info; dd-trace-java and dd-trace-go LLM Obs also need the trailing slash.
const EVP_PROXY_V2_BASE_PATH: &str = "/evp_proxy/v2/";
const FFE_FLAG_EVALUATION_ENDPOINT_PATH: &str = "/evp_proxy/v2/api/v2/flagevaluation";
const FFE_EXPOSURES_ENDPOINT_PATH: &str = "/evp_proxy/v2/api/v2/exposures";
const INFO_ENDPOINT_PATH: &str = "/info";
const V1_DEBUGGER_ENDPOINT_PATH: &str = "/debugger/v1/input";
const V2_DEBUGGER_ENDPOINT_PATH: &str = "/debugger/v2/input";
Expand All @@ -75,6 +80,8 @@ const INSTRUMENTATION_ENDPOINT_PATH: &str = "/telemetry/proxy/api/v2/apmtelemetr
// Intake endpoints
const DSM_INTAKE_PATH: &str = "/api/v0.1/pipeline_stats";
const LLM_OBS_SPANS_INTAKE_PATH: &str = "/api/v2/llmobs";
const FFE_FLAG_EVALUATION_INTAKE_PATH: &str = "/api/v2/flagevaluation";
const FFE_EXPOSURES_INTAKE_PATH: &str = "/api/v2/exposures";
const LLM_OBS_EVAL_METRIC_INTAKE_PATH: &str = "/api/intake/llm-obs/v1/eval-metric";
const LLM_OBS_EVAL_METRIC_INTAKE_PATH_V2: &str = "/api/intake/llm-obs/v2/eval-metric";
const PROFILING_INTAKE_PATH: &str = "/api/v2/profile";
Expand All @@ -87,6 +94,8 @@ const STATS_PAYLOAD_CHANNEL_BUFFER_SIZE: usize = 10;
const BARRIER_CHANNEL_BUFFER_SIZE: usize = 1;
pub const TRACE_REQUEST_BODY_LIMIT: usize = 50 * 1024 * 1024;
pub const DEFAULT_REQUEST_BODY_LIMIT: usize = 2 * 1024 * 1024;
/// Tracers send EVP batches of about 5 MiB at most; the Agent's EVP proxy accepts 10 MiB.
const EVP_PROXY_REQUEST_BODY_LIMIT: usize = 10 * 1024 * 1024;
pub const MAX_CONTENT_LENGTH: usize = 50 * 1024 * 1024;
const LAMBDA_LOAD_SPAN: &str = "aws.lambda.load";

Expand Down Expand Up @@ -472,15 +481,6 @@ impl TraceAgent {
let proxy_router = Router::new()
.route(DSM_AGENT_PATH, post(Self::dsm_proxy))
.route(PROFILING_ENDPOINT_PATH, post(Self::profiling_proxy))
.route(
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH,
post(Self::llm_obs_eval_metric_proxy),
)
.route(
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH_V2,
post(Self::llm_obs_eval_metric_proxy_v2),
)
.route(LLM_OBS_SPANS_ENDPOINT_PATH, post(Self::llm_obs_spans_proxy))
.route(V1_DEBUGGER_ENDPOINT_PATH, post(Self::debugger_logs_proxy))
.route(V2_DEBUGGER_ENDPOINT_PATH, post(Self::debugger_intake_proxy))
.route(
Expand All @@ -492,6 +492,24 @@ impl TraceAgent {
post(Self::instrumentation_proxy),
)
.layer(RequestBodyLimitLayer::new(DEFAULT_REQUEST_BODY_LIMIT))
.with_state(proxy_state.clone());

let evp_proxy_router = Router::new()
.route(
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH,
post(Self::llm_obs_eval_metric_proxy),
)
.route(
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH_V2,
post(Self::llm_obs_eval_metric_proxy_v2),
)
.route(LLM_OBS_SPANS_ENDPOINT_PATH, post(Self::llm_obs_spans_proxy))
.route(
FFE_FLAG_EVALUATION_ENDPOINT_PATH,
post(Self::ffe_flag_evaluation_proxy),
)
.route(FFE_EXPOSURES_ENDPOINT_PATH, post(Self::ffe_exposures_proxy))
Comment thread
clifordshelton marked this conversation as resolved.
Resolved
.layer(RequestBodyLimitLayer::new(EVP_PROXY_REQUEST_BODY_LIMIT))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound buffered EVP bytes before accepting larger bodies

For a long-running or high-volume invocation using an end-of-invocation flush strategy, several valid roughly 5 MiB LLM/EVP batches can arrive before any flush occurs. This layer now accepts up to 10 MiB per request, but proxy_aggregator::Aggregator stores every body in an unbounded Vec, and handle_proxy always acknowledges it with 200, so a small-memory Lambda can exhaust its memory and terminate before reaching the flush. Add a byte/count bound with backpressure or rejection before increasing and advertising this capacity.

AGENTS.md reference: AGENTS.md:L48-L53

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with aarsilv:

Agreed that the proxy queue needs a byte cap. The 10 MiB limit came from our earlier review comment on this PR, which flagged the missing cap at the same time, and the author has filed a follow-up for it.

How long bodies can pile up during one long invocation depends on the flush strategy. In On-Demand mode:

  • The default strategy keeps flushing on a nominal 60 s timer while the invocation runs (main.rs:768-770 and :818-822, DEFAULT_FLUSH_INTERVAL at flush_control.rs:7).
  • With an explicit periodically or continuously strategy, timer ticks do not trigger flushes during the invocation (main.rs:818-822). An explicit end strategy uses a nominal 15-minute race timer instead (flush_control.rs:60-63). These strategies can therefore let bodies accumulate through a long invocation, so they are the particularly exposed cases.

The 2 MiB limit did not bound the queue either; it only capped each request. How fast the queue grows depends on how much the tracers send, and a cap bounds it in every case. Our take: keep the cap as the follow-up, and note the explicit-strategy case in the PR description until it lands.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, tracked in SVLS-10128. As Aaron noted, the 2 MiB limit only capped each request, not the queue, so a byte cap is the real bound either way. Until it lands, I added a note to the description: the most exposed setups are long invocations with an explicit DD_SERVERLESS_FLUSH_STRATEGY of periodically, continuously or end.

.with_state(proxy_state);

let info_router = Router::new().route(INFO_ENDPOINT_PATH, any(Self::info));
Expand All @@ -500,6 +518,7 @@ impl TraceAgent {
.merge(trace_router)
.merge(stats_router)
.merge(proxy_router)
.merge(evp_proxy_router)
.merge(info_router);

if let Some(extension) = &self.router_extension {
Expand Down Expand Up @@ -623,6 +642,33 @@ impl TraceAgent {
.await
}

async fn ffe_flag_evaluation_proxy(
State(state): State<ProxyState>,
request: Request,
) -> Response {
Self::handle_proxy(
state.config,
state.proxy_aggregator,
request,
"event-platform-intake",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with aarsilv:

Heads up: the end-of-invocation flush now depends on reaching event-platform-intake.<DD_SITE>

The Extension answers the tracer at once and sends flag events during its flush. The blocking flush waits for the proxy requests (flushing/service.rs:369-374, awaited at main.rs:775). If the intake host is unreachable or slow, for example with restricted VPC egress, the next /next waits as follows:

  • Each request is tried up to FLUSH_RETRY_COUNT (3) times (lib.rs:45), with flush_timeout per attempt (proxy_flusher.rs:133).
  • The HTTP client keeps no idle connections (pool_max_idle_per_host(0), http.rs:34), so each flush opens a new TLS connection.

This mechanism already exists for the LLM Obs routes, but flag customers now reach it by default. A release note could say: "Allow egress to event-platform-intake.<DD_SITE>."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I added "Allow egress to event-platform-intake.<DD_SITE>" to the release notes in the PR description.

FFE_FLAG_EVALUATION_INTAKE_PATH,
"ffe_flag_evaluation",
)
.await
}

async fn ffe_exposures_proxy(State(state): State<ProxyState>, request: Request) -> Response {
Self::handle_proxy(
state.config,
state.proxy_aggregator,
request,
"event-platform-intake",
FFE_EXPOSURES_INTAKE_PATH,
"ffe_exposures",
)
.await
}

// Used for `/debugger/v1/input` in Exception Replay
async fn debugger_logs_proxy(State(state): State<ProxyState>, request: Request) -> Response {
Self::handle_proxy(
Expand Down Expand Up @@ -675,10 +721,16 @@ impl TraceAgent {
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH,
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH_V2,
LLM_OBS_SPANS_ENDPOINT_PATH,
EVP_PROXY_V2_BASE_PATH,
Comment thread
clifordshelton marked this conversation as resolved.
Resolved
Comment thread
clifordshelton marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with aarsilv:

🟡 [P2] Listing /evp_proxy/v2/ moves dd-trace-go LLM Obs to agent mode, where its dataset and experiment calls get 404

dd-trace-go turns on its EVP proxy support when /info lists exactly "/evp_proxy/v2/" (option.go#L666). Unless agentless mode is set, through DD_LLMOBS_AGENTLESS_ENABLED or the WithLLMObsAgentlessEnabled option, ResolveAgentlessEnabled then picks agent mode (llmobs.go#L185-L195). In agent mode every LLM Obs call goes to the agent URL plus /evp_proxy/v2 (transport.go#L211). That includes the dataset and experiment APIs under /api/unstable/llm-obs/v1 and /api/v2/llm-obs/v1 (transport.go#L41-L42). The Extension does not route those paths, so they get 404, and dd-trace-go treats the failure as permanent (transport.go#L385). The span and evaluation-metric routes still return 200 in the router test below.

This affects Go functions that use LLM Obs datasets or experiments without agentless mode set. Before this PR they ran agentless.

Why the Extension cannot relay these calls

In agent mode those calls send X-Datadog-NeedsAppKey: true (transport.go#L304-L310), and the Extension has no application key. The pinned Datadog Agent does not add one for EVP requests either: "ApplicationKey is the top-level application key (app_key). Only the AI Guard proxy uses it." (config.go#L330).

A unit test against make_router() with this PR's commit gives:

POST path Status
/evp_proxy/v2/api/unstable/llm-obs/v1/datasets 404
/evp_proxy/v2/api/v2/llm-obs/v1/experiments 404
/evp_proxy/v2/api/v2/llmobs 200
/evp_proxy/v2/api/intake/llm-obs/v2/eval-metric 200
Suggested fix
  • In the PR description and release notes: "dd-trace-go LLM Observability datasets and experiments: set DD_LLMOBS_AGENTLESS_ENABLED=true, with DD_API_KEY and an application key."
  • Add a Go dataset or experiment call to the pending LLM Obs smoke test.
  • Optional: ask dd-trace-go to fall back to direct intake when a local EVP call gets 404.
  • Worth noting too: with DD_LLMOBS_AGENTLESS_ENABLED=false, Go LLM Obs used to fail to start because the agent did not support it (llmobs.go#L189-L191). That startup error is now avoided; dataset and experiment calls still get 404.

Was this finding useful? React with 👍 or 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, confirmed. dd-trace-go switches to agent mode when /info lists /evp_proxy/v2/ and DD_LLMOBS_AGENTLESS_ENABLED is unset. After that, dataset and experiment calls go through the Extension, which doesn't route them.

What we'll do in this PR: document it. The PR description and release notes will say:

Go functions that use LLM Observability datasets or experiments: set DD_LLMOBS_AGENTLESS_ENABLED=true and keep DD_API_KEY and DD_APP_KEY set, so those calls go directly to Datadog. LLM Observability spans and evaluations work through the Extension with no change.

The setups affected are Go functions that have DD_API_KEY and DD_APP_KEY set in plain text, use datasets or experiments, and leave agentless mode unset. Functions that use DD_API_KEY_SECRET_ARN couldn't use datasets before this PR either, and they now get spans and evaluations through the Extension.

Why the Extension won't pass DD_APP_KEY: dd-trace-go reads the app key only from DD_APP_KEY, so the Extension could read the same variable. We decided against it for two reasons:

  • The Datadog Agent removed this on purpose. trace: remove evp proxy appkey injection datadog-agent#51580 (June 2026) dropped app key injection and X-Datadog-NeedsAppKey from its EVP proxy because "it's not used by anyone and could be misused." Adding it to the Extension would bring back a local endpoint that attaches an app key to requests, which the Agent team removed. That decision belongs to the Agent, LLM Observability and security teams, not to a flag PR.
  • It's more than a header. Dataset and experiment calls are request and response (GET records, POST and PATCH experiments, multipart uploads). The store-and-forward proxy answers 200 right away and sends later, so these calls would need a synchronous pass-through with wildcard paths.

Likely a dd-trace-go issue: in agent mode, dd-trace-go sends these calls with X-Datadog-NeedsAppKey: true and no app key (transport.go#L303-L310). The current Agent no longer adds one. So dataset and experiment calls in agent mode look broken against the Datadog Agent too, not only in Lambda. A fix in dd-trace-go would cover both, for example sending these calls directly whenever DD_APP_KEY is set, or falling back to direct on a local 404. I'll raise it with the dd-trace-go team.

FFE_FLAG_EVALUATION_ENDPOINT_PATH,
FFE_EXPOSURES_ENDPOINT_PATH,
V1_DEBUGGER_ENDPOINT_PATH,
V2_DEBUGGER_ENDPOINT_PATH,
DEBUGGER_DIAGNOSTICS_ENDPOINT_PATH,
],
// The proxy flusher keeps these two headers. Agentless flag discovery needs
// both listed before it uses the local route.
"evp_proxy_allowed_headers": ["DD-EVP-ORIGIN", "DD-EVP-ORIGIN-VERSION"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the advertised EVP header allowlist

When a request to either newly advertised EVP route contains additional headers, handle_proxy queues every incoming header and proxy_flusher::create_request removes only host and content-length, so headers such as Authorization, cookies, or other credentials are forwarded to the Datadog intake even though /info declares that only these two headers are allowed. The EVP contract treats this field as a forwarding allowlist; use an Agent-compatible allowlist—including required payload headers such as Content-Type and Content-Encoding—and enforce it on EVP requests before queueing them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with aarsilv:

Our take: an allowlist is worth adding as hardening for all EVP routes in a follow-up, rather than as a blocker for this PR.

  • The flag routes forward headers the same way the three existing LLM Observability routes do: the flusher drops host and content-length and adds its own headers (proxy_flusher.rs:122-128). So a client that adds Authorization or cookies would have them forwarded on all five routes, and an allowlist would close that.
  • Flag-route discovery works because both required headers are listed and forwarded. dd-trace-js describes the field as the headers "that the proxy forwards to intake" (discovery.js#L18-L19).
  • The local flag routes in dd-trace-py, dd-trace-js and dd-trace-go do not add credentials. For example, dd-trace-py builds its local route with Content-Type, X-Datadog-EVP-Subdomain and the two origin headers (_evp_transport.py#L353-L363). The flusher sets DD-API-KEY itself, and HeaderMap::extend replaces any value a client sent.

The Agent forwards Content-Type, Accept-Encoding, Content-Encoding, User-Agent, DD-CI-PROVIDER-NAME, DD-EVP-ORIGIN and DD-EVP-ORIGIN-VERSION and clears the rest (evp_proxy.go#L40-L41); the same list would fit here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it's worth doing, and it applies to all five EVP routes, not only the new ones. Filed SVLS-10139 to forward only the Agent's allowlist (Content-Type, Accept-Encoding, Content-Encoding, User-Agent, DD-CI-PROVIDER-NAME, DD-EVP-ORIGIN, DD-EVP-ORIGIN-VERSION). Keeping it out of this PR since the tracers' local EVP routes don't add credentials and the flusher always sets DD-API-KEY itself.

"client_drop_p0s": false,
}
);
Expand Down Expand Up @@ -1324,4 +1376,150 @@ mod tests {

assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

/// The `/info` fields tracers read to pick a local EVP route. Discovery prefers
/// v4 when it is listed; dd-trace-java and dd-trace-go LLM Obs need the trailing
/// slash; agentless flag discovery needs both identity headers.
#[tokio::test]
async fn info_advertises_evp_proxy_for_feature_flags() {
Comment thread
clifordshelton marked this conversation as resolved.
Resolved
let response = TraceAgent::info().await;
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.expect("info body");
let info: serde_json::Value = serde_json::from_slice(&body).expect("info json");
let endpoints: Vec<&str> = info["endpoints"]
.as_array()
.expect("endpoints")
.iter()
.filter_map(serde_json::Value::as_str)
.collect();
// Literals, not the production constants, so a typo fails here.
for path in [
"/evp_proxy/v2/",
"/evp_proxy/v2/api/v2/flagevaluation",
"/evp_proxy/v2/api/v2/exposures",
] {
assert!(endpoints.contains(&path), "missing {path} in {endpoints:?}");
}
assert!(
!endpoints
.iter()
.any(|e| e.trim_start_matches('/').starts_with("evp_proxy/v4")),
"v4 is listed, so tracers would send to unrouted v4 paths: {endpoints:?}"
);
let headers: Vec<String> = info["evp_proxy_allowed_headers"]
.as_array()
.expect("evp_proxy_allowed_headers")
.iter()
.filter_map(serde_json::Value::as_str)
.map(str::to_ascii_lowercase)
.collect();
for header in ["dd-evp-origin", "dd-evp-origin-version"] {
assert!(
headers.iter().any(|h| h == header),
"missing {header} in {headers:?}"
);
}
}

/// EVP paths without a route return 404 and are not buffered.
#[tokio::test]
async fn unrouted_evp_paths_return_not_found() {
let agent = build_test_agent();
let router = agent.make_router().expect("make_router");
let response = router
.oneshot(
Request::builder()
.method("POST")
.uri("/evp_proxy/v2/api/v2/not-a-flag-route")
.header("X-Datadog-EVP-Subdomain", "event-platform-intake")
.body(Body::from("{}"))
.expect("build request"),
)
.await
.expect("route response");

assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert!(agent.proxy_aggregator.lock().await.get_batch().is_empty());
}

/// Tracers send EVP batches of about 5 MiB at most (the envelope can add a
/// little). Sent with Content-Length, such a batch gets 413 under the default
/// 2 MiB proxy limit, and tracers drop the rejected batch.
#[tokio::test]
async fn evp_proxy_routes_accept_five_mib_batches() {
for path in [
LLM_OBS_SPANS_ENDPOINT_PATH,
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH,
LLM_OBS_EVAL_METRIC_ENDPOINT_PATH_V2,
FFE_FLAG_EVALUATION_ENDPOINT_PATH,
FFE_EXPOSURES_ENDPOINT_PATH,
] {
for (size, expected) in [
(5 * 1024 * 1024 + 64 * 1024, StatusCode::OK),
(
EVP_PROXY_REQUEST_BODY_LIMIT + 1,
StatusCode::PAYLOAD_TOO_LARGE,
),
] {
let agent = build_test_agent();
let router = agent.make_router().expect("make_router");
let response = router
.oneshot(
Request::builder()
.method("POST")
.uri(path)
.header("Content-Type", "application/json")
.header("Content-Length", size.to_string())
.body(Body::from(vec![b' '; size]))
.expect("build request"),
)
.await
.expect("route response");
assert_eq!(response.status(), expected, "{path} with {size} bytes");
let queued = agent.proxy_aggregator.lock().await.get_batch().len();
assert_eq!(queued, usize::from(expected == StatusCode::OK), "{path}");
}
}
}

#[tokio::test]
async fn feature_flag_events_are_relayed_to_event_platform_intake() {
let agent = build_test_agent();
let site = agent.config.site.clone();
let router = agent.make_router().expect("make_router");
// Literals: the tracer paths and the intake paths are the contract.
for (path, intake) in [
(
"/evp_proxy/v2/api/v2/flagevaluation",
"/api/v2/flagevaluation",
),
("/evp_proxy/v2/api/v2/exposures", "/api/v2/exposures"),
] {
let response = router
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri(path)
.header("Content-Type", "application/json")
.header("DD-EVP-ORIGIN", "dd-trace-py")
.header("DD-EVP-ORIGIN-VERSION", "4.17.0")
.header("X-Datadog-EVP-Subdomain", "event-platform-intake")
.body(Body::from(r#"{"events":[]}"#))
.expect("build request"),
)
.await
.expect("route response");
assert_eq!(response.status(), StatusCode::OK, "{path}");
let batch = agent.proxy_aggregator.lock().await.get_batch();
assert_eq!(batch.len(), 1, "{path}");
assert_eq!(
batch[0].target_url,
format!("https://event-platform-intake.{site}{intake}")
);
assert_eq!(batch[0].headers["dd-evp-origin"], "dd-trace-py");
assert_eq!(batch[0].headers["dd-evp-origin-version"], "4.17.0");
}
}
}
91 changes: 91 additions & 0 deletions bottlecap/tests/evp_proxy_flush_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0
// Integration tests are exempt from the production lint policy in Cargo.toml.
#![allow(
unreachable_pub,
clippy::pedantic,
clippy::panic,
clippy::unwrap_used,
clippy::expect_used
)]

//! The proxy flusher sends a queued flag event batch with the API key and the
//! tracer's identity headers. The trace agent builds the intake URL; here the
//! batch targets a local intake directly.

mod fixtures;
#[path = "common/harness.rs"]
mod harness;

use std::collections::HashMap;
use std::sync::Arc;

use bottlecap::LAMBDA_RUNTIME_SLUG;
use bottlecap::config::Config;
use bottlecap::tags::provider::Provider;
use bottlecap::traces::proxy_aggregator::{Aggregator as ProxyAggregator, ProxyRequest};
use bottlecap::traces::proxy_flusher::Flusher as ProxyFlusher;
use datadog_fips::reqwest_adapter::create_reqwest_client_builder;
use dogstatsd::api_key::ApiKeyFactory;
use harness::prelude::*;
use tokio::sync::Mutex;

#[tokio::test]
async fn flag_event_batch_is_flushed_with_api_key_and_origin_headers() {
let intake = FaultIntake::start(FaultMode::Ok).await;
let config = Arc::new(Config {
api_key: TEST_API_KEY.to_string(),
site: "datadoghq.com".to_string(),
..Config::default()
});
let tags = Arc::new(Provider::new(
Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([(
"function_arn".to_string(),
"arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
)]),
));
let aggregator = Arc::new(Mutex::new(ProxyAggregator::default()));
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("content-type", "application/json".parse().unwrap());
headers.insert("dd-evp-origin", "dd-trace-js".parse().unwrap());
headers.insert("dd-evp-origin-version", "5.80.0".parse().unwrap());
aggregator.lock().await.add(ProxyRequest {
headers,
body: r#"{"exposures":[{"flag":{"key":"harness-exposed-flag"}}]}"#.into(),
target_url: format!("{}/api/v2/exposures", intake.url()),
});
// Test-only client towards a local intake; the FIPS adapter is what production uses.
let client = create_reqwest_client_builder()
.expect("client builder")
.no_proxy()
.build()
.expect("client");
let flusher = ProxyFlusher::new(
Arc::new(ApiKeyFactory::new(TEST_API_KEY)),
Arc::clone(&aggregator),
tags,
Arc::clone(&config),
client,
);

let failed = flusher.flush(None).await;
assert!(
failed.is_none(),
"flush failed: {failed:?}. {}",
intake.summary()
);

let sent = intake.requests_to("/api/v2/exposures");
assert_eq!(sent.len(), 1, "{}", intake.summary());
assert_eq!(sent[0].api_key(), Some(TEST_API_KEY));
assert_eq!(sent[0].header("dd-evp-origin"), Some("dd-trace-js"));
assert_eq!(sent[0].header("dd-evp-origin-version"), Some("5.80.0"));
assert!(
sent[0]
.body_text()
.unwrap()
.contains("harness-exposed-flag")
);
}
Loading