use std::sync::Arc;
use std::time::SystemTime;
use dashmap::DashMap;
use crate::stats::stats_item::StatsItem;
use crate::stats::stats_snapshot::StatsSnapshot;
#[derive(Clone, Debug)]
pub struct StatsItemSet {
stats_name: String,
items: Arc<DashMap<String, Arc<StatsItem>>>,
}
impl StatsItemSet {
pub fn new(stats_name: String) -> Self {
StatsItemSet {
stats_name,
items: Arc::new(DashMap::new()),
}
}
pub fn get_or_create_stats_item(&self, key: &str) -> Arc<StatsItem> {
if let Some(item) = self.items.get(key) {
return Arc::clone(&*item);
}
self.items
.entry(key.to_string())
.or_insert_with(|| Arc::new(StatsItem::new(&self.stats_name, key)))
.clone()
}
pub fn add_value(&self, stats_key: &str, inc_value: impl Into<i64>, inc_times: impl Into<i64>) {
let (inc_value, inc_times) = (inc_value.into() as u64, inc_times.into() as u64);
if let Some(item) = self.items.get(stats_key) {
item.add(inc_value, inc_times);
return;
}
self.items
.entry(stats_key.to_owned())
.or_insert_with(|| Arc::new(StatsItem::new(&self.stats_name, stats_key)))
.add(inc_value, inc_times);
}
pub fn add_rt_value(&self, stats_key: &str, inc_value: impl Into<i64>, inc_times: impl Into<i64>) {
self.add_value(stats_key, inc_value.into(), inc_times.into());
}
pub fn get_stats_data_in_minute(&self, stats_key: &str) -> StatsSnapshot {
self.items
.get(stats_key)
.map(|item| item.get_stats_data_in_minute())
.unwrap_or_default()
}
pub fn get_stats_data_in_hour(&self, stats_key: &str) -> StatsSnapshot {
self.items
.get(stats_key)
.map(|item| item.get_stats_data_in_hour())
.unwrap_or_default()
}
pub fn get_stats_item(&self, stats_key: &str) -> Option<Arc<StatsItem>> {
self.items.get(stats_key).map(|entry| entry.clone())
}
pub fn sampling_in_seconds(&self) {
for entry in self.items.iter() {
entry.value().sampling_in_seconds();
}
}
pub fn sampling_in_minutes(&self) {
for entry in self.items.iter() {
entry.value().sampling_in_minutes_level();
}
}
pub fn sampling_in_hours(&self) {
for entry in self.items.iter() {
entry.value().sampling_in_hour_level();
}
}
pub fn del_value(&self, key: &str) {
if let Some((_, item)) = self.items.remove(key) {
item.retire();
}
}
pub fn del_value_by_prefix_key(&self, prefix: &str, separator: &str) {
let match_prefix = format!("{}{}", prefix, separator);
self.retain_items(|key, _| !key.starts_with(&match_prefix));
}
pub fn del_value_by_suffix_key(&self, suffix: &str, separator: &str) {
let match_suffix = format!("{}{}", separator, suffix);
self.retain_items(|key, _| !key.ends_with(&match_suffix));
}
pub fn del_value_by_infix_key(&self, infix: &str, separator: &str) {
let pattern = format!("{}{}{}", separator, infix, separator);
self.retain_items(|key, _| !key.contains(&pattern));
}
pub fn size(&self) -> usize {
self.items.len()
}
pub fn clear(&self) {
self.retain_items(|_, _| false);
}
pub fn clean_resource(&self, max_idle_minutes: u64) {
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
self.clean_resource_at(now, max_idle_minutes);
}
pub fn clean_resource_at(&self, now_ms: u64, max_idle_minutes: u64) {
let threshold_ms = max_idle_minutes.saturating_mul(60 * 1000);
self.retain_items(|_, item| now_ms.saturating_sub(item.get_last_update_timestamp()) <= threshold_ms);
}
fn retain_items(&self, mut keep: impl FnMut(&str, &StatsItem) -> bool) {
self.items.retain(|key, item| {
let kept = keep(key, item);
if !kept {
item.retire();
}
kept
});
}
}
#[cfg(test)]
mod tests {
use super::*;
fn set_with(keys: &[&str]) -> (StatsItemSet, Vec<Arc<StatsItem>>) {
let set = StatsItemSet::new("TOPIC_PUT_NUMS".to_string());
let items = keys.iter().map(|key| set.get_or_create_stats_item(key)).collect();
(set, items)
}
#[test]
fn add_value_updates_the_existing_item_and_creates_missing_ones() {
let set = StatsItemSet::new("TOPIC_PUT_NUMS".to_string());
set.add_value("TopicA", 3, 1);
let item = set.get_stats_item("TopicA").expect("created by add_value");
set.add_value("TopicA", 4, 2);
assert_eq!(7, item.get_value());
assert_eq!(3, item.get_times());
assert_eq!(1, set.size());
}
#[test]
fn removal_retires_exactly_the_removed_items() {
let (set, items) = set_with(&["TopicA", "TopicB"]);
set.del_value("TopicA");
assert!(items[0].is_retired());
assert!(!items[1].is_retired());
let (set, items) = set_with(&["TopicA@GroupA", "TopicB@GroupA"]);
set.del_value_by_prefix_key("TopicA", "@");
assert_eq!([true, false], [items[0].is_retired(), items[1].is_retired()]);
let (set, items) = set_with(&["TopicA@GroupA", "TopicA@GroupB"]);
set.del_value_by_suffix_key("GroupB", "@");
assert_eq!([false, true], [items[0].is_retired(), items[1].is_retired()]);
let (set, items) = set_with(&["0@TopicA@GroupA", "0@TopicB@GroupA"]);
set.del_value_by_infix_key("TopicA", "@");
assert_eq!([true, false], [items[0].is_retired(), items[1].is_retired()]);
let (set, items) = set_with(&["TopicA", "TopicB"]);
set.clean_resource(60);
assert!(
items.iter().all(|item| !item.is_retired()),
"recently updated items stay"
);
set.clear();
assert!(items.iter().all(|item| item.is_retired()));
assert_eq!(0, set.size());
set.add_value("TopicA", 1, 1);
let fresh = set.get_stats_item("TopicA").expect("recreated");
assert!(!fresh.is_retired());
assert_eq!(1, fresh.get_times());
}
}