1use std::collections::{BTreeMap, HashMap};
30
31use table::requests::{SEMANTIC_VALUE_MIXED, SEMANTIC_VALUE_UNKNOWN, validate_semantic_option};
32
33pub const METRIC_TYPE_COUNTER: &str = "counter";
37pub const METRIC_TYPE_UPDOWN_COUNTER: &str = "updown_counter";
38pub const METRIC_TYPE_GAUGE: &str = "gauge";
39pub const METRIC_TYPE_HISTOGRAM: &str = "histogram";
40pub const METRIC_TYPE_GAUGE_HISTOGRAM: &str = "gauge_histogram";
41pub const METRIC_TYPE_SUMMARY: &str = "summary";
42pub const METRIC_TYPE_INFO: &str = "info";
43pub const METRIC_TYPE_STATESET: &str = "stateset";
44
45pub fn openmetrics_unit_to_ucum(unit: &str) -> Option<&'static str> {
50 Some(match unit {
51 "seconds" => "s",
52 "celsius" => "Cel",
53 "meters" => "m",
54 "bytes" => "By",
55 "ratios" => "1",
56 "volts" => "V",
57 "amperes" => "A",
58 "joules" => "J",
59 "grams" => "g",
60 _ => return None,
61 })
62}
63
64#[derive(Debug, Default)]
66pub struct SemanticIndex {
67 tables: HashMap<String, BTreeMap<&'static str, String>>,
69}
70
71impl SemanticIndex {
72 pub fn is_empty(&self) -> bool {
73 self.tables.is_empty()
74 }
75
76 pub fn record_scalar(&mut self, table: &str, key: &'static str, value: &str) {
80 if let Some(scalars) = self.tables.get_mut(table) {
83 match scalars.get(key).map(String::as_str) {
84 Some(existing) if existing == value => {}
85 Some(SEMANTIC_VALUE_MIXED) | Some(SEMANTIC_VALUE_UNKNOWN) => {}
86 Some(_) => {
87 scalars.insert(key, collapse_value(key));
88 }
89 None => {
90 scalars.insert(key, value.to_string());
91 }
92 }
93 } else {
94 self.tables.insert(
95 table.to_string(),
96 BTreeMap::from([(key, value.to_string())]),
97 );
98 }
99 }
100
101 pub fn encode(&self, schema: &str) -> Option<String> {
105 if self.tables.is_empty() {
106 return None;
107 }
108 serde_json::to_string(&BTreeMap::from([(schema, &self.tables)])).ok()
109 }
110
111 fn merge_from(&mut self, other: &SemanticIndex) {
112 for (table, scalars) in &other.tables {
113 for (key, value) in scalars {
114 self.record_scalar(table, key, value);
115 }
116 }
117 }
118
119 #[cfg(test)]
120 fn options_of(&self, table: &str) -> Option<&BTreeMap<&'static str, String>> {
121 self.tables.get(table)
122 }
123}
124
125#[derive(Debug, Default)]
130pub struct SemanticIndexes {
131 default: SemanticIndex,
133 overrides: HashMap<String, SemanticIndex>,
135}
136
137impl SemanticIndexes {
138 pub fn is_empty(&self) -> bool {
139 self.default.is_empty() && self.overrides.values().all(SemanticIndex::is_empty)
140 }
141
142 pub fn index_for(&mut self, schema: Option<&str>) -> &mut SemanticIndex {
144 match schema {
145 None => &mut self.default,
146 Some(schema) => {
147 if !self.overrides.contains_key(schema) {
148 self.overrides
149 .insert(schema.to_string(), SemanticIndex::default());
150 }
151 self.overrides.get_mut(schema).expect("just inserted")
152 }
153 }
154 }
155
156 pub fn encode(&self, default_schema: &str) -> Option<String> {
161 if self.is_empty() {
162 return None;
163 }
164 let mut by_schema: BTreeMap<&str, &HashMap<String, BTreeMap<&'static str, String>>> =
165 BTreeMap::new();
166 let mut merged_default;
167 if let Some(aliased) = self.overrides.get(default_schema) {
168 merged_default = SemanticIndex::default();
169 merged_default.merge_from(&self.default);
170 merged_default.merge_from(aliased);
171 by_schema.insert(default_schema, &merged_default.tables);
172 } else if !self.default.is_empty() {
173 by_schema.insert(default_schema, &self.default.tables);
174 }
175 for (schema, index) in &self.overrides {
176 if schema != default_schema && !index.is_empty() {
177 by_schema.insert(schema, &index.tables);
178 }
179 }
180 serde_json::to_string(&by_schema).ok()
181 }
182}
183
184fn collapse_value(key: &str) -> String {
188 if validate_semantic_option(key, SEMANTIC_VALUE_MIXED) {
189 SEMANTIC_VALUE_MIXED.to_string()
190 } else {
191 SEMANTIC_VALUE_UNKNOWN.to_string()
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use table::requests::{
198 SEMANTIC_METRIC_METADATA_QUALITY, SEMANTIC_METRIC_TYPE, SEMANTIC_METRIC_UNIT,
199 };
200
201 use super::*;
202
203 type Decoded = BTreeMap<String, BTreeMap<String, BTreeMap<String, String>>>;
204
205 #[test]
206 fn test_scalar_recording_keeps_first_then_collapses_on_conflict() {
207 let mut index = SemanticIndex::default();
208 index.record_scalar("t", SEMANTIC_METRIC_TYPE, "counter");
209 index.record_scalar("t", SEMANTIC_METRIC_TYPE, "counter");
210 assert_eq!(
211 index
212 .options_of("t")
213 .unwrap()
214 .get(SEMANTIC_METRIC_TYPE)
215 .map(String::as_str),
216 Some("counter")
217 );
218
219 index.record_scalar("t", SEMANTIC_METRIC_TYPE, "gauge");
221 assert_eq!(
222 index
223 .options_of("t")
224 .unwrap()
225 .get(SEMANTIC_METRIC_TYPE)
226 .map(String::as_str),
227 Some("mixed")
228 );
229 index.record_scalar("t", SEMANTIC_METRIC_TYPE, "histogram");
231 assert_eq!(
232 index
233 .options_of("t")
234 .unwrap()
235 .get(SEMANTIC_METRIC_TYPE)
236 .map(String::as_str),
237 Some("mixed")
238 );
239 }
240
241 #[test]
242 fn test_scalar_conflict_without_mixed_domain_collapses_to_unknown() {
243 let mut index = SemanticIndex::default();
244 index.record_scalar("t", SEMANTIC_METRIC_METADATA_QUALITY, "declared");
245 index.record_scalar("t", SEMANTIC_METRIC_METADATA_QUALITY, "inferred");
246 assert_eq!(
249 index
250 .options_of("t")
251 .unwrap()
252 .get(SEMANTIC_METRIC_METADATA_QUALITY)
253 .map(String::as_str),
254 Some("unknown")
255 );
256 }
257
258 #[test]
259 fn test_encode_is_none_when_empty_and_round_trips() {
260 let index = SemanticIndex::default();
261 assert!(index.is_empty());
262 assert_eq!(index.encode("public"), None);
263
264 let mut index = SemanticIndex::default();
265 index.record_scalar("metric_a", SEMANTIC_METRIC_TYPE, "counter");
266 index.record_scalar("metric_a", SEMANTIC_METRIC_UNIT, "By");
267 let json = index.encode("public").unwrap();
268 let parsed: Decoded = serde_json::from_str(&json).unwrap();
269 let table = parsed.get("public").unwrap().get("metric_a").unwrap();
270 assert_eq!(
271 table.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
272 Some("counter")
273 );
274 assert_eq!(
275 table.get(SEMANTIC_METRIC_UNIT).map(String::as_str),
276 Some("By")
277 );
278 }
279
280 #[test]
281 fn test_indexes_keep_schemas_apart_and_merge_default_alias() {
282 let mut indexes = SemanticIndexes::default();
283 assert!(indexes.is_empty());
284 assert_eq!(indexes.encode("public"), None);
285
286 indexes
288 .index_for(None)
289 .record_scalar("cpu_usage", SEMANTIC_METRIC_TYPE, "counter");
290 indexes.index_for(Some("tenant_b")).record_scalar(
291 "cpu_usage",
292 SEMANTIC_METRIC_TYPE,
293 "gauge",
294 );
295 let parsed: Decoded = serde_json::from_str(&indexes.encode("public").unwrap()).unwrap();
296 assert_eq!(
297 parsed["public"]["cpu_usage"][SEMANTIC_METRIC_TYPE],
298 "counter"
299 );
300 assert_eq!(
301 parsed["tenant_b"]["cpu_usage"][SEMANTIC_METRIC_TYPE],
302 "gauge"
303 );
304
305 indexes
308 .index_for(Some("public"))
309 .record_scalar("cpu_usage", SEMANTIC_METRIC_TYPE, "gauge");
310 let parsed: Decoded = serde_json::from_str(&indexes.encode("public").unwrap()).unwrap();
311 assert_eq!(parsed["public"]["cpu_usage"][SEMANTIC_METRIC_TYPE], "mixed");
312 }
313
314 #[test]
315 fn test_openmetrics_unit_mapping() {
316 assert_eq!(openmetrics_unit_to_ucum("seconds"), Some("s"));
317 assert_eq!(openmetrics_unit_to_ucum("bytes"), Some("By"));
318 assert_eq!(openmetrics_unit_to_ucum("ratios"), Some("1"));
319 assert_eq!(openmetrics_unit_to_ucum("requests"), None);
321 assert_eq!(openmetrics_unit_to_ucum(""), None);
322 assert_eq!(openmetrics_unit_to_ucum("By"), None);
324 }
325}