-
Notifications
You must be signed in to change notification settings - Fork 7
feat(cloudflare): add telemetry collection and /metrics endpoint #400
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vahidlazio
wants to merge
9
commits into
main
Choose a base branch
from
feat/cloudflare-telemetry-analytics-engine
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
bbfc703
feat(cloudflare): add telemetry collection and /metrics endpoint
vahidlazio d513ce5
fix: await KV puts, guard malformed BucketSpan offsets, add tests
vahidlazio 88bfac7
chore: sync WASM module for Go provider
vahidlazio d62457b
fix: satisfy strict clippy lints in accumulate_delta
vahidlazio 39cb102
style: fix rustfmt line length in accumulate_delta
vahidlazio 404ed3f
chore: re-sync WASM module for Go provider after fmt fix
vahidlazio 2a52bfe
fix: aggregate telemetry deltas in flag_logger::aggregate_batch
vahidlazio 86094d6
fix(cloudflare): address PR review feedback
vahidlazio 157ae24
fix: resolve clippy redundant closure warning
vahidlazio File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,10 +2,12 @@ use confidence_resolver::{ | |
| assign_logger::AssignLogger, | ||
| flag_logger, | ||
| proto::{confidence, google::Struct}, | ||
| telemetry::{Telemetry, TelemetrySnapshot}, | ||
| FlagToApply, Host, ResolvedValue, ResolverState, | ||
| }; | ||
| use worker::*; | ||
|
|
||
| use arc_swap::ArcSwap; | ||
| use base64::engine::general_purpose::STANDARD; | ||
| use base64::Engine; | ||
| use bytes::Bytes; | ||
|
|
@@ -14,13 +16,37 @@ use serde_json::from_slice; | |
| use serde_json::json; | ||
|
|
||
| use confidence::flags::resolver::v1::{ApplyFlagsRequest, ApplyFlagsResponse, ResolveFlagsRequest}; | ||
| use confidence_resolver::proto::confidence::flags::resolver::v1::ResolveProcessRequest; | ||
| use confidence_resolver::proto::confidence::flags::resolver::v1::{ResolveProcessRequest, ResolveReason}; | ||
|
|
||
| static RESOLVE_LOGGER: LazyLock<ResolveLogger<H>> = LazyLock::new(ResolveLogger::new); | ||
| static ASSIGN_LOGGER: LazyLock<AssignLogger> = LazyLock::new(AssignLogger::new); | ||
| static TELEMETRY: LazyLock<Telemetry> = LazyLock::new(Telemetry::new); | ||
| static LAST_FLUSHED: LazyLock<ArcSwap<TelemetrySnapshot>> = | ||
| LazyLock::new(|| ArcSwap::from_pointee(TelemetrySnapshot::default())); | ||
|
|
||
| use confidence_resolver::Client; | ||
| use once_cell::sync::Lazy; | ||
| use std::cell::RefCell; | ||
|
|
||
| /// High-resolution timestamp in milliseconds via `performance.now()`. | ||
| fn performance_now() -> f64 { | ||
| js_sys::Reflect::get(&js_sys::global(), &"performance".into()) | ||
| .ok() | ||
| .and_then(|p| js_sys::Reflect::get(&p, &"now".into()).ok()) | ||
| .and_then(|f| js_sys::Function::from(f).call0(&js_sys::global()).ok()) | ||
| .and_then(|v| v.as_f64()) | ||
| .unwrap_or_else(js_sys::Date::now) | ||
| } | ||
|
|
||
| /// Per-request resolve metrics captured in the hot path, recorded in wait_until. | ||
| struct ResolveMetrics { | ||
| elapsed_us: u32, | ||
| reasons: Vec<ResolveReason>, | ||
| } | ||
|
|
||
| thread_local! { | ||
| static PENDING_METRICS: RefCell<Vec<ResolveMetrics>> = const { RefCell::new(Vec::new()) }; | ||
| } | ||
|
|
||
| /// SetResolverStateRequest message from the CDN. | ||
| /// This matches the protobuf message format returned by the CDN. | ||
|
|
@@ -142,6 +168,19 @@ pub async fn main(req: Request, env: Env, ctx: Context) -> Result<Response> { | |
| let router = Router::new(); | ||
|
|
||
| let response = router | ||
| .get_async("/metrics", |_req, ctx| { | ||
| let allowed_origin = allowed_origin_env.clone(); | ||
| async move { | ||
| let text = match ctx.env.kv("CONFIDENCE_METRICS_KV") { | ||
| Ok(kv) => kv.get("prometheus").text().await.unwrap_or(None), | ||
| Err(_) => None, | ||
| }; | ||
| let body = text.unwrap_or_default(); | ||
| let headers = Headers::new(); | ||
| headers.set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")?; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think there might be some special Content-Type we should use for Prometheus. |
||
| Response::ok(body)?.with_headers(headers).with_cors_headers(&allowed_origin) | ||
| } | ||
| }) | ||
| // GET endpoint to expose the current deployment state etag and resolver version | ||
| .get_async("/v1/state:etag", |_req, _ctx| { | ||
| let allowed_origin = allowed_origin_env.clone(); | ||
|
|
@@ -181,6 +220,7 @@ pub async fn main(req: Request, env: Env, ctx: Context) -> Result<Response> { | |
| .evaluation_context | ||
| .clone() | ||
| .unwrap_or_default(); | ||
| let start = performance_now(); | ||
| match state.get_resolver::<H>( | ||
| &resolver_request.client_secret, | ||
| evaluation_context, | ||
|
|
@@ -193,23 +233,56 @@ pub async fn main(req: Request, env: Env, ctx: Context) -> Result<Response> { | |
| ); | ||
| match resolver.resolve_flags(process_request) { | ||
| Ok(process_response) => { | ||
| let elapsed_us = ((performance_now() - start) * 1000.0) as u32; | ||
| match process_response.into_resolved() { | ||
| Some((response, _writes)) => { | ||
| let reasons: Vec<ResolveReason> = response | ||
| .resolved_flags | ||
| .iter() | ||
| .map(|f| f.reason()) | ||
| .collect(); | ||
| PENDING_METRICS.with(|m| { | ||
| m.borrow_mut().push(ResolveMetrics { elapsed_us, reasons }); | ||
| }); | ||
| Response::from_json(&response)? | ||
| .with_cors_headers(&allowed_origin) | ||
| } | ||
| None => Response::error( | ||
| "Unexpected suspended response", | ||
| 500, | ||
| )? | ||
| .with_cors_headers(&allowed_origin), | ||
| None => { | ||
| PENDING_METRICS.with(|m| { | ||
| m.borrow_mut().push(ResolveMetrics { | ||
| elapsed_us, | ||
| reasons: vec![ResolveReason::Error], | ||
| }); | ||
| }); | ||
| Response::error( | ||
| "Unexpected suspended response", | ||
| 500, | ||
| )? | ||
| .with_cors_headers(&allowed_origin) | ||
| } | ||
| } | ||
| } | ||
| Err(msg) => Response::error(msg, 500)? | ||
| .with_cors_headers(&allowed_origin), | ||
| Err(msg) => { | ||
| let elapsed_us = ((performance_now() - start) * 1000.0) as u32; | ||
| PENDING_METRICS.with(|m| { | ||
| m.borrow_mut().push(ResolveMetrics { | ||
| elapsed_us, | ||
| reasons: vec![ResolveReason::Error], | ||
| }); | ||
| }); | ||
| Response::error(msg, 500)? | ||
| .with_cors_headers(&allowed_origin) | ||
| } | ||
| } | ||
| } | ||
| Err(msg) => { | ||
| let elapsed_us = ((performance_now() - start) * 1000.0) as u32; | ||
| PENDING_METRICS.with(|m| { | ||
| m.borrow_mut().push(ResolveMetrics { | ||
| elapsed_us, | ||
| reasons: vec![ResolveReason::Error], | ||
| }); | ||
| }); | ||
| Response::error(msg, 500)?.with_cors_headers(&allowed_origin) | ||
| } | ||
| } | ||
|
|
@@ -250,8 +323,18 @@ pub async fn main(req: Request, env: Env, ctx: Context) -> Result<Response> { | |
| .run(req, env) | ||
| .await; | ||
|
|
||
| // Use ctx.waitUntil to run logging after response is returned | ||
| // Use ctx.waitUntil to run logging and telemetry after response is returned | ||
| ctx.wait_until(async move { | ||
| // Record pending resolve metrics into the telemetry counters | ||
| PENDING_METRICS.with(|m| { | ||
| for metrics in m.borrow_mut().drain(..) { | ||
| TELEMETRY.record_latency_us(metrics.elapsed_us); | ||
| for reason in metrics.reasons { | ||
| TELEMETRY.mark_resolve(reason); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| let aggregated: confidence_resolver::proto::confidence::flags::resolver::v1::WriteFlagLogsRequest | ||
| = checkpoint(); | ||
| if let Ok(converted) = serde_json::to_string(&aggregated) { | ||
|
|
@@ -284,6 +367,12 @@ pub async fn consume_flag_logs_queue( | |
| client_resolve_info: v.client_resolve_info, | ||
| }) | ||
| .collect(); | ||
|
|
||
| // Accumulate telemetry deltas into KV-backed cumulative snapshot for /metrics | ||
| if let Ok(kv) = env.kv("CONFIDENCE_METRICS_KV") { | ||
| let _ = update_prometheus_kv(&kv, &logs).await; | ||
| } | ||
|
|
||
| let req = flag_logger::aggregate_batch(logs); | ||
| send_flags_logs(CONFIDENCE_CLIENT_SECRET.get().unwrap().as_str(), req).await?; | ||
| } | ||
|
|
@@ -293,10 +382,42 @@ pub async fn consume_flag_logs_queue( | |
|
|
||
| fn checkpoint() -> WriteFlagLogsRequest { | ||
| let mut req = RESOLVE_LOGGER.checkpoint(); | ||
| req.telemetry_data = Some(TELEMETRY.delta_snapshot(&LAST_FLUSHED)); | ||
| ASSIGN_LOGGER.checkpoint_fill(&mut req); | ||
| req | ||
| } | ||
|
|
||
| /// Accumulate telemetry deltas from all isolates into a cumulative | ||
| /// `TelemetrySnapshot` stored in KV, then write its Prometheus text | ||
| /// representation for the /metrics endpoint. | ||
| /// | ||
| /// Note: concurrent queue consumer invocations can race on KV read-modify-write. | ||
| /// Acceptable for metrics — at worst one batch's deltas are lost, not cumulative state. | ||
| async fn update_prometheus_kv(kv: &kv::KvStore, logs: &[WriteFlagLogsRequest]) { | ||
| let mut cumulative = match kv.get("snapshot").text().await { | ||
| Ok(Some(text)) => serde_json::from_str::<TelemetrySnapshot>(&text).unwrap_or_default(), | ||
| _ => TelemetrySnapshot::default(), | ||
| }; | ||
|
|
||
| for log in logs { | ||
| if let Some(td) = &log.telemetry_data { | ||
| cumulative.accumulate_delta(td); | ||
| } | ||
| } | ||
|
|
||
| let prom_text = cumulative.to_prometheus( | ||
| "cf-resolver", | ||
| &confidence_resolver::telemetry::PrometheusConfig::default(), | ||
| ); | ||
|
|
||
| if let Ok(builder) = kv.put("snapshot", serde_json::to_string(&cumulative).unwrap_or_default()) { | ||
| let _ = builder.execute().await; | ||
| } | ||
| if let Ok(builder) = kv.put("prometheus", prom_text) { | ||
| let _ = builder.execute().await; | ||
| } | ||
| } | ||
|
|
||
| async fn send_flags_logs(client_secret: &str, message: WriteFlagLogsRequest) -> Result<Response> { | ||
| let resolve_url = "https://resolver.confidence.dev/v1/clientFlagLogs:write"; | ||
| let mut init = RequestInit::new(); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should use this parser to check that we can parse the output of this.
Edit: No need to do this since it's the same serializer that we test in go.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also we could consider supporting the same options on this endpoint like we do in local:
confidence-resolver/openfeature-provider/go/confidence/provider.go
Line 356 in 3d30683
But that could also wait for a followup PR. Maybe even better.