Skip to main content

rocketmq_protocol/protocol/body/
timer_metrics_serialize_wrapper.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::fmt::Display;
17use std::sync::atomic::AtomicU64;
18
19use cheetah_string::CheetahString;
20
21use crate::protocol::DataVersion;
22
23#[derive(Debug, serde::Serialize, serde::Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct TimerMetricsSerializeWrapper {
26    timing_count: HashMap<CheetahString, Metric>,
27    data_version: DataVersion,
28}
29
30impl TimerMetricsSerializeWrapper {
31    pub fn new() -> Self {
32        TimerMetricsSerializeWrapper::default()
33    }
34
35    pub fn with_timing_count(mut self, timing_count: HashMap<CheetahString, Metric>) -> Self {
36        self.timing_count = timing_count;
37        self
38    }
39
40    pub fn with_data_version(mut self, data_version: DataVersion) -> Self {
41        self.data_version = data_version;
42        self
43    }
44
45    pub fn timing_count(&self) -> &HashMap<CheetahString, Metric> {
46        &self.timing_count
47    }
48
49    pub fn data_version(&self) -> &DataVersion {
50        &self.data_version
51    }
52
53    pub fn data_version_mut(&mut self) -> &mut DataVersion {
54        &mut self.data_version
55    }
56
57    pub fn timing_count_mut(&mut self) -> &mut HashMap<CheetahString, Metric> {
58        &mut self.timing_count
59    }
60
61    pub fn insert_metric(&mut self, key: CheetahString, metric: Metric) {
62        self.timing_count.insert(key, metric);
63    }
64
65    pub fn get_metric(&self, key: &CheetahString) -> Option<&Metric> {
66        self.timing_count.get(key)
67    }
68
69    pub fn get_metric_mut(&mut self, key: &CheetahString) -> Option<&mut Metric> {
70        self.timing_count.get_mut(key)
71    }
72}
73
74impl Default for TimerMetricsSerializeWrapper {
75    fn default() -> Self {
76        TimerMetricsSerializeWrapper {
77            timing_count: HashMap::with_capacity(1024),
78            data_version: DataVersion::default(),
79        }
80    }
81}
82
83#[derive(Debug, serde::Serialize, serde::Deserialize)]
84#[serde(rename_all = "camelCase")]
85pub struct Metric {
86    pub count: AtomicU64,
87    pub time_stamp: u64,
88}
89
90impl Default for Metric {
91    fn default() -> Self {
92        Metric {
93            count: AtomicU64::new(0),
94            time_stamp: 0,
95        }
96    }
97}
98
99impl Display for Metric {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        write!(
102            f,
103            "Metric {{ count: {}, time_stamp: {} }}",
104            self.count.load(std::sync::atomic::Ordering::Relaxed),
105            self.time_stamp
106        )
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use std::sync::atomic::Ordering;
113
114    use super::*;
115
116    fn metric(count: u64, time_stamp: u64) -> Metric {
117        Metric {
118            count: AtomicU64::new(count),
119            time_stamp,
120        }
121    }
122
123    #[test]
124    fn wrapper_methods_cover_builders_and_mutable_accessors() {
125        let default_metric = Metric::default();
126        assert_eq!(default_metric.count.load(Ordering::Relaxed), 0);
127        assert_eq!(default_metric.time_stamp, 0);
128
129        let empty = TimerMetricsSerializeWrapper::new();
130        assert!(empty.timing_count().is_empty());
131        assert!(empty.timing_count().capacity() >= 1024);
132
133        let key = CheetahString::from_static_str("metric-a");
134        let mut data_version = DataVersion::default();
135        data_version.set_state_version(7);
136        let mut wrapper = TimerMetricsSerializeWrapper::new()
137            .with_timing_count(HashMap::from([(key.clone(), metric(10, 1000))]))
138            .with_data_version(data_version);
139
140        assert!(wrapper.timing_count().capacity() >= 1);
141        assert_eq!(wrapper.data_version().state_version(), 7);
142        assert_eq!(
143            wrapper
144                .get_metric(&key)
145                .expect("inserted metric")
146                .count
147                .load(Ordering::Relaxed),
148            10
149        );
150        assert!(wrapper.get_metric(&CheetahString::from_static_str("missing")).is_none());
151
152        wrapper
153            .get_metric_mut(&key)
154            .expect("mutable inserted metric")
155            .time_stamp = 2000;
156        wrapper.data_version_mut().set_state_version(8);
157        wrapper
158            .timing_count_mut()
159            .insert(CheetahString::from_static_str("metric-b"), metric(20, 3000));
160        wrapper.insert_metric(CheetahString::from_static_str("metric-c"), metric(30, 4000));
161
162        assert_eq!(wrapper.get_metric(&key).expect("updated metric").time_stamp, 2000);
163        assert_eq!(wrapper.data_version().state_version(), 8);
164        assert_eq!(wrapper.timing_count().len(), 3);
165    }
166
167    #[test]
168    fn metric_display_reports_the_current_values() {
169        assert_eq!(
170            metric(123, 9876543210).to_string(),
171            "Metric { count: 123, time_stamp: 9876543210 }"
172        );
173    }
174
175    #[test]
176    fn serde_contract_preserves_metric_and_version_fields() {
177        let key = CheetahString::from_static_str("metric-a");
178        let mut data_version = DataVersion::default();
179        data_version.set_state_version(7);
180        data_version.set_timestamp(12345);
181        data_version.set_counter(3);
182        let wrapper = TimerMetricsSerializeWrapper::new()
183            .with_timing_count(HashMap::from([(key.clone(), metric(42, 1000))]))
184            .with_data_version(data_version);
185
186        let value = serde_json::to_value(&wrapper).expect("serialize timer metrics");
187        assert_eq!(value["timingCount"]["metric-a"]["count"], 42);
188        assert_eq!(value["timingCount"]["metric-a"]["timeStamp"], 1000);
189        assert_eq!(value["dataVersion"]["stateVersion"], 7);
190
191        let decoded: TimerMetricsSerializeWrapper = serde_json::from_value(value).expect("deserialize timer metrics");
192        let decoded_metric = decoded.get_metric(&key).expect("decoded metric");
193        assert_eq!(decoded_metric.count.load(Ordering::Relaxed), 42);
194        assert_eq!(decoded_metric.time_stamp, 1000);
195        assert_eq!(decoded.data_version().state_version(), 7);
196        assert_eq!(decoded.data_version().timestamp(), 12345);
197        assert_eq!(decoded.data_version().counter(), 3);
198    }
199}