Skip to main content

datatypes/series/
raw.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(test)]
16mod tests;
17
18use arrow::buffer::{Buffer, ScalarBuffer};
19use snafu::OptionExt;
20
21use crate::error::{InvalidSeriesSnafu, Result};
22use crate::series::samples::{SeriesFields, SeriesSchema};
23use crate::series::{SeriesLabels, invalid_series};
24
25/// Strictly increasing source timestamps for a raw series chunk, in the unit of the source's time
26/// index.
27///
28/// Its private buffer ensures timestamps are validated once at construction. Direct
29/// construction is intentionally unavailable:
30///
31/// ```compile_fail
32/// use arrow::buffer::ScalarBuffer;
33/// use datatypes::series::raw::RawTimestamps;
34///
35/// let timestamps = RawTimestamps {
36///     values: ScalarBuffer::from(vec![1_i64, 2]),
37/// };
38/// ```
39#[derive(Clone, Debug)]
40pub struct RawTimestamps {
41    values: ScalarBuffer<i64>,
42}
43
44impl RawTimestamps {
45    /// Validates and wraps strictly increasing timestamps; an empty wrapper is valid.
46    pub fn try_new(values: ScalarBuffer<i64>) -> Result<Self> {
47        if values.windows(2).any(|pair| pair[0] >= pair[1]) {
48            return invalid_series("raw timestamps must be strictly increasing");
49        }
50        Ok(Self { values })
51    }
52
53    /// Returns the underlying timestamp buffer.
54    pub fn as_buffer(&self) -> &ScalarBuffer<i64> {
55        &self.values
56    }
57
58    /// Returns the number of timestamps.
59    pub fn len(&self) -> usize {
60        self.values.len()
61    }
62
63    /// Returns whether there are no timestamps.
64    pub fn is_empty(&self) -> bool {
65        self.values.is_empty()
66    }
67
68    /// Returns the timestamp at `index`, or `None` when out of bounds.
69    pub fn timestamp(&self, index: usize) -> Option<i64> {
70        self.values.get(index).copied()
71    }
72
73    /// Returns a zero-copy slice, reporting overflowing or out-of-range bounds as an error.
74    pub fn slice(&self, offset: usize, len: usize) -> Result<Self> {
75        let end = offset
76            .checked_add(len)
77            .with_context(|| InvalidSeriesSnafu {
78                reason: "raw timestamps slice bounds overflow".to_string(),
79            })?;
80        if end > self.len() {
81            return invalid_series("raw timestamps slice is out of bounds");
82        }
83        Ok(Self {
84            values: self.values.slice(offset, len),
85        })
86    }
87}
88
89impl AsRef<[i64]> for RawTimestamps {
90    fn as_ref(&self) -> &[i64] {
91        &self.values
92    }
93}
94
95/// One raw source batch, with fields aligned to its timestamps.
96///
97/// `metric: None` means labels are not yet decoded because identity is bound by the source; it
98/// does not mean the metric name is absent. An explicit `Some(metric)` is always complete.
99///
100/// Public fields allow direct access and construction, which bypasses the checks in
101/// [`RawSeriesChunk::try_new`]; callers crossing a trust boundary must validate input.
102#[derive(Clone, Debug)]
103pub struct RawSeriesChunk {
104    /// Complete identity of the source series, not a TSID or hash alone. Fragments of one
105    /// series read from different regions carry the same identity; only a stream declaring a
106    /// label decode specification requires a label-bearing key.
107    pub primary_key: Buffer,
108    /// `None` denotes an encoded key under bound-label mode; `Some` contains complete
109    /// explicit labels and retains their identity.
110    pub metric: Option<SeriesLabels>,
111    /// Source timestamps aligned with every field.
112    pub time: RawTimestamps,
113    /// Field values aligned with the source timestamps.
114    pub fields: SeriesFields,
115    /// Whether this is the final chunk for this series in the input stream exposing it.
116    /// Merge code must recompute finalization globally across all relevant inputs before
117    /// downstream finalization.
118    pub is_last: bool,
119}
120
121impl RawSeriesChunk {
122    /// Creates a nonempty chunk after checking its time axis and schema alignment.
123    ///
124    /// Validation is local to this chunk and does not verify ordering between chunks.
125    pub fn try_new(
126        schema: &SeriesSchema,
127        primary_key: Buffer,
128        metric: Option<SeriesLabels>,
129        time: RawTimestamps,
130        fields: SeriesFields,
131        is_last: bool,
132    ) -> Result<Self> {
133        if schema.eval_grid.is_some() {
134            return invalid_series("raw series schema cannot have an evaluation grid");
135        }
136        if fields.len() != schema.fields.len() {
137            return invalid_series("raw series field count does not match schema");
138        }
139        if fields.iter().any(|field| field.len() != time.len()) {
140            return invalid_series("raw series field length does not match time axis");
141        }
142        if time.is_empty() {
143            return invalid_series("raw series chunks must not be empty");
144        }
145        Ok(Self {
146            primary_key,
147            metric,
148            time,
149            fields,
150            is_last,
151        })
152    }
153}