sierradb_server/request/
info.rs1use combine::{Parser, choice};
2use indexmap::indexmap;
3use redis_protocol::resp3::types::BytesFrame;
4use sierradb::cache::{BLOCK_SIZE, SegmentBlockCache};
5
6use crate::parser::{FrameStream, keyword};
7use crate::request::{HandleRequest, blob_str, double, map, number};
8use crate::server::Conn;
9
10pub struct Info {
11 pub section: InfoSection,
12}
13
14impl Info {
15 pub fn parser<'a>() -> impl Parser<FrameStream<'a>, Output = Info> + 'a {
16 InfoSection::parser().map(|section| Info { section })
17 }
18}
19
20pub enum InfoSection {
21 Cache,
22}
23
24impl InfoSection {
25 pub fn parser<'a>() -> impl Parser<FrameStream<'a>, Output = InfoSection> + 'a {
26 choice!(keyword("CACHE").map(|_| InfoSection::Cache))
27 }
28}
29
30impl HandleRequest for Info {
31 type Error = String;
32 type Ok = InfoResp;
33
34 async fn handle_request(self, conn: &mut Conn) -> Result<Option<Self::Ok>, Self::Error> {
35 let resp = match self.section {
36 InfoSection::Cache => {
37 let hits = SegmentBlockCache::cache_hits();
38 let misses = SegmentBlockCache::cache_misses();
39 let hit_ratio = if hits + misses > 0 {
40 let total = (hits + misses) as f64;
41 (hits as f64 / total * 1000.0).round() / 1000.0
42 } else {
43 0.0
44 };
45
46 let entries: u64 = conn
47 .caches
48 .values()
49 .map(|cache| cache.cache().entry_count())
50 .sum();
51 let memory_bytes: u64 = conn
52 .caches
53 .values()
54 .map(|cache| cache.cache().weighted_size())
55 .sum();
56 let max_bytes = conn.cache_capacity_bytes;
57 let block_size_bytes = BLOCK_SIZE;
58 let evictions = SegmentBlockCache::blocks_evicted();
59
60 InfoResp::Cache(InfoCacheResp {
61 hits,
62 misses,
63 hit_ratio,
64 entries,
65 memory_bytes,
66 max_bytes,
67 block_size_bytes,
68 evictions,
69 })
70 }
71 };
72
73 Ok(Some(resp))
74 }
75}
76
77pub enum InfoResp {
78 Cache(InfoCacheResp),
79}
80
81impl From<InfoResp> for BytesFrame {
82 fn from(resp: InfoResp) -> Self {
83 match resp {
84 InfoResp::Cache(resp) => resp.into(),
85 }
86 }
87}
88
89pub struct InfoCacheResp {
90 hits: u64,
91 misses: u64,
92 hit_ratio: f64,
93 entries: u64,
94 memory_bytes: u64,
95 max_bytes: usize,
96 block_size_bytes: usize,
97 evictions: u64,
98}
99
100impl From<InfoCacheResp> for BytesFrame {
101 fn from(resp: InfoCacheResp) -> Self {
102 map(indexmap! {
103 blob_str("hits") => number(resp.hits as i64),
104 blob_str("misses") => number(resp.misses as i64),
105 blob_str("hit_ratio") => double(resp.hit_ratio),
106 blob_str("entries") => number(resp.entries as i64),
107 blob_str("memory_bytes") => number(resp.memory_bytes as i64),
108 blob_str("max_bytes") => number(resp.max_bytes as i64),
109 blob_str("block_size_bytes") => number(resp.block_size_bytes as i64),
110 blob_str("evictions") => number(resp.evictions as i64),
111 })
112 }
113}