settings/inspect/
listener_logger.rsuse crate::base::SettingType;
use fuchsia_inspect::{self as inspect, component, NumericProperty};
use fuchsia_inspect_derive::Inspect;
use settings_inspect_utils::managed_inspect_map::ManagedInspectMap;
const LISTENER_INSPECT_NODE_NAME: &str = "active_listeners";
pub struct ListenerInspectLogger {
listener_counts: ManagedInspectMap<ListenerInspectInfo>,
}
impl Default for ListenerInspectLogger {
fn default() -> Self {
Self::new()
}
}
#[derive(Default, Inspect)]
struct ListenerInspectInfo {
inspect_node: inspect::Node,
count: inspect::UintProperty,
}
impl ListenerInspectLogger {
pub fn new() -> Self {
Self::with_inspector(component::inspector())
}
pub fn with_inspector(inspector: &inspect::Inspector) -> Self {
let listener_counts_node = inspector.root().create_child(LISTENER_INSPECT_NODE_NAME);
Self {
listener_counts: ManagedInspectMap::<ListenerInspectInfo>::with_node(
listener_counts_node,
),
}
}
pub fn add_listener(&mut self, setting_type: SettingType) {
let setting_type_str = format!("{setting_type:?}");
let inspect_info =
self.listener_counts.get_or_insert_with(setting_type_str, ListenerInspectInfo::default);
let _ = inspect_info.count.add(1u64);
}
pub fn remove_listener(&mut self, setting_type: SettingType) {
let setting_type_str = format!("{setting_type:?}");
match self.listener_counts.map_mut().get_mut(&setting_type_str) {
Some(listener_inspect_info) => {
let _ = listener_inspect_info.count.subtract(1u64);
}
None => tracing::error!("Tried to subtract from nonexistent listener count"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use diagnostics_assertions::assert_data_tree;
#[fuchsia::test]
fn test_listener_logger() {
let inspector = inspect::Inspector::default();
let mut logger = ListenerInspectLogger::with_inspector(&inspector);
logger.add_listener(SettingType::Unknown);
logger.add_listener(SettingType::Unknown);
logger.add_listener(SettingType::Unknown);
logger.remove_listener(SettingType::Unknown);
assert_data_tree!(inspector, root: {
active_listeners: {
Unknown: {
"count": 2u64,
}
}
});
}
}