Skip to main content

mito2/series_index/columnar/
metadata.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//! Explicit little-endian framing and the two-level metadata index.
16
17use crate::error::Result;
18use crate::series_index::columnar::codec::{
19    self, Compression, Cursor, put_string, put_u32, put_u64,
20};
21use crate::series_index::columnar::{VERSION, invalid, require, unsupported};
22use crate::series_index::{MetricSeriesId, ROW_COUNT_COLUMN, TSID_COLUMN};
23
24pub(crate) const MAGIC: &[u8; 8] = b"GTSERIES";
25pub(crate) const HEADER_SIZE: u64 = 16;
26pub(crate) const TRAILER_SIZE: u64 = 96;
27pub(crate) const PAGE_TARGET: usize = 65536;
28pub(crate) const PAGE_LIMIT: usize = 8 * 1024 * 1024;
29pub(crate) const PAGE_STORED_LIMIT: usize = PAGE_LIMIT + PAGE_TARGET;
30pub(crate) const ROOT_CAPACITY: usize = (PAGE_TARGET - 12) / 56;
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub(crate) struct PayloadReference {
34    pub(crate) offset: u64,
35    pub(crate) stored: u32,
36    pub(crate) decoded: u32,
37    pub(crate) checksum: u64,
38    pub(crate) encoding: u16,
39    pub(crate) compression: u16,
40}
41impl PayloadReference {
42    pub(crate) fn end(&self) -> Result<u64> {
43        self.offset
44            .checked_add(u64::from(self.stored))
45            .ok_or_else(|| invalid("series offset overflow"))
46    }
47    pub(crate) fn validate(&self, start: u64, end: u64, page: bool) -> Result<()> {
48        let (decoded_limit, stored_limit) = if page {
49            (PAGE_LIMIT, PAGE_STORED_LIMIT)
50        } else {
51            (codec::COLUMN_LIMIT, codec::COLUMN_STORED_LIMIT)
52        };
53        require(
54            self.stored > 0
55                && self.decoded > 0
56                && self.stored as usize <= stored_limit
57                && self.decoded as usize <= decoded_limit,
58            "series payload exceeds size limits",
59        )?;
60        require(
61            self.offset >= start && self.end()? <= end,
62            "series payload outside its area",
63        )
64    }
65    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
66        put_u64(out, self.offset);
67        put_u32(out, self.stored);
68        put_u32(out, self.decoded);
69        put_u64(out, self.checksum);
70        out.extend(self.encoding.to_le_bytes());
71        out.extend(self.compression.to_le_bytes());
72        put_u32(out, 0);
73    }
74    pub(crate) fn decode(c: &mut Cursor<'_>) -> Result<Self> {
75        let reference = Self {
76            offset: c.u64()?,
77            stored: c.u32()?,
78            decoded: c.u32()?,
79            checksum: c.u64()?,
80            encoding: c.u16()?,
81            compression: c.u16()?,
82        };
83        require(c.u32()? == 0, "nonzero series reference reserved field")?;
84        Ok(reference)
85    }
86    pub(crate) fn unpack(&self, bytes: &[u8]) -> Result<Vec<u8>> {
87        require(
88            bytes.len() == self.stored as usize,
89            "series payload length mismatch",
90        )?;
91        codec::decompress(bytes, self.compression, self.decoded as usize)
92    }
93}
94
95pub(crate) fn pack(
96    bytes: &[u8],
97    offset: u64,
98    encoding: u16,
99    compression: Compression,
100    level: i32,
101    page: bool,
102) -> Result<(PayloadReference, Vec<u8>)> {
103    let limit = if page {
104        PAGE_LIMIT
105    } else {
106        codec::COLUMN_LIMIT
107    };
108    require(
109        !bytes.is_empty() && bytes.len() <= limit,
110        "series decoded payload exceeds size limit",
111    )?;
112    let stored = codec::compress(bytes, compression, level)?;
113    let reference = PayloadReference {
114        offset,
115        stored: u32::try_from(stored.len())
116            .map_err(|_| invalid("series stored length overflow"))?,
117        decoded: bytes.len() as u32,
118        checksum: codec::checksum(&stored),
119        encoding,
120        compression: compression as u16,
121    };
122    reference.validate(offset, reference.end()?, page)?;
123    Ok((reference, stored))
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127pub(crate) struct PageReference {
128    pub(crate) first: MetricSeriesId,
129    pub(crate) last: MetricSeriesId,
130    pub(crate) payload: PayloadReference,
131}
132impl PageReference {
133    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
134        put_u32(out, self.first.table_id);
135        put_u64(out, self.first.tsid);
136        put_u32(out, self.last.table_id);
137        put_u64(out, self.last.tsid);
138        self.payload.encode(out);
139    }
140    pub(crate) fn decode(c: &mut Cursor<'_>) -> Result<Self> {
141        let first = MetricSeriesId {
142            table_id: c.u32()?,
143            tsid: c.u64()?,
144        };
145        let last = MetricSeriesId {
146            table_id: c.u32()?,
147            tsid: c.u64()?,
148        };
149        require(first <= last, "reversed series page bounds")?;
150        Ok(Self {
151            first,
152            last,
153            payload: PayloadReference::decode(c)?,
154        })
155    }
156}
157
158#[derive(Debug, Clone)]
159pub(crate) struct Column {
160    pub(crate) name: String,
161    pub(crate) payload: PayloadReference,
162    pub(crate) null_count: u32,
163    pub(crate) bounds: Option<(String, String)>,
164}
165#[derive(Debug, Clone)]
166pub(crate) struct Block {
167    pub(crate) table_id: u32,
168    pub(crate) first: u64,
169    pub(crate) last: u64,
170    pub(crate) rows: u32,
171    pub(crate) columns: Vec<Column>,
172}
173impl Block {
174    pub(crate) fn first_id(&self) -> MetricSeriesId {
175        MetricSeriesId {
176            table_id: self.table_id,
177            tsid: self.first,
178        }
179    }
180    pub(crate) fn last_id(&self) -> MetricSeriesId {
181        MetricSeriesId {
182            table_id: self.table_id,
183            tsid: self.last,
184        }
185    }
186    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
187        put_u32(out, self.table_id);
188        put_u64(out, self.first);
189        put_u64(out, self.last);
190        put_u32(out, self.rows);
191        put_u32(out, self.columns.len() as u32);
192        for column in &self.columns {
193            put_string(out, &column.name);
194            column.payload.encode(out);
195            put_u32(out, column.null_count);
196            if let Some((min, max)) = &column.bounds {
197                put_u32(out, 1);
198                put_string(out, min);
199                put_string(out, max);
200            } else {
201                put_u32(out, 0);
202            }
203        }
204    }
205    fn decode(
206        c: &mut Cursor<'_>,
207        names: &[String],
208        payload_end: u64,
209        previous_end: &mut u64,
210    ) -> Result<Self> {
211        let table_id = c.u32()?;
212        let first = c.u64()?;
213        let last = c.u64()?;
214        let rows = c.u32()?;
215        let count = c.u32()? as usize;
216        // `first`/`last` are the coarse `(table_id, tsid)` prefix, so several rows may
217        // share one identifier when their exact keys differ. Only their order is fixed,
218        // so the count is bounded by the block limit and not by the identifier span.
219        require(
220            rows > 0 && rows as usize <= codec::COLUMN_LIMIT / 8 && first <= last,
221            "invalid series block bounds/count",
222        )?;
223        require(
224            count >= 2 && count <= names.len() && count <= c.remaining() / 48,
225            "invalid series column count",
226        )?;
227        let mut columns = Vec::with_capacity(count);
228        let mut next_name = 0;
229        for index in 0..count {
230            let name = c.string()?;
231            let position = names[next_name..]
232                .iter()
233                .position(|n| *n == name)
234                .map(|p| p + next_name)
235                .ok_or_else(|| invalid("unknown or unordered series column"))?;
236            require(
237                index >= 2 || position == index,
238                "missing required series column",
239            )?;
240            next_name = position + 1;
241            let payload = PayloadReference::decode(c)?;
242            payload.validate(*previous_end, payload_end, false)?;
243            *previous_end = payload.end()?;
244            let null_count = c.u32()?;
245            require(null_count <= rows, "invalid series null count")?;
246            let bounds = match c.u32()? {
247                0 => None,
248                1 => {
249                    let min = c.string()?;
250                    let max = c.string()?;
251                    require(min <= max, "reversed string bounds")?;
252                    Some((min, max))
253                }
254                _ => return Err(unsupported("series statistics kind")),
255            };
256            if name == TSID_COLUMN || name == ROW_COUNT_COLUMN {
257                require(
258                    null_count == 0 && bounds.is_none(),
259                    "invalid integer column statistics",
260                )?;
261            } else {
262                require(
263                    bounds.is_some() == (null_count < rows),
264                    "missing or invalid string statistics",
265                )?;
266            }
267            columns.push(Column {
268                name,
269                payload,
270                null_count,
271                bounds,
272            });
273        }
274        require(
275            columns.iter().take(2).all(|column| {
276                column.payload.encoding != codec::INTEGER || rows <= column.payload.decoded
277            }),
278            "series row count exceeds integer payload lengths",
279        )?;
280        Ok(Self {
281            table_id,
282            first,
283            last,
284            rows,
285            columns,
286        })
287    }
288}
289
290#[derive(Debug)]
291pub(crate) enum Page {
292    Leaf(Vec<Block>),
293    Internal(Vec<PageReference>),
294}
295impl Page {
296    pub(crate) fn blocks(&self) -> Result<&[Block]> {
297        match self {
298            Self::Leaf(blocks) => Ok(blocks),
299            Self::Internal(_) => Err(unsupported("expected a series metadata leaf")),
300        }
301    }
302
303    pub(crate) fn retained_size(&self) -> usize {
304        std::mem::size_of::<Self>()
305            + match self {
306                Self::Internal(children) => {
307                    children.capacity() * std::mem::size_of::<PageReference>()
308                }
309                Self::Leaf(blocks) => {
310                    blocks.capacity() * std::mem::size_of::<Block>()
311                        + blocks
312                            .iter()
313                            .map(|block| {
314                                block.columns.capacity() * std::mem::size_of::<Column>()
315                                    + block
316                                        .columns
317                                        .iter()
318                                        .map(|column| {
319                                            column.name.capacity()
320                                                + column.bounds.as_ref().map_or(0, |(min, max)| {
321                                                    min.capacity() + max.capacity()
322                                                })
323                                        })
324                                        .sum::<usize>()
325                            })
326                            .sum::<usize>()
327                }
328            }
329    }
330
331    pub(crate) fn encode(&self) -> Vec<u8> {
332        let mut out = Vec::new();
333        match self {
334            Self::Leaf(blocks) => {
335                put_u32(&mut out, 0);
336                put_u64(&mut out, blocks.len() as u64);
337                for block in blocks {
338                    block.encode(&mut out);
339                }
340            }
341            Self::Internal(children) => {
342                put_u32(&mut out, 1);
343                put_u64(&mut out, children.len() as u64);
344                for child in children {
345                    child.encode(&mut out);
346                }
347            }
348        }
349        out
350    }
351    pub(crate) fn decode(
352        bytes: &[u8],
353        reference: &PageReference,
354        depth: u32,
355        payload_end: u64,
356        names: &[String],
357    ) -> Result<Self> {
358        let mut c = Cursor::new(bytes);
359        let kind = c.u32()?;
360        let count = c.length()?;
361        require(count > 0, "empty series metadata page")?;
362        let (page, first, last) = match (kind, depth) {
363            (0, 1) => {
364                require(
365                    count <= c.remaining() / 28,
366                    "series block count exceeds page",
367                )?;
368                let mut blocks: Vec<Block> = Vec::new();
369                let mut end = HEADER_SIZE;
370                for _ in 0..count {
371                    let block = Block::decode(&mut c, names, payload_end, &mut end)?;
372                    if let Some(previous) = blocks.last() {
373                        // Bounds are the coarse `(table_id, tsid)` prefix and stay
374                        // conservative: two blocks may share one prefix when their exact
375                        // keys differ, so equality is allowed and only ever over-selects.
376                        require(
377                            previous.last_id() <= block.first_id(),
378                            "unordered series blocks",
379                        )?;
380                    }
381                    blocks.push(block);
382                }
383                let first = blocks[0].first_id();
384                let last = blocks[count - 1].last_id();
385                (Self::Leaf(blocks), first, last)
386            }
387            (1, 2) => {
388                require(
389                    bytes.len() <= PAGE_TARGET
390                        && count <= ROOT_CAPACITY
391                        && count <= c.remaining() / 56,
392                    "series root exceeds capacity",
393                )?;
394                let mut children: Vec<PageReference> = Vec::with_capacity(count);
395                let mut end = payload_end;
396                for _ in 0..count {
397                    let child = PageReference::decode(&mut c)?;
398                    child
399                        .payload
400                        .validate(end, reference.payload.offset, true)?;
401                    end = child.payload.end()?;
402                    if let Some(previous) = children.last() {
403                        require(
404                            previous.last <= child.first,
405                            "unordered series child ranges",
406                        )?;
407                    }
408                    children.push(child);
409                }
410                let first = children[0].first;
411                let last = children[count - 1].last;
412                (Self::Internal(children), first, last)
413            }
414            _ => return Err(unsupported("series metadata kind/depth")),
415        };
416        c.end()?;
417        require(
418            first == reference.first && last == reference.last,
419            "series page bounds disagree with parent",
420        )?;
421        Ok(page)
422    }
423}
424
425pub(crate) fn header() -> Vec<u8> {
426    let mut out = MAGIC.to_vec();
427    put_u32(&mut out, VERSION);
428    put_u32(&mut out, 0);
429    out
430}
431pub(crate) fn validate_header(bytes: &[u8]) -> Result<()> {
432    let mut c = Cursor::new(bytes);
433    require(c.take(8)? == MAGIC, "invalid series header magic")?;
434    if c.u32()? != VERSION {
435        return Err(unsupported("series file version"));
436    }
437    require(c.u32()? == 0, "nonzero series header reserved field")?;
438    c.end()
439}
440
441pub(crate) struct Trailer {
442    pub(crate) root: PageReference,
443    pub(crate) depth: u32,
444    pub(crate) file_length: u64,
445    pub(crate) payload_end: u64,
446}
447impl Trailer {
448    pub(crate) fn encode(&self) -> Vec<u8> {
449        let mut out = Vec::new();
450        self.root.encode(&mut out);
451        put_u32(&mut out, self.depth);
452        put_u32(&mut out, VERSION);
453        put_u64(&mut out, self.file_length);
454        put_u64(&mut out, self.payload_end);
455        out.extend(MAGIC);
456        let checksum = codec::checksum(&out);
457        put_u64(&mut out, checksum);
458        out
459    }
460    pub(crate) fn decode(bytes: &[u8], file_length: u64) -> Result<Self> {
461        require(
462            bytes.len() == TRAILER_SIZE as usize,
463            "truncated series trailer",
464        )?;
465        let mut c = Cursor::new(bytes);
466        let root = PageReference::decode(&mut c)?;
467        let depth = c.u32()?;
468        let version = c.u32()?;
469        if !(1..=2).contains(&depth) || version != VERSION {
470            return Err(unsupported("series trailer version/depth"));
471        }
472        let length = c.u64()?;
473        let payload_end = c.u64()?;
474        require(c.take(8)? == MAGIC, "series trailer magic mismatch")?;
475        require(
476            length == file_length
477                && payload_end >= HEADER_SIZE
478                && file_length >= HEADER_SIZE + TRAILER_SIZE,
479            "invalid series file framing",
480        )?;
481        root.payload
482            .validate(payload_end, file_length - TRAILER_SIZE, true)?;
483        require(
484            root.payload.end()? == file_length - TRAILER_SIZE,
485            "series root does not end at trailer",
486        )?;
487        Ok(Self {
488            root,
489            depth,
490            file_length,
491            payload_end,
492        })
493    }
494}