Skip to main content

mito2/series_index/
columnar.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//! Columnar series format. See `docs/formats/mito-series.md` for the wire contract.
16
17pub(super) mod codec;
18mod metadata;
19pub(crate) use metadata::{Page, PageReference, Trailer};
20pub(crate) mod reader;
21#[cfg(test)]
22mod tests;
23mod writer;
24
25use std::sync::Arc;
26
27use crate::sst::file::{FileMeta, WindowSequence};
28use crate::sst::location;
29use common_time::Timestamp;
30use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
31use object_store::ObjectStore;
32use serde::{Deserialize, Serialize};
33use std::collections::BTreeMap;
34use store_api::metadata::RegionMetadataRef;
35use store_api::storage::FileId;
36
37use crate::error::{InvalidMetaSnafu, Result};
38use crate::series_index::artifact::ArtifactFormat;
39use crate::series_index::identity::IdentityEncoding;
40use crate::series_index::{MetricSeriesId, ROW_COUNT_COLUMN, TABLE_ID_COLUMN, TSID_COLUMN};
41
42pub(crate) const VERSION: u32 = 1;
43pub(crate) const MANIFEST_LIMIT: usize = 64 * 1024 * 1024;
44
45/// Packing and compression choices are internal and do not change the wire version.
46#[derive(Debug, Clone)]
47pub(crate) struct ColumnarSeriesFormat {
48    pub(crate) block_rows: usize,
49    pub(crate) zstd_level: i32,
50    pub(crate) compression: codec::Compression,
51    pub(crate) part_bytes: u64,
52    pub(crate) metadata_bytes: usize,
53    pub(crate) page_bytes: usize,
54    pub(crate) root_capacity: usize,
55}
56
57impl Default for ColumnarSeriesFormat {
58    fn default() -> Self {
59        Self {
60            block_rows: 8192,
61            zstd_level: 3,
62            compression: codec::Compression::Zstd,
63            part_bytes: 512 * 1024 * 1024,
64            metadata_bytes: 8 * 1024 * 1024,
65            page_bytes: metadata::PAGE_TARGET,
66            root_capacity: metadata::ROOT_CAPACITY,
67        }
68    }
69}
70
71impl ColumnarSeriesFormat {
72    pub(crate) fn narthex_writer(
73        &self,
74        metadata: RegionMetadataRef,
75        store: ObjectStore,
76        file: &FileMeta,
77        prefix: String,
78    ) -> Result<Box<writer::ColumnarWriter>> {
79        Ok(Box::new(writer::ColumnarWriter::new(
80            self.clone(),
81            metadata,
82            store,
83            file,
84            prefix,
85        )?))
86    }
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub(crate) struct Tag {
91    pub(crate) column_id: u32,
92    pub(crate) name: String,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub(crate) struct Part {
97    pub(crate) part_id: u32,
98    pub(crate) file_size: u64,
99    pub(crate) num_series: u64,
100    pub(crate) first: MetricSeriesId,
101    pub(crate) last: MetricSeriesId,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub(crate) struct Manifest {
106    #[serde(skip)]
107    pub(crate) prefix: String,
108    pub(crate) format: ArtifactFormat,
109    pub(crate) version: u32,
110    /// Mandatory discriminator; see [`IdentityEncoding`]. Never defaulted on read.
111    pub(crate) identity_encoding: IdentityEncoding,
112    pub(crate) region_id: u64,
113    pub(crate) generation: FileId,
114    pub(crate) tags: Vec<Tag>,
115    pub(crate) coverage: SeriesCoverage,
116    pub(crate) files: Vec<Part>,
117}
118
119/// V1 series-file coverage header. The region manifest holds the certified window.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub(crate) struct SeriesCoverage {
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    artifact: Option<crate::series_index::artifact::ArtifactMetadata>,
124    file_size: u64,
125    index_uuid: FileId,
126    bucket_start: Timestamp,
127    bucket_end: Timestamp,
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    source_file_ids: Option<Vec<FileId>>,
130    min_file_sequence: u64,
131    max_file_sequence: u64,
132    compaction_window_secs: i64,
133    window_sequences: BTreeMap<i64, WindowSequence>,
134}
135
136impl SeriesCoverage {
137    fn from_file(file: &FileMeta) -> Self {
138        Self {
139            artifact: None,
140            file_size: 0,
141            index_uuid: file.file_id,
142            bucket_start: file.time_range.0,
143            bucket_end: file.time_range.1,
144            source_file_ids: None,
145            min_file_sequence: 0,
146            max_file_sequence: 0,
147            compaction_window_secs: 0,
148            window_sequences: BTreeMap::new(),
149        }
150    }
151}
152
153impl Manifest {
154    fn retained_size(&self) -> usize {
155        std::mem::size_of::<Self>() + self.prefix.capacity() + self.files.capacity() * std::mem::size_of::<Part>()
156            + self.tags.capacity() * std::mem::size_of::<Tag>()
157            + self.tags.iter().map(|tag| tag.name.capacity()).sum::<usize>()
158            + self.coverage.source_file_ids.as_ref().map_or(0, Vec::capacity) * std::mem::size_of::<FileId>()
159            // BTree nodes include allocation and partially occupied key/value slots.
160            + 512
161            + self.coverage.window_sequences.len() * 128
162    }
163
164    pub(crate) fn part_path(&self, id: u32) -> String {
165        crate::sst::location::narthex_part_path(&self.prefix, id as usize, "series")
166    }
167    pub(crate) fn path(&self) -> String {
168        location::narthex_manifest_path(&self.prefix)
169    }
170    pub(crate) fn schema(&self) -> SchemaRef {
171        let mut fields = vec![
172            Field::new(TABLE_ID_COLUMN, DataType::UInt32, false),
173            Field::new(TSID_COLUMN, DataType::UInt64, false),
174            Field::new(ROW_COUNT_COLUMN, DataType::UInt64, false),
175        ];
176        fields.extend(self.tags.iter().map(|tag| {
177            crate::sst::with_field_id(Field::new(&tag.name, DataType::Utf8, true), tag.column_id)
178        }));
179        Arc::new(Schema::new(fields))
180    }
181}
182
183pub(crate) fn invalid(reason: impl Into<String>) -> crate::error::Error {
184    InvalidMetaSnafu {
185        reason: reason.into(),
186    }
187    .build()
188}
189
190pub(crate) fn require(valid: bool, reason: &str) -> Result<()> {
191    if valid { Ok(()) } else { Err(invalid(reason)) }
192}
193
194pub(crate) fn unsupported(reason: impl Into<String>) -> crate::error::Error {
195    crate::error::UnsupportedOperationSnafu {
196        err_msg: reason.into(),
197    }
198    .build()
199}