Skip to main content

tsdb_reader/index/
label_index.rs

1//! Label lookups behind a trait, so a query layer can treat any label space
2//! uniformly.
3//!
4//! `IndexReader` is the only implementation today; the trait exists so that
5//! higher layers (a block set, a PromQL series source, a test double) can be
6//! written against label access without depending on the concrete reader.
7
8use crate::error::Result;
9
10use super::IndexReader;
11
12/// Read-only access to the label space of an index.
13///
14/// Both methods are sorted and deduplicated, which is what the index guarantees
15/// on disk: names are returned in lexicographic order and exclude the internal
16/// all-series key, and the values of one name follow the index's order.
17///
18/// The trait is object safe, so `&dyn LabelIndexReader` works.
19pub trait LabelIndexReader {
20    /// All label names present in the block, sorted.
21    fn label_names(&self) -> Result<Vec<String>>;
22
23    /// All values of `name`, sorted; empty when the name is absent.
24    fn label_values(&self, name: &str) -> Result<Vec<String>>;
25}
26
27impl LabelIndexReader for IndexReader {
28    fn label_names(&self) -> Result<Vec<String>> {
29        IndexReader::label_names(self)
30    }
31
32    fn label_values(&self, name: &str) -> Result<Vec<String>> {
33        IndexReader::label_values(self, name)
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40    use std::path::PathBuf;
41
42    fn index() -> IndexReader {
43        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
44            .join("tests/data/block/01M70C8VV61N5H5VWXB17HQQ1R/index");
45        IndexReader::open(&path, true).unwrap()
46    }
47
48    #[test]
49    fn trait_matches_the_inherent_methods() {
50        let index = index();
51        let via_trait: &dyn LabelIndexReader = &index;
52        assert_eq!(
53            via_trait.label_names().unwrap(),
54            IndexReader::label_names(&index).unwrap()
55        );
56        for name in via_trait.label_names().unwrap() {
57            assert_eq!(
58                via_trait.label_values(&name).unwrap(),
59                IndexReader::label_values(&index, &name).unwrap()
60            );
61        }
62        assert!(via_trait.label_values("absent").unwrap().is_empty());
63    }
64
65    #[test]
66    fn names_exclude_the_all_series_key_and_stay_sorted() {
67        let index = index();
68        let names = LabelIndexReader::label_names(&index).unwrap();
69        assert!(!names.iter().any(|n| n.is_empty()));
70        let mut sorted = names.clone();
71        sorted.sort();
72        assert_eq!(names, sorted);
73    }
74}