tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! Label lookups behind a trait, so a query layer can treat any label space
//! uniformly.
//!
//! `IndexReader` is the only implementation today; the trait exists so that
//! higher layers (a block set, a PromQL series source, a test double) can be
//! written against label access without depending on the concrete reader.

use crate::error::Result;

use super::IndexReader;

/// Read-only access to the label space of an index.
///
/// Both methods are sorted and deduplicated, which is what the index guarantees
/// on disk: names are returned in lexicographic order and exclude the internal
/// all-series key, and the values of one name follow the index's order.
///
/// The trait is object safe, so `&dyn LabelIndexReader` works.
pub trait LabelIndexReader {
    /// All label names present in the block, sorted.
    fn label_names(&self) -> Result<Vec<String>>;

    /// All values of `name`, sorted; empty when the name is absent.
    fn label_values(&self, name: &str) -> Result<Vec<String>>;
}

impl LabelIndexReader for IndexReader {
    fn label_names(&self) -> Result<Vec<String>> {
        IndexReader::label_names(self)
    }

    fn label_values(&self, name: &str) -> Result<Vec<String>> {
        IndexReader::label_values(self, name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn index() -> IndexReader {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/data/block/01M70C8VV61N5H5VWXB17HQQ1R/index");
        IndexReader::open(&path, true).unwrap()
    }

    #[test]
    fn trait_matches_the_inherent_methods() {
        let index = index();
        let via_trait: &dyn LabelIndexReader = &index;
        assert_eq!(
            via_trait.label_names().unwrap(),
            IndexReader::label_names(&index).unwrap()
        );
        for name in via_trait.label_names().unwrap() {
            assert_eq!(
                via_trait.label_values(&name).unwrap(),
                IndexReader::label_values(&index, &name).unwrap()
            );
        }
        assert!(via_trait.label_values("absent").unwrap().is_empty());
    }

    #[test]
    fn names_exclude_the_all_series_key_and_stay_sorted() {
        let index = index();
        let names = LabelIndexReader::label_names(&index).unwrap();
        assert!(!names.iter().any(|n| n.is_empty()));
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
    }
}