Skip to main content

metric_engine/engine/
state.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//! Internal states of metric engine
16
17use std::collections::{HashMap, HashSet};
18use std::sync::Arc;
19
20use api::v1::SemanticType;
21use common_time::timestamp::TimeUnit;
22use snafu::OptionExt;
23use store_api::codec::PrimaryKeyEncoding;
24use store_api::metadata::ColumnMetadata;
25use store_api::storage::RegionId;
26
27use crate::engine::options::PhysicalRegionOptions;
28use crate::engine::region_metadata::LogicalColumns;
29use crate::error::{PhysicalRegionNotFoundSnafu, Result};
30use crate::metrics::LOGICAL_REGION_COUNT;
31use crate::utils::to_data_region_id;
32
33pub struct PhysicalRegionState {
34    logical_regions: HashSet<RegionId>,
35    /// Columns of the physical region, wrapped in an [`Arc`] so that hot read
36    /// paths (e.g. write request verification) can hold a cheap snapshot
37    /// instead of deep-cloning the whole map on every row batch.
38    physical_columns: Arc<HashMap<String, ColumnMetadata>>,
39    /// Name of the time index column, cached at region load so that the write
40    /// path doesn't have to scan `physical_columns` for the timestamp on every
41    /// row batch. The time index is fixed at region creation and never
42    /// changes, so this stays in sync with `physical_columns`.
43    time_index_column_name: String,
44    primary_key_encoding: PrimaryKeyEncoding,
45    options: PhysicalRegionOptions,
46    time_index_unit: TimeUnit,
47    /// Serializes adding columns to this physical region: the column existence
48    /// check, the column id allocation and the physical ALTER that installs the
49    /// columns. Column ids are derived from the current metadata, so two
50    /// concurrent add-column requests on logical regions sharing this physical
51    /// region could otherwise assign the same id to different columns.
52    ///
53    /// Callers clone the [`Arc`] out of the state and hold it across the
54    /// physical alter; see [`crate::data_region::DataRegion::add_columns`].
55    column_add_lock: Arc<tokio::sync::Mutex<()>>,
56}
57
58impl PhysicalRegionState {
59    pub fn new(
60        physical_columns: HashMap<String, ColumnMetadata>,
61        primary_key_encoding: PrimaryKeyEncoding,
62        options: PhysicalRegionOptions,
63        time_index_unit: TimeUnit,
64    ) -> Self {
65        // Safety: a valid physical region always has exactly one time index
66        // column; callers validate this before reaching here (see
67        // `create_data_region_request` and the open path).
68        let time_index_column_name = physical_columns
69            .iter()
70            .find(|(_, meta)| meta.semantic_type == SemanticType::Timestamp)
71            .map(|(name, _)| name.clone())
72            .unwrap_or_default();
73        Self {
74            logical_regions: HashSet::new(),
75            physical_columns: Arc::new(physical_columns),
76            time_index_column_name,
77            primary_key_encoding,
78            options,
79            time_index_unit,
80            column_add_lock: Arc::new(tokio::sync::Mutex::new(())),
81        }
82    }
83
84    /// Returns the lock that serializes adding columns to this physical region.
85    pub fn column_add_lock(&self) -> &Arc<tokio::sync::Mutex<()>> {
86        &self.column_add_lock
87    }
88
89    /// Returns a reference to the logical region ids.
90    pub fn logical_regions(&self) -> &HashSet<RegionId> {
91        &self.logical_regions
92    }
93
94    /// Returns a reference to the physical columns.
95    pub fn physical_columns(&self) -> &HashMap<String, ColumnMetadata> {
96        &self.physical_columns
97    }
98
99    /// Returns a cheap snapshot of the physical columns that stays valid
100    /// after releasing the state lock.
101    pub fn physical_columns_snapshot(&self) -> Arc<HashMap<String, ColumnMetadata>> {
102        self.physical_columns.clone()
103    }
104
105    /// Returns the cached name of the time index column.
106    pub fn time_index_column_name(&self) -> &str {
107        &self.time_index_column_name
108    }
109
110    /// Returns a reference to the physical region options.
111    pub fn options(&self) -> &PhysicalRegionOptions {
112        &self.options
113    }
114
115    /// Removes a logical region id from the physical region state.
116    /// Returns true if the logical region id was present.
117    pub fn remove_logical_region(&mut self, logical_region_id: RegionId) -> bool {
118        self.logical_regions.remove(&logical_region_id)
119    }
120}
121
122/// Internal states of metric engine
123#[derive(Default)]
124pub(crate) struct MetricEngineState {
125    /// Physical regions states.
126    physical_regions: HashMap<RegionId, PhysicalRegionState>,
127    /// Mapping from logical region id to physical region id.
128    logical_regions: HashMap<RegionId, RegionId>,
129    /// Cache for the column metadata of logical regions.
130    /// The column order is the same with the order in the metadata, which is
131    /// alphabetically ordered on column name.
132    logical_columns: HashMap<RegionId, LogicalColumns>,
133}
134
135impl MetricEngineState {
136    pub fn add_physical_region(
137        &mut self,
138        physical_region_id: RegionId,
139        physical_columns: HashMap<String, ColumnMetadata>,
140        primary_key_encoding: PrimaryKeyEncoding,
141        options: PhysicalRegionOptions,
142        time_index_unit: TimeUnit,
143    ) {
144        let physical_region_id = to_data_region_id(physical_region_id);
145        self.physical_regions.insert(
146            physical_region_id,
147            PhysicalRegionState::new(
148                physical_columns,
149                primary_key_encoding,
150                options,
151                time_index_unit,
152            ),
153        );
154    }
155
156    /// # Panic
157    /// if the physical region does not exist
158    pub fn add_physical_columns(
159        &mut self,
160        physical_region_id: RegionId,
161        physical_columns: impl IntoIterator<Item = (String, ColumnMetadata)>,
162    ) {
163        let physical_region_id = to_data_region_id(physical_region_id);
164        let state = self.physical_regions.get_mut(&physical_region_id).unwrap();
165        for (col, meta) in physical_columns {
166            // The time index is fixed at region creation and alter cannot add
167            // a new one; keep the cached name in sync defensively.
168            debug_assert_ne!(
169                meta.semantic_type,
170                SemanticType::Timestamp,
171                "unexpected time index column {col} added to an existing physical region"
172            );
173            Arc::make_mut(&mut state.physical_columns).insert(col, meta);
174        }
175    }
176
177    /// # Panic
178    /// if the physical region does not exist
179    pub fn add_logical_regions(
180        &mut self,
181        physical_region_id: RegionId,
182        logical_region_ids: impl IntoIterator<Item = RegionId>,
183    ) {
184        let physical_region_id = to_data_region_id(physical_region_id);
185        let state = self.physical_regions.get_mut(&physical_region_id).unwrap();
186        for logical_region_id in logical_region_ids {
187            state.logical_regions.insert(logical_region_id);
188            self.logical_regions
189                .insert(logical_region_id, physical_region_id);
190        }
191    }
192
193    pub fn invalid_logical_regions_cache(
194        &mut self,
195        logical_region_ids: impl IntoIterator<Item = RegionId>,
196    ) {
197        for logical_region_id in logical_region_ids {
198            self.logical_columns.remove(&logical_region_id);
199        }
200    }
201
202    /// # Panic
203    /// if the physical region does not exist
204    pub fn add_logical_region(
205        &mut self,
206        physical_region_id: RegionId,
207        logical_region_id: RegionId,
208    ) {
209        let physical_region_id = to_data_region_id(physical_region_id);
210        self.physical_regions
211            .get_mut(&physical_region_id)
212            .unwrap()
213            .logical_regions
214            .insert(logical_region_id);
215        self.logical_regions
216            .insert(logical_region_id, physical_region_id);
217    }
218
219    /// Replace the logical columns of the logical region with given columns.
220    pub fn set_logical_columns(&mut self, logical_region_id: RegionId, columns: LogicalColumns) {
221        self.logical_columns.insert(logical_region_id, columns);
222    }
223
224    pub fn get_physical_region_id(&self, logical_region_id: RegionId) -> Option<RegionId> {
225        self.logical_regions.get(&logical_region_id).copied()
226    }
227
228    pub fn logical_columns(&self) -> &HashMap<RegionId, LogicalColumns> {
229        &self.logical_columns
230    }
231
232    pub fn physical_region_states(&self) -> &HashMap<RegionId, PhysicalRegionState> {
233        &self.physical_regions
234    }
235
236    pub fn exist_physical_region(&self, physical_region_id: RegionId) -> bool {
237        self.physical_regions.contains_key(&physical_region_id)
238    }
239
240    pub fn physical_region_time_index_unit(
241        &self,
242        physical_region_id: RegionId,
243    ) -> Option<TimeUnit> {
244        self.physical_regions
245            .get(&physical_region_id)
246            .map(|state| state.time_index_unit)
247    }
248
249    pub fn get_primary_key_encoding(
250        &self,
251        physical_region_id: RegionId,
252    ) -> Option<PrimaryKeyEncoding> {
253        self.physical_regions
254            .get(&physical_region_id)
255            .map(|state| state.primary_key_encoding)
256    }
257
258    pub fn logical_regions(&self) -> &HashMap<RegionId, RegionId> {
259        &self.logical_regions
260    }
261
262    /// Remove all data that are related to the physical region id.
263    pub fn remove_physical_region(&mut self, physical_region_id: RegionId) -> Result<()> {
264        let physical_region_id = to_data_region_id(physical_region_id);
265
266        let logical_regions = &self
267            .physical_regions
268            .get(&physical_region_id)
269            .context(PhysicalRegionNotFoundSnafu {
270                region_id: physical_region_id,
271            })?
272            .logical_regions;
273
274        LOGICAL_REGION_COUNT.sub(logical_regions.len() as i64);
275
276        for logical_region in logical_regions {
277            self.logical_regions.remove(logical_region);
278            self.logical_columns.remove(logical_region);
279        }
280        self.physical_regions.remove(&physical_region_id);
281        Ok(())
282    }
283
284    /// Remove all data that are related to the logical region id.
285    pub fn remove_logical_region(&mut self, logical_region_id: RegionId) -> Result<()> {
286        let physical_region_id = self.logical_regions.remove(&logical_region_id).context(
287            PhysicalRegionNotFoundSnafu {
288                region_id: logical_region_id,
289            },
290        )?;
291
292        self.physical_regions
293            .get_mut(&physical_region_id)
294            .unwrap() // Safety: physical_region_id is got from physical_regions
295            .remove_logical_region(logical_region_id);
296
297        self.logical_columns.remove(&logical_region_id);
298
299        Ok(())
300    }
301
302    pub fn is_logical_region_exist(&self, logical_region_id: RegionId) -> bool {
303        self.logical_regions().contains_key(&logical_region_id)
304    }
305}