waratah_stats/
serde_bin.rs1use std::collections::BTreeMap;
4
5use waratah_storage::StrHash;
6
7use crate::StatsError;
8use crate::StatsProfile;
9use crate::cms::{CountMinSketch, take_u32, take_u64};
10use crate::hll::HyperLogLog;
11use crate::tick_histogram::TickHistogram;
12
13const MAGIC: &[u8; 4] = b"WST1";
14const VERSION: u16 = 4;
18const VERSION_V1: u16 = 1;
19const VERSION_V2: u16 = 2;
20const VERSION_V3: u16 = 3;
21
22pub fn to_bytes(profile: &StatsProfile) -> Vec<u8> {
24 let mut out = Vec::new();
25 out.extend_from_slice(MAGIC);
26 out.extend_from_slice(&VERSION.to_le_bytes());
27 out.extend_from_slice(&profile.total_puts.to_le_bytes());
28 encode_exact_map(&profile.predicate_counts, &mut out);
29 encode_exact_map(&profile.class_counts, &mut out);
30 profile.subject_cms.encode_body(&mut out);
31 profile.object_cms.encode_body(&mut out);
32 encode_hll_map(&profile.subjects_per_predicate, &mut out);
33 encode_hll_map(&profile.objects_per_predicate, &mut out);
34 out.extend_from_slice(&profile.named_graph_count.to_le_bytes());
35 profile.temporal_histogram.encode_body(&mut out);
36 profile.geo_cell_histogram.encode_body(&mut out);
37 out
38}
39
40pub fn from_bytes(bytes: &[u8]) -> Result<StatsProfile, StatsError> {
42 let mut buf = bytes;
43 if buf.len() < 6 || &buf[..4] != MAGIC {
44 return Err(StatsError::Corrupt("bad magic".into()));
45 }
46 buf = &buf[4..];
47 let version = u16::from_le_bytes(buf[..2].try_into().unwrap());
48 buf = &buf[2..];
49 if version != VERSION && version != VERSION_V1 && version != VERSION_V2 && version != VERSION_V3
50 {
51 return Err(StatsError::Corrupt(format!(
52 "unsupported version {version}"
53 )));
54 }
55 let total_puts = take_u64(&mut buf)?;
56 let predicate_counts = decode_exact_map(&mut buf)?;
57 let class_counts = decode_exact_map(&mut buf)?;
58 let subject_cms = CountMinSketch::decode_body(&mut buf)?;
59 let object_cms = CountMinSketch::decode_body(&mut buf)?;
60 let subjects_per_predicate = decode_hll_map(&mut buf)?;
61 let objects_per_predicate = decode_hll_map(&mut buf)?;
62 let named_graph_count = if version >= VERSION_V2 {
63 take_u64(&mut buf)?
64 } else {
65 0
66 };
67 let temporal_histogram = if version >= VERSION_V3 {
68 TickHistogram::decode_body(&mut buf)?
69 } else {
70 TickHistogram::default()
71 };
72 let geo_cell_histogram = if version >= VERSION {
73 crate::geo_cell_histogram::GeoCellHistogram::decode_body(&mut buf)?
74 } else {
75 crate::geo_cell_histogram::GeoCellHistogram::default()
76 };
77 if !buf.is_empty() {
78 return Err(StatsError::Corrupt(format!("{} trailing bytes", buf.len())));
79 }
80 Ok(StatsProfile {
81 total_puts,
82 predicate_counts,
83 class_counts,
84 subject_cms,
85 object_cms,
86 subjects_per_predicate,
87 objects_per_predicate,
88 subject_domains_per_predicate: BTreeMap::new(),
91 object_domains_per_predicate: BTreeMap::new(),
92 named_graph_count,
93 temporal_histogram,
94 geo_cell_histogram,
95 text_seed_sketch: crate::text_seed_sketch::TextSeedSketch::empty(),
98 })
99}
100
101fn encode_exact_map(map: &BTreeMap<StrHash, u64>, out: &mut Vec<u8>) {
102 out.extend_from_slice(&(map.len() as u32).to_le_bytes());
103 for (k, v) in map {
104 out.extend_from_slice(&k.to_be_bytes());
105 out.extend_from_slice(&v.to_le_bytes());
106 }
107}
108
109fn decode_exact_map(buf: &mut &[u8]) -> Result<BTreeMap<StrHash, u64>, StatsError> {
110 let n = take_u32(buf)? as usize;
111 let mut map = BTreeMap::new();
112 for _ in 0..n {
113 if buf.len() < 24 {
114 return Err(StatsError::Corrupt("truncated exact map entry".into()));
115 }
116 let hash = StrHash::from_be_bytes(buf[..16].try_into().unwrap());
117 *buf = &buf[16..];
118 let count = take_u64(buf)?;
119 map.insert(hash, count);
120 }
121 Ok(map)
122}
123
124fn encode_hll_map(map: &BTreeMap<StrHash, HyperLogLog>, out: &mut Vec<u8>) {
125 out.extend_from_slice(&(map.len() as u32).to_le_bytes());
126 for (k, hll) in map {
127 out.extend_from_slice(&k.to_be_bytes());
128 hll.encode_body(out);
129 }
130}
131
132fn decode_hll_map(buf: &mut &[u8]) -> Result<BTreeMap<StrHash, HyperLogLog>, StatsError> {
133 let n = take_u32(buf)? as usize;
134 let mut map = BTreeMap::new();
135 for _ in 0..n {
136 if buf.len() < 16 {
137 return Err(StatsError::Corrupt("truncated HLL map key".into()));
138 }
139 let hash = StrHash::from_be_bytes(buf[..16].try_into().unwrap());
140 *buf = &buf[16..];
141 let hll = HyperLogLog::decode_body(buf)?;
142 map.insert(hash, hll);
143 }
144 Ok(map)
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use crate::LiveQuadsProfile;
151 use crate::observe::observe_quad;
152 use waratah_storage::{NamedNode, StorageOp, encode_quad};
153
154 #[test]
155 fn round_trip_profile() {
156 let mut live = LiveQuadsProfile::default();
157 let q = encode_quad(&waratah_storage::Quad::new(
158 NamedNode::new("http://ex/a").unwrap(),
159 NamedNode::new("http://ex/p").unwrap(),
160 NamedNode::new("http://ex/o").unwrap(),
161 waratah_storage::GraphName::DefaultGraph,
162 ))
163 .unwrap();
164 observe_quad(&mut live, &q, StorageOp::Put);
165 let mut profile = StatsProfile::from(live);
166 profile.named_graph_count = 3;
167 let bytes = to_bytes(&profile);
168 let decoded = from_bytes(&bytes).unwrap();
169 assert_eq!(decoded.total_puts, 1);
170 assert_eq!(decoded.predicate_counts, profile.predicate_counts);
171 assert_eq!(decoded.named_graph_count, 3);
172 }
173
174 #[test]
175 fn round_trip_carries_geo_histogram() {
176 let mut hist = crate::geo_cell_histogram::GeoCellHistogram::default();
177 hist.observe_posting(0x0000_0000_0000_0001); hist.observe_posting(0x4000_0000_0000_0001); let profile = StatsProfile {
180 geo_cell_histogram: hist,
181 ..StatsProfile::default()
182 };
183 let decoded = from_bytes(&to_bytes(&profile)).unwrap();
184 assert_eq!(decoded.geo_cell_histogram, profile.geo_cell_histogram);
185 let v3 = {
187 let mut bytes = to_bytes(&profile);
188 let geo_section = 2 + 4 + 2 * 8 + 4 + 4;
191 bytes.truncate(bytes.len() - geo_section);
192 bytes[4..6].copy_from_slice(&3u16.to_le_bytes());
193 bytes
194 };
195 let decoded = from_bytes(&v3).unwrap();
196 assert!(decoded.geo_cell_histogram.is_empty());
197 }
198
199 #[test]
200 fn version_1_blob_decodes_with_zero_named_graph_count() {
201 let mut live = LiveQuadsProfile::default();
202 let q = encode_quad(&waratah_storage::Quad::new(
203 NamedNode::new("http://ex/a").unwrap(),
204 NamedNode::new("http://ex/p").unwrap(),
205 NamedNode::new("http://ex/o").unwrap(),
206 waratah_storage::GraphName::DefaultGraph,
207 ))
208 .unwrap();
209 observe_quad(&mut live, &q, StorageOp::Put);
210 let profile = StatsProfile::from(live);
211 let mut v1 = to_bytes(&profile);
212 v1.truncate(v1.len() - 8 - 46 - 14);
217 v1[4..6].copy_from_slice(&1u16.to_le_bytes());
218 let decoded = from_bytes(&v1).unwrap();
219 assert_eq!(decoded.total_puts, 1);
220 assert_eq!(decoded.named_graph_count, 0);
221 assert_eq!(decoded.temporal_histogram.total_postings(), 0);
222 assert!(decoded.geo_cell_histogram.is_empty());
223 }
224}