use crate::block::BlockReader;
use crate::chunkenc::{
self, CounterResetHint, DecodeLimits, FloatHistogramSample, IntHistogramSample, SampleSink,
Span,
};
use crate::chunks::ChunkReader;
use crate::error::{Error, Result};
use crate::index::{IndexReader, SeriesRef};
use crate::tombstones::{self, Tombstones};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeRange {
pub start: i64,
pub end: i64,
}
impl TimeRange {
pub const fn new(start: i64, end: i64) -> Self {
Self { start, end }
}
pub const fn all() -> Self {
Self {
start: i64::MIN,
end: i64::MAX,
}
}
pub const fn is_empty(&self) -> bool {
self.end <= self.start
}
pub const fn contains(&self, ts: i64) -> bool {
ts >= self.start && ts < self.end
}
pub const fn overlaps_chunk(&self, mint: i64, maxt: i64) -> bool {
maxt >= self.start && mint < self.end
}
}
impl Default for TimeRange {
fn default() -> Self {
Self::all()
}
}
#[derive(Debug, Clone)]
pub struct SampleIterOptions {
pub range: TimeRange,
pub skip_deleted: bool,
pub strict_order: bool,
pub limits: DecodeLimits,
}
impl Default for SampleIterOptions {
fn default() -> Self {
Self {
range: TimeRange::all(),
skip_deleted: true,
strict_order: true,
limits: DecodeLimits::default(),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Sample<'a> {
pub series: &'a SeriesRef,
pub timestamp: i64,
pub value: SampleValue<'a>,
}
#[derive(Debug, Clone, Copy)]
pub enum SampleValue<'a> {
Float(f64),
IntHistogram(IntHistogramSample<'a>),
FloatHistogram(FloatHistogramSample<'a>),
}
pub struct SampleIterator<'a> {
index: &'a IndexReader,
chunks: &'a ChunkReader,
tombstones: &'a Tombstones,
opts: SampleIterOptions,
series_iter: crate::index::SeriesIter<'a>,
series: Option<SeriesRef>,
chunk_idx: usize,
deleted: Vec<(i64, i64)>,
series_key: String,
pending: Pending,
cursor: usize,
last_ts: Option<i64>,
done: bool,
samples_emitted: u64,
chunks_decoded: u64,
samples_filtered: u64,
}
impl<'a> SampleIterator<'a> {
pub fn new(
index: &'a IndexReader,
chunks: &'a ChunkReader,
tombstones: &'a Tombstones,
opts: SampleIterOptions,
) -> Self {
Self {
index,
chunks,
tombstones,
opts,
series_iter: index.series(0),
series: None,
chunk_idx: 0,
deleted: Vec::new(),
series_key: String::new(),
pending: Pending::default(),
cursor: 0,
last_ts: None,
done: false,
samples_emitted: 0,
chunks_decoded: 0,
samples_filtered: 0,
}
}
pub fn options(&self) -> &SampleIterOptions {
&self.opts
}
pub fn index(&self) -> &'a IndexReader {
self.index
}
pub fn samples_emitted(&self) -> u64 {
self.samples_emitted
}
pub fn chunks_decoded(&self) -> u64 {
self.chunks_decoded
}
pub fn samples_filtered(&self) -> u64 {
self.samples_filtered
}
pub fn next_sample(&mut self) -> Result<Option<Sample<'_>>> {
loop {
if self.cursor < self.pending.len() {
let ts = self.pending.ts(self.cursor);
let inside = self.opts.range.contains(ts);
let deleted = self.opts.skip_deleted && tombstone_hit(&self.deleted, ts);
if let Some(last) = self.last_ts {
if self.opts.strict_order && ts < last {
return Err(Error::corrupt(format!(
"series {}: timestamp {ts} goes backwards (previous {last})",
self.series_key
)));
}
}
let idx = self.cursor;
self.cursor += 1;
if !inside || deleted {
self.samples_filtered += 1;
continue;
}
self.last_ts = Some(ts);
self.samples_emitted += 1;
let series = self.series.as_ref().expect("a series is loaded");
let value = self.pending.value(idx);
return Ok(Some(Sample {
series,
timestamp: ts,
value,
}));
}
if !self.load_next_chunk()? {
self.done = true;
return Ok(None);
}
}
}
fn load_next_chunk(&mut self) -> Result<bool> {
loop {
if self.done {
return Ok(false);
}
let Some(series) = self.series.as_ref() else {
if !self.advance_series()? {
return Ok(false);
}
continue;
};
if self.chunk_idx >= series.chunks.len() {
if !self.advance_series()? {
return Ok(false);
}
continue;
}
let chunk = series.chunks[self.chunk_idx];
self.chunk_idx += 1;
if !self
.opts
.range
.overlaps_chunk(chunk.min_time, chunk.max_time)
{
continue;
}
self.pending.reset();
let slice = self.chunks.chunk(chunk.reference).map_err(|e| {
contextual(
format!(
"series {} chunk {} (ref {:#x})",
self.series_key,
self.chunk_idx - 1,
chunk.reference
),
e,
)
})?;
let outcome = chunkenc::decode_with_limits(
slice.encoding,
slice.data,
&self.opts.limits,
&mut self.pending,
)
.map_err(|e| {
contextual(
format!(
"series {} chunk {} (ref {:#x}, encoding {})",
self.series_key,
self.chunk_idx - 1,
chunk.reference,
chunkenc::encoding_name(slice.encoding)
),
e,
)
})?;
self.chunks_decoded += 1;
if outcome.samples() == 0 {
continue;
}
self.cursor = 0;
return Ok(true);
}
}
fn advance_series(&mut self) -> Result<bool> {
loop {
let Some(next) = self.series_iter.next() else {
self.series = None;
return Ok(false);
};
let series = next?;
let intersects = match (series.min_time(), series.max_time()) {
(Some(mint), Some(maxt)) => self.opts.range.overlaps_chunk(mint, maxt),
_ => false,
};
if !intersects {
continue;
}
self.series_key = series_key(&series);
self.deleted.clear();
if self.opts.skip_deleted {
self.deleted
.extend_from_slice(self.tombstones.intervals(series.id));
}
self.series = Some(series);
self.chunk_idx = 0;
self.last_ts = None;
return Ok(true);
}
}
}
impl BlockReader {
pub fn samples(&self, range: TimeRange) -> SampleIterator<'_> {
self.samples_with(SampleIterOptions {
range,
..SampleIterOptions::default()
})
}
pub fn samples_with(&self, opts: SampleIterOptions) -> SampleIterator<'_> {
SampleIterator::new(self.index(), self.chunk_reader(), self.tombstones(), opts)
}
}
fn series_key(series: &SeriesRef) -> String {
let mut out = String::new();
for (i, (n, v)) in series.labels.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(n);
out.push('=');
out.push_str(v);
}
out
}
fn contextual(prefix: String, err: Error) -> Error {
match err {
Error::Format(m) => Error::Format(format!("{prefix}: {m}")),
Error::Decode(m) => Error::Decode(format!("{prefix}: {m}")),
Error::Corrupt(m) => Error::Corrupt(format!("{prefix}: {m}")),
Error::Checksum(s) => Error::Corrupt(format!("{prefix}: checksum mismatch in {s}")),
Error::Eof(off) => {
Error::Corrupt(format!("{prefix}: unexpected end of data at byte {off}"))
}
other => other,
}
}
fn tombstone_hit(intervals: &[(i64, i64)], ts: i64) -> bool {
if intervals.is_empty() {
return false;
}
tombstone_is_deleted(intervals, ts)
}
fn tombstone_is_deleted(intervals: &[(i64, i64)], ts: i64) -> bool {
tombstones::is_deleted(intervals, ts)
}
#[derive(Default)]
struct Pending {
items: Vec<Item>,
len: usize,
}
enum Item {
Float { ts: i64, value: f64 },
Int(OwnedIntHistogram),
FloatHist(OwnedFloatHistogram),
}
impl Default for Item {
fn default() -> Self {
Item::Float { ts: 0, value: 0.0 }
}
}
impl Pending {
fn reset(&mut self) {
self.len = 0;
}
fn len(&self) -> usize {
self.len
}
fn ts(&self, idx: usize) -> i64 {
match &self.items[idx] {
Item::Float { ts, .. } => *ts,
Item::Int(h) => h.ts,
Item::FloatHist(h) => h.ts,
}
}
fn value(&self, idx: usize) -> SampleValue<'_> {
match &self.items[idx] {
Item::Float { value, .. } => SampleValue::Float(*value),
Item::Int(h) => SampleValue::IntHistogram(h.view()),
Item::FloatHist(h) => SampleValue::FloatHistogram(h.view()),
}
}
fn slot(&mut self) -> usize {
let idx = self.len;
if idx >= self.items.len() {
self.items.push(Item::default());
}
self.len += 1;
idx
}
}
impl SampleSink for Pending {
fn push_float(&mut self, ts: i64, value: f64) {
let idx = self.slot();
self.items[idx] = Item::Float { ts, value };
}
fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>) {
let idx = self.slot();
match &mut self.items[idx] {
Item::Int(owned) => owned.set(h),
slot => *slot = Item::Int(OwnedIntHistogram::from_sample(h)),
}
}
fn push_float_histogram(&mut self, h: &FloatHistogramSample<'_>) {
let idx = self.slot();
match &mut self.items[idx] {
Item::FloatHist(owned) => owned.set(h),
slot => *slot = Item::FloatHist(OwnedFloatHistogram::from_sample(h)),
}
}
}
struct OwnedIntHistogram {
ts: i64,
st: i64,
count: u64,
zero_count: u64,
sum: f64,
schema: i32,
zero_threshold: f64,
pos_spans: Vec<Span>,
neg_spans: Vec<Span>,
pos_counts: Vec<i64>,
neg_counts: Vec<i64>,
pos_deltas: Vec<i64>,
neg_deltas: Vec<i64>,
custom_values: Vec<f64>,
chunk_reset_hint: CounterResetHint,
counter_reset_hint: CounterResetHint,
}
impl OwnedIntHistogram {
fn from_sample(h: &IntHistogramSample<'_>) -> Self {
let mut out = Self {
ts: 0,
st: 0,
count: 0,
zero_count: 0,
sum: 0.0,
schema: 0,
zero_threshold: 0.0,
pos_spans: Vec::new(),
neg_spans: Vec::new(),
pos_counts: Vec::new(),
neg_counts: Vec::new(),
pos_deltas: Vec::new(),
neg_deltas: Vec::new(),
custom_values: Vec::new(),
chunk_reset_hint: CounterResetHint::Unknown,
counter_reset_hint: CounterResetHint::Unknown,
};
out.set(h);
out
}
fn set(&mut self, h: &IntHistogramSample<'_>) {
self.ts = h.ts;
self.st = h.st;
self.count = h.count;
self.zero_count = h.zero_count;
self.sum = h.sum;
self.schema = h.schema;
self.zero_threshold = h.zero_threshold;
copy_spans(&mut self.pos_spans, h.pos_spans);
copy_spans(&mut self.neg_spans, h.neg_spans);
self.pos_counts.clear();
self.pos_counts.extend_from_slice(h.pos_counts);
self.neg_counts.clear();
self.neg_counts.extend_from_slice(h.neg_counts);
self.pos_deltas.clear();
self.pos_deltas.extend_from_slice(h.pos_deltas);
self.neg_deltas.clear();
self.neg_deltas.extend_from_slice(h.neg_deltas);
self.custom_values.clear();
self.custom_values.extend_from_slice(h.custom_values);
self.chunk_reset_hint = h.chunk_reset_hint;
self.counter_reset_hint = h.counter_reset_hint;
}
fn view(&self) -> IntHistogramSample<'_> {
IntHistogramSample {
ts: self.ts,
st: self.st,
count: self.count,
zero_count: self.zero_count,
sum: self.sum,
schema: self.schema,
zero_threshold: self.zero_threshold,
pos_spans: &self.pos_spans,
neg_spans: &self.neg_spans,
pos_counts: &self.pos_counts,
neg_counts: &self.neg_counts,
pos_deltas: &self.pos_deltas,
neg_deltas: &self.neg_deltas,
custom_values: &self.custom_values,
chunk_reset_hint: self.chunk_reset_hint,
counter_reset_hint: self.counter_reset_hint,
}
}
}
struct OwnedFloatHistogram {
ts: i64,
st: i64,
count: f64,
zero_count: f64,
sum: f64,
schema: i32,
zero_threshold: f64,
pos_spans: Vec<Span>,
neg_spans: Vec<Span>,
pos_buckets: Vec<f64>,
neg_buckets: Vec<f64>,
custom_values: Vec<f64>,
chunk_reset_hint: CounterResetHint,
counter_reset_hint: CounterResetHint,
}
impl OwnedFloatHistogram {
fn from_sample(h: &FloatHistogramSample<'_>) -> Self {
let mut out = Self {
ts: 0,
st: 0,
count: 0.0,
zero_count: 0.0,
sum: 0.0,
schema: 0,
zero_threshold: 0.0,
pos_spans: Vec::new(),
neg_spans: Vec::new(),
pos_buckets: Vec::new(),
neg_buckets: Vec::new(),
custom_values: Vec::new(),
chunk_reset_hint: CounterResetHint::Unknown,
counter_reset_hint: CounterResetHint::Unknown,
};
out.set(h);
out
}
fn set(&mut self, h: &FloatHistogramSample<'_>) {
self.ts = h.ts;
self.st = h.st;
self.count = h.count;
self.zero_count = h.zero_count;
self.sum = h.sum;
self.schema = h.schema;
self.zero_threshold = h.zero_threshold;
copy_spans(&mut self.pos_spans, h.pos_spans);
copy_spans(&mut self.neg_spans, h.neg_spans);
self.pos_buckets.clear();
self.pos_buckets.extend_from_slice(h.pos_buckets);
self.neg_buckets.clear();
self.neg_buckets.extend_from_slice(h.neg_buckets);
self.custom_values.clear();
self.custom_values.extend_from_slice(h.custom_values);
self.chunk_reset_hint = h.chunk_reset_hint;
self.counter_reset_hint = h.counter_reset_hint;
}
fn view(&self) -> FloatHistogramSample<'_> {
FloatHistogramSample {
ts: self.ts,
st: self.st,
count: self.count,
zero_count: self.zero_count,
sum: self.sum,
schema: self.schema,
zero_threshold: self.zero_threshold,
pos_spans: &self.pos_spans,
neg_spans: &self.neg_spans,
pos_buckets: &self.pos_buckets,
neg_buckets: &self.neg_buckets,
custom_values: &self.custom_values,
chunk_reset_hint: self.chunk_reset_hint,
counter_reset_hint: self.counter_reset_hint,
}
}
}
fn copy_spans(dst: &mut Vec<Span>, src: &[Span]) {
dst.clear();
dst.extend_from_slice(src);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn range_translation_is_half_open() {
let r = TimeRange::new(100, 200);
assert!(r.contains(100));
assert!(r.contains(199));
assert!(!r.contains(200));
assert!(r.overlaps_chunk(199, 300));
assert!(!r.overlaps_chunk(50, 99));
assert!(!r.overlaps_chunk(200, 300));
assert!(TimeRange::new(5, 5).is_empty());
assert!(TimeRange::all().contains(i64::MIN));
}
#[test]
fn pending_buffer_is_reused() {
let mut p = Pending::default();
p.push_float(1, 2.0);
p.push_float(3, 4.0);
assert_eq!(p.len(), 2);
assert_eq!(p.ts(1), 3);
matches!(p.value(0), SampleValue::Float(_));
let capacity = p.items.capacity();
p.reset();
assert_eq!(p.len(), 0);
assert_eq!(p.items.capacity(), capacity);
p.push_float(5, 6.0);
assert_eq!(p.ts(0), 5);
}
#[test]
fn integer_histogram_slots_keep_their_buffers() {
let mut p = Pending::default();
let sample = IntHistogramSample {
ts: 10,
st: 0,
count: 1 << 60,
zero_count: 0,
sum: 1.0,
schema: 1,
zero_threshold: 0.0,
pos_spans: &[Span {
offset: 0,
length: 1,
}],
neg_spans: &[],
pos_counts: &[1 << 40],
neg_counts: &[],
pos_deltas: &[1 << 40],
neg_deltas: &[],
custom_values: &[],
chunk_reset_hint: CounterResetHint::Unknown,
counter_reset_hint: CounterResetHint::NotCounterReset,
};
p.push_int_histogram(&sample);
match p.value(0) {
SampleValue::IntHistogram(v) => {
assert_eq!(v.count, 1 << 60);
assert_eq!(v.pos_counts, &[1 << 40]);
assert_eq!(v.counter_reset_hint, CounterResetHint::NotCounterReset);
}
other => panic!("expected an integer histogram, got {other:?}"),
}
}
}