Skip to main content

hashiverse_server_lib/server/stats/
request_counts.rs

1use hashiverse_lib::protocol::payload::payload::{PayloadRequestKind, PAYLOAD_REQUEST_KIND_COUNT};
2use std::sync::atomic::{AtomicU64, Ordering};
3
4/// Build the `requests` subtree: one numeric field per [`PayloadRequestKind`]
5/// variant, keyed by its `Display` name, holding the running inbound counter.
6///
7/// Reads use `Ordering::Relaxed` — counters are advisory metrics, not
8/// synchronisation primitives, and the snapshot doesn't need to be coherent
9/// across kinds.
10pub fn request_counts_subtree(counters: &[AtomicU64; PAYLOAD_REQUEST_KIND_COUNT]) -> serde_json::Value {
11    let mut map = serde_json::Map::with_capacity(PAYLOAD_REQUEST_KIND_COUNT);
12    for (index, counter) in counters.iter().enumerate() {
13        let kind = match PayloadRequestKind::from_u16(index as u16) {
14            Ok(kind) => kind,
15            Err(_) => continue,
16        };
17        let count = counter.load(Ordering::Relaxed);
18        map.insert(kind.to_string(), serde_json::Value::from(count));
19    }
20    serde_json::Value::Object(map)
21}