file_engine/
manifest.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;
use std::sync::Arc;

use common_datasource::file_format::Format;
use object_store::ObjectStore;
use serde::{Deserialize, Serialize};
use snafu::{ensure, OptionExt, ResultExt};
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
use store_api::storage::{ColumnId, RegionId};

use crate::error::{
    CheckObjectSnafu, DecodeJsonSnafu, DeleteRegionManifestSnafu, EncodeJsonSnafu,
    InvalidMetadataSnafu, LoadRegionManifestSnafu, ManifestExistsSnafu, MissingRequiredFieldSnafu,
    ParseFileFormatSnafu, Result, StoreRegionManifestSnafu,
};
use crate::FileOptions;

#[inline]
fn region_manifest_path(region_dir: &str) -> String {
    format!("{region_dir}manifest/_file_manifest")
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FileRegionManifest {
    pub region_id: RegionId,
    pub column_metadatas: Vec<ColumnMetadata>,
    pub primary_key: Vec<ColumnId>,
    pub options: HashMap<String, String>,
}

impl FileRegionManifest {
    pub async fn store(&self, region_dir: &str, object_store: &ObjectStore) -> Result<()> {
        let path = &region_manifest_path(region_dir);
        let exist = object_store
            .exists(path)
            .await
            .context(CheckObjectSnafu { path })?;
        ensure!(!exist, ManifestExistsSnafu { path });

        let bs = self.encode()?;
        object_store
            .write(path, bs)
            .await
            .context(StoreRegionManifestSnafu {
                region_id: self.region_id,
            })?;

        Ok(())
    }

    pub async fn load(
        region_id: RegionId,
        region_dir: &str,
        object_store: &ObjectStore,
    ) -> Result<Self> {
        let path = &region_manifest_path(region_dir);
        let bs = object_store
            .read(path)
            .await
            .context(LoadRegionManifestSnafu { region_id })?
            .to_vec();
        Self::decode(bs.as_slice())
    }

    pub async fn delete(
        region_id: RegionId,
        region_dir: &str,
        object_store: &ObjectStore,
    ) -> Result<()> {
        let path = &region_manifest_path(region_dir);
        object_store
            .delete(path)
            .await
            .context(DeleteRegionManifestSnafu { region_id })
    }

    pub fn metadata(&self) -> Result<RegionMetadataRef> {
        let mut builder = RegionMetadataBuilder::new(self.region_id);
        for column in &self.column_metadatas {
            builder.push_column_metadata(column.clone());
        }
        builder.primary_key(self.primary_key.clone());
        let metadata = builder.build().context(InvalidMetadataSnafu)?;

        Ok(Arc::new(metadata))
    }

    pub fn url(&self) -> Result<String> {
        self.get_option(table::requests::FILE_TABLE_LOCATION_KEY)
    }

    pub fn file_options(&self) -> Result<FileOptions> {
        let encoded_opts = self.get_option(table::requests::FILE_TABLE_META_KEY)?;
        serde_json::from_str(&encoded_opts).context(DecodeJsonSnafu)
    }

    pub fn format(&self) -> Result<Format> {
        Format::try_from(&self.options).context(ParseFileFormatSnafu)
    }

    fn encode(&self) -> Result<Vec<u8>> {
        serde_json::to_vec(self).context(EncodeJsonSnafu)
    }

    fn decode(src: &[u8]) -> Result<Self> {
        serde_json::from_slice(src).context(DecodeJsonSnafu)
    }

    fn get_option(&self, name: &str) -> Result<String> {
        self.options
            .get(name)
            .cloned()
            .context(MissingRequiredFieldSnafu { name })
    }
}