-
Notifications
You must be signed in to change notification settings - Fork 37
feat: [metrics] Create metrics framework and add connection metrics #407
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
charlesdong1991
wants to merge
15
commits into
apache:main
Choose a base branch
from
charlesdong1991:metrics-framework
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
15 commits
Select commit
Hold shift + click to select a range
d62a1f8
Create metrics framework and add connection metrics
charlesdong1991 666bb78
Merge remote-tracking branch 'upstream/main' into metrics-framework
charlesdong1991 4dade11
Merge remote-tracking branch 'upstream/main' into metrics-framework
charlesdong1991 0345c69
address review feedback
charlesdong1991 2c88f31
Update comment to reflect correct behaviour
charlesdong1991 7003c57
Merge remote-tracking branch 'upstream/main' into metrics-framework
charlesdong1991 44c4474
update response byte and request byte to exclude header and framing
charlesdong1991 c197654
Merge remote-tracking branch 'upstream/main' into metrics-framework
charlesdong1991 1d91fab
update error message and fix format
charlesdong1991 98eb598
Merge remote-tracking branch 'upstream/main' into metrics-framework
charlesdong1991 9ab7f84
update tests
charlesdong1991 2aee3e2
Merge remote-tracking branch 'upstream/main' into metrics-framework
charlesdong1991 063b9f5
enhance testing
charlesdong1991 11a8eeb
address comments
charlesdong1991 5b0008c
Merge remote-tracking branch 'upstream/main' into metrics-framework
charlesdong1991 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
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
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 |
|---|---|---|
| @@ -0,0 +1,270 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| //! Metric name constants and helpers for fluss-rust client instrumentation. | ||
| //! | ||
| //! Uses the [`metrics`] crate facade pattern: library code emits metrics via | ||
| //! `counter!`/`gauge!`/`histogram!` macros, and the application installs a | ||
| //! recorder (e.g. `metrics-exporter-prometheus`) to collect them. When no | ||
| //! recorder is installed, all metric calls are no-ops with zero overhead. | ||
|
|
||
| use crate::rpc::ApiKey; | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Label keys | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| pub const LABEL_API_KEY: &str = "api_key"; | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Connection / RPC metrics | ||
| // | ||
| // Java reference: ConnectionMetrics.java, ClientMetricGroup.java, MetricNames.java | ||
| // | ||
| // Byte counting matches Java semantics: both sides count only the API message | ||
| // body, excluding the protocol header and framing. | ||
| // Java: rawRequest.totalSize() / response.totalSize() (see MessageCodec.java). | ||
| // Rust: buf.len() - REQUEST_HEADER_LENGTH for sent bytes, | ||
| // buffer.len() - cursor.position() for received bytes. | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| pub const CLIENT_REQUESTS_TOTAL: &str = "fluss.client.requests.total"; | ||
| pub const CLIENT_RESPONSES_TOTAL: &str = "fluss.client.responses.total"; | ||
| pub const CLIENT_BYTES_SENT_TOTAL: &str = "fluss.client.bytes_sent.total"; | ||
| pub const CLIENT_BYTES_RECEIVED_TOTAL: &str = "fluss.client.bytes_received.total"; | ||
| pub const CLIENT_REQUEST_LATENCY_MS: &str = "fluss.client.request_latency_ms"; | ||
| pub const CLIENT_REQUESTS_IN_FLIGHT: &str = "fluss.client.requests_in_flight"; | ||
|
|
||
| /// Returns a label value for reportable API keys, matching Java's | ||
| /// `ConnectionMetrics.REPORT_API_KEYS` filter (`ProduceLog`, `FetchLog`, | ||
| /// `PutKv`, `Lookup`). Returns `None` for admin/metadata/auth calls to | ||
| /// avoid metric cardinality bloat. | ||
| pub(crate) fn api_key_label(api_key: ApiKey) -> Option<&'static str> { | ||
| match api_key { | ||
| ApiKey::ProduceLog => Some("produce_log"), | ||
| ApiKey::FetchLog => Some("fetch_log"), | ||
| ApiKey::PutKv => Some("put_kv"), | ||
| ApiKey::Lookup => Some("lookup"), | ||
| _ => None, | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use metrics_util::debugging::DebuggingRecorder; | ||
|
|
||
| macro_rules! find_counter { | ||
| ($entries:expr, $name:expr) => { | ||
| $entries.iter().find_map(|(key, _, _, val)| { | ||
| if key.key().name() == $name { | ||
| match val { | ||
| metrics_util::debugging::DebugValue::Counter(v) => Some(*v), | ||
| _ => None, | ||
| } | ||
| } else { | ||
| None | ||
| } | ||
| }) | ||
| }; | ||
| } | ||
|
|
||
| macro_rules! find_histogram { | ||
| ($entries:expr, $name:expr) => { | ||
| $entries.iter().find_map(|(key, _, _, val)| { | ||
| if key.key().name() == $name { | ||
| match val { | ||
| metrics_util::debugging::DebugValue::Histogram(v) => { | ||
| Some(v.iter().map(|f| f.into_inner()).collect::<Vec<_>>()) | ||
| } | ||
| _ => None, | ||
| } | ||
| } else { | ||
| None | ||
| } | ||
| }) | ||
| }; | ||
| } | ||
|
|
||
| macro_rules! find_gauge { | ||
| ($entries:expr, $name:expr) => { | ||
| $entries.iter().find_map(|(key, _, _, val)| { | ||
| if key.key().name() == $name { | ||
| match val { | ||
| metrics_util::debugging::DebugValue::Gauge(g) => Some(g.into_inner()), | ||
| _ => None, | ||
| } | ||
| } else { | ||
| None | ||
| } | ||
| }) | ||
| }; | ||
| } | ||
|
|
||
| #[test] | ||
| fn reportable_api_keys_return_label() { | ||
| assert_eq!(api_key_label(ApiKey::ProduceLog), Some("produce_log")); | ||
| assert_eq!(api_key_label(ApiKey::FetchLog), Some("fetch_log")); | ||
| assert_eq!(api_key_label(ApiKey::PutKv), Some("put_kv")); | ||
| assert_eq!(api_key_label(ApiKey::Lookup), Some("lookup")); | ||
| } | ||
|
|
||
| #[test] | ||
| fn non_reportable_api_keys_return_none() { | ||
| assert_eq!(api_key_label(ApiKey::MetaData), None); | ||
| assert_eq!(api_key_label(ApiKey::CreateTable), None); | ||
| assert_eq!(api_key_label(ApiKey::Authenticate), None); | ||
| assert_eq!(api_key_label(ApiKey::ListDatabases), None); | ||
| assert_eq!(api_key_label(ApiKey::GetTable), None); | ||
| } | ||
|
|
||
| #[test] | ||
| fn reportable_request_records_all_connection_metrics() { | ||
| let recorder = DebuggingRecorder::new(); | ||
| let snapshotter = recorder.snapshotter(); | ||
|
|
||
| metrics::with_local_recorder(&recorder, || { | ||
| let label = api_key_label(ApiKey::ProduceLog).unwrap(); | ||
|
|
||
| metrics::counter!(CLIENT_REQUESTS_TOTAL, LABEL_API_KEY => label).increment(1); | ||
| metrics::counter!(CLIENT_BYTES_SENT_TOTAL, LABEL_API_KEY => label).increment(256); | ||
| metrics::gauge!(CLIENT_REQUESTS_IN_FLIGHT, LABEL_API_KEY => label).increment(1.0); | ||
|
|
||
| metrics::counter!(CLIENT_RESPONSES_TOTAL, LABEL_API_KEY => label).increment(1); | ||
| metrics::counter!(CLIENT_BYTES_RECEIVED_TOTAL, LABEL_API_KEY => label).increment(128); | ||
| metrics::histogram!(CLIENT_REQUEST_LATENCY_MS, LABEL_API_KEY => label).record(42.5); | ||
| metrics::gauge!(CLIENT_REQUESTS_IN_FLIGHT, LABEL_API_KEY => label).decrement(1.0); | ||
| }); | ||
|
|
||
| let snapshot = snapshotter.snapshot(); | ||
| let entries: Vec<_> = snapshot.into_vec(); | ||
|
|
||
| assert_eq!(find_counter!(entries, CLIENT_REQUESTS_TOTAL), Some(1)); | ||
| assert_eq!(find_counter!(entries, CLIENT_RESPONSES_TOTAL), Some(1)); | ||
| assert_eq!(find_counter!(entries, CLIENT_BYTES_SENT_TOTAL), Some(256)); | ||
| assert_eq!( | ||
| find_counter!(entries, CLIENT_BYTES_RECEIVED_TOTAL), | ||
| Some(128) | ||
| ); | ||
| assert_eq!( | ||
| find_histogram!(entries, CLIENT_REQUEST_LATENCY_MS), | ||
| Some(vec![42.5]) | ||
| ); | ||
| assert_eq!(find_gauge!(entries, CLIENT_REQUESTS_IN_FLIGHT), Some(0.0)); | ||
|
|
||
| let has_label = entries.iter().all(|(key, _, _, _)| { | ||
| key.key() | ||
| .labels() | ||
| .any(|l| l.key() == LABEL_API_KEY && l.value() == "produce_log") | ||
| }); | ||
| assert!(has_label, "all metrics must carry the api_key label"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn non_reportable_request_records_no_metrics() { | ||
| let recorder = DebuggingRecorder::new(); | ||
| let snapshotter = recorder.snapshotter(); | ||
|
|
||
| metrics::with_local_recorder(&recorder, || { | ||
| let label = api_key_label(ApiKey::MetaData); | ||
| assert!(label.is_none()); | ||
| // When label is None, no metrics calls are made (matching request() logic). | ||
| }); | ||
|
|
||
| let snapshot = snapshotter.snapshot(); | ||
| assert!( | ||
| snapshot.into_vec().is_empty(), | ||
| "non-reportable API keys must not produce metrics" | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn inflight_gauge_nets_to_zero_after_balanced_calls() { | ||
| let recorder = DebuggingRecorder::new(); | ||
| let snapshotter = recorder.snapshotter(); | ||
|
|
||
| metrics::with_local_recorder(&recorder, || { | ||
| let label = api_key_label(ApiKey::FetchLog).unwrap(); | ||
|
|
||
| // Simulate 3 concurrent requests completing | ||
| for _ in 0..3 { | ||
| metrics::gauge!(CLIENT_REQUESTS_IN_FLIGHT, LABEL_API_KEY => label).increment(1.0); | ||
| } | ||
| for _ in 0..3 { | ||
| metrics::gauge!(CLIENT_REQUESTS_IN_FLIGHT, LABEL_API_KEY => label).decrement(1.0); | ||
| } | ||
| }); | ||
|
|
||
| let snapshot = snapshotter.snapshot(); | ||
| let entries: Vec<_> = snapshot.into_vec(); | ||
| assert_eq!( | ||
| find_gauge!(entries, CLIENT_REQUESTS_IN_FLIGHT), | ||
| Some(0.0), | ||
| "in-flight gauge should be 0 after balanced inc/dec" | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn different_api_keys_produce_separate_metric_series() { | ||
| use std::collections::HashMap; | ||
|
|
||
| let recorder = DebuggingRecorder::new(); | ||
| let snapshotter = recorder.snapshotter(); | ||
|
|
||
| metrics::with_local_recorder(&recorder, || { | ||
| let produce_label = api_key_label(ApiKey::ProduceLog).unwrap(); | ||
| let fetch_label = api_key_label(ApiKey::FetchLog).unwrap(); | ||
|
|
||
| metrics::counter!(CLIENT_REQUESTS_TOTAL, LABEL_API_KEY => produce_label).increment(5); | ||
| metrics::counter!(CLIENT_REQUESTS_TOTAL, LABEL_API_KEY => fetch_label).increment(3); | ||
| }); | ||
|
|
||
| let snapshot = snapshotter.snapshot(); | ||
| let entries: Vec<_> = snapshot.into_vec(); | ||
|
|
||
| let request_entries: Vec<_> = entries | ||
| .iter() | ||
| .filter(|(key, _, _, _)| key.key().name() == CLIENT_REQUESTS_TOTAL) | ||
| .collect(); | ||
|
|
||
| assert_eq!( | ||
charlesdong1991 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| request_entries.len(), | ||
| 2, | ||
| "produce_log and fetch_log should be separate metric series" | ||
| ); | ||
|
|
||
| let mut counter_by_api_key: HashMap<String, u64> = HashMap::new(); | ||
| for (key, _, _, val) in request_entries { | ||
| let api_key = key | ||
| .key() | ||
| .labels() | ||
| .find(|label| label.key() == LABEL_API_KEY) | ||
| .map(|label| label.value()) | ||
| .expect("requests total metric must include api_key label"); | ||
|
|
||
| let counter_value = match val { | ||
| metrics_util::debugging::DebugValue::Counter(v) => *v, | ||
| other => panic!("expected Counter, got {other:?}"), | ||
| }; | ||
|
|
||
| counter_by_api_key.insert(api_key.to_string(), counter_value); | ||
| } | ||
|
|
||
| assert_eq!(counter_by_api_key.get("produce_log"), Some(&5)); | ||
| assert_eq!(counter_by_api_key.get("fetch_log"), Some(&3)); | ||
| } | ||
| } | ||
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
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.