Skip to main content

partition/
manager.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
15use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use api::v1::Rows;
19use common_meta::cache::{TableRoute, TableRouteCacheRef};
20use common_meta::key::table_route::{PhysicalTableRouteValue, TableRouteManager};
21use common_meta::kv_backend::KvBackendRef;
22use common_meta::peer::Peer;
23use common_meta::rpc::router::{self, RegionRoute};
24use snafu::{OptionExt, ResultExt};
25use store_api::metric_engine_consts::{
26    DATA_SCHEMA_TABLE_ID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME,
27};
28use store_api::storage::{RegionId, RegionNumber};
29use table::metadata::{TableId, TableInfo};
30
31use crate::cache::{CachedPartitionInfo, PartitionInfoCacheRef, PhysicalPartitionInfo};
32use crate::error::{FindLeaderSnafu, Result};
33use crate::expr::PartitionExpr;
34use crate::multi_dim::MultiDimPartitionRule;
35use crate::partition::PartitionEvalContext;
36use crate::splitter::RowSplitter;
37use crate::{PartitionRuleRef, error};
38
39pub type PartitionRuleManagerRef = Arc<PartitionRuleManager>;
40
41/// PartitionRuleManager manages the table routes and partition rules.
42/// It provides methods to find regions by:
43/// - values (in case of insertion)
44/// - filters (in case of select, deletion and update)
45pub struct PartitionRuleManager {
46    table_route_manager: TableRouteManager,
47    table_route_cache: TableRouteCacheRef,
48    partition_info_cache: PartitionInfoCacheRef,
49}
50
51#[derive(Debug, Clone)]
52pub struct PartitionInfo {
53    pub id: RegionId,
54    pub partition_expr: Option<PartitionExpr>,
55}
56
57#[derive(Debug, Clone)]
58pub struct PartitionInfoWithVersion {
59    pub id: RegionId,
60    pub partition_expr: Option<PartitionExpr>,
61    pub partition_expr_version: Option<u64>,
62}
63
64impl PartitionRuleManager {
65    pub fn new(
66        kv_backend: KvBackendRef,
67        table_route_cache: TableRouteCacheRef,
68        partition_info_cache: PartitionInfoCacheRef,
69    ) -> Self {
70        Self {
71            table_route_manager: TableRouteManager::new(kv_backend),
72            table_route_cache,
73            partition_info_cache,
74        }
75    }
76
77    pub async fn find_physical_table_route(
78        &self,
79        table_id: TableId,
80    ) -> Result<Arc<PhysicalTableRouteValue>> {
81        Ok(self.find_physical_table_route_with_id(table_id).await?.1)
82    }
83
84    /// Returns the resolved physical table id and its route.
85    pub async fn find_physical_table_route_with_id(
86        &self,
87        table_id: TableId,
88    ) -> Result<(TableId, Arc<PhysicalTableRouteValue>)> {
89        match self
90            .table_route_cache
91            .get(table_id)
92            .await
93            .context(error::TableRouteManagerSnafu)?
94            .context(error::TableRouteNotFoundSnafu { table_id })?
95            .as_ref()
96        {
97            TableRoute::Physical(physical_table_route) => {
98                Ok((table_id, physical_table_route.clone()))
99            }
100            TableRoute::Logical(logical_table_route) => {
101                let physical_table_id = logical_table_route.physical_table_id();
102                let physical_table_route = self
103                    .table_route_cache
104                    .get(physical_table_id)
105                    .await
106                    .context(error::TableRouteManagerSnafu)?
107                    .context(error::TableRouteNotFoundSnafu {
108                        table_id: physical_table_id,
109                    })?;
110
111                let physical_table_route = physical_table_route
112                    .as_physical_table_route_ref()
113                    .context(error::UnexpectedSnafu{
114                        err_msg: format!(
115                            "Expected the physical table route, but got logical table route, table: {physical_table_id}"
116                        ),
117                    })?;
118
119                Ok((physical_table_id, physical_table_route.clone()))
120            }
121        }
122    }
123
124    pub async fn batch_find_region_routes(
125        &self,
126        table_ids: &[TableId],
127    ) -> Result<HashMap<TableId, Vec<RegionRoute>>> {
128        let table_routes = self
129            .table_route_manager
130            .batch_get_physical_table_routes(table_ids)
131            .await
132            .context(error::TableRouteManagerSnafu)?;
133
134        let mut table_region_routes = HashMap::with_capacity(table_routes.len());
135
136        for (table_id, table_route) in table_routes {
137            let region_routes = table_route.region_routes;
138            table_region_routes.insert(table_id, region_routes);
139        }
140
141        Ok(table_region_routes)
142    }
143
144    /// Loads cached routing metadata for callers that only inspect region IDs or partitions.
145    /// Peer-address consumers use `batch_find_region_routes` to refresh node addresses.
146    pub async fn batch_cached_physical_table_routes(
147        &self,
148        table_ids: &[TableId],
149    ) -> Result<HashMap<TableId, Arc<PhysicalTableRouteValue>>> {
150        TableRouteManager::resolve_physical_table_routes(table_ids, |ids| async move {
151            self.table_route_cache.get_many(&ids).await
152        })
153        .await
154        .context(error::TableRouteManagerSnafu)
155    }
156
157    /// Returns the physical partition info with version.
158    pub async fn find_physical_partition_info(
159        &self,
160        table_id: TableId,
161    ) -> Result<Arc<PhysicalPartitionInfo>> {
162        let cached = self
163            .partition_info_cache
164            .get(table_id)
165            .await
166            .context(error::GetPartitionInfoSnafu)?
167            .context(error::TableRouteNotFoundSnafu { table_id })?;
168        match cached {
169            CachedPartitionInfo::Physical(info) => Ok(info),
170            CachedPartitionInfo::Logical(physical_table_id) => {
171                let cached = self
172                    .partition_info_cache
173                    .get(physical_table_id)
174                    .await
175                    .context(error::GetPartitionInfoSnafu)?
176                    .context(error::TableRouteNotFoundSnafu {
177                        table_id: physical_table_id,
178                    })?;
179                let info = cached.into_physical().context(error::UnexpectedSnafu{
180                        err_msg: format!(
181                            "Expected the physical partition info, but got logical partable route, table: {physical_table_id}"
182                        )
183                    })?;
184
185                Ok(info)
186            }
187        }
188    }
189
190    pub async fn batch_find_table_partitions(
191        &self,
192        table_ids: &[TableId],
193    ) -> Result<HashMap<TableId, Vec<PartitionInfo>>> {
194        let routes = self.batch_cached_physical_table_routes(table_ids).await?;
195
196        let mut results = HashMap::with_capacity(table_ids.len());
197
198        for (table_id, route) in routes {
199            results.insert(
200                table_id,
201                create_partitions_from_region_routes(table_id, &route.region_routes)?,
202            );
203        }
204
205        Ok(results)
206    }
207
208    pub async fn find_table_partition_rule(
209        &self,
210        table_info: &TableInfo,
211    ) -> Result<(PartitionRuleRef, HashMap<RegionNumber, Option<u64>>)> {
212        let partition_info = self
213            .find_physical_partition_info(table_info.table_id())
214            .await?;
215        let partition_versions = partition_info
216            .partitions
217            .iter()
218            .map(|r| (r.id.region_number(), r.partition_expr_version))
219            .collect::<HashMap<RegionNumber, Option<u64>>>();
220        let (mut regions, exprs): (Vec<_>, Vec<_>) = partition_info
221            .partitions
222            .iter()
223            .filter_map(|partition| {
224                partition
225                    .partition_expr
226                    .as_ref()
227                    .map(|expr| (partition.id.region_number(), expr.clone()))
228            })
229            .unzip();
230        // Empty expressions belong to the default region. Keep it after the
231        // explicit regions so expression indices still identify the right region.
232        regions.extend(
233            partition_info
234                .partitions
235                .iter()
236                .filter(|partition| partition.partition_expr.is_none())
237                .map(|partition| partition.id.region_number()),
238        );
239        let (partition_columns, eval_context) =
240            Self::resolve_partition_columns_and_context(table_info, &exprs)?;
241        let partition_rule = Arc::new(
242            MultiDimPartitionRule::try_new(partition_columns, regions, exprs, false)?
243                .with_eval_context(eval_context),
244        ) as _;
245        Ok((partition_rule, partition_versions))
246    }
247
248    /// Find the leader of the region.
249    pub async fn find_region_leader(&self, region_id: RegionId) -> Result<Peer> {
250        let region_routes = &self
251            .find_physical_table_route(region_id.table_id())
252            .await?
253            .region_routes;
254
255        router::find_region_leader(region_routes, region_id.region_number()).context(
256            FindLeaderSnafu {
257                region_id,
258                table_id: region_id.table_id(),
259            },
260        )
261    }
262
263    pub async fn split_rows(
264        &self,
265        table_info: &TableInfo,
266        rows: Rows,
267    ) -> Result<HashMap<RegionNumber, (Rows, Option<u64>)>> {
268        let (partition_rule, partition_versions) =
269            self.find_table_partition_rule(table_info).await?;
270
271        let result = RowSplitter::new(partition_rule)
272            .split(rows)?
273            .into_iter()
274            .map(|(region_number, rows)| {
275                (
276                    region_number,
277                    (
278                        rows,
279                        partition_versions
280                            .get(&region_number)
281                            .copied()
282                            .unwrap_or_default(),
283                    ),
284                )
285            })
286            .collect::<HashMap<_, _>>();
287
288        Ok(result)
289    }
290
291    /// Resolves all expression inputs, including identity supplied outside the payload.
292    fn resolve_partition_columns_and_context(
293        table_info: &TableInfo,
294        exprs: &[PartitionExpr],
295    ) -> Result<(Vec<String>, PartitionEvalContext)> {
296        let mut referenced = HashSet::new();
297        for expr in exprs {
298            expr.collect_column_names(&mut referenced);
299        }
300        let mut referenced: Vec<_> = referenced.into_iter().collect();
301        // Keep rule snapshots deterministic despite collecting names in a HashSet.
302        referenced.sort_unstable();
303
304        if table_info.meta.engine != METRIC_ENGINE_NAME
305            || !table_info
306                .meta
307                .options
308                .extra_options
309                .contains_key(LOGICAL_TABLE_METADATA_KEY)
310        {
311            let mut columns: Vec<_> = table_info.meta.partition_column_names().cloned().collect();
312            for column in referenced {
313                if !(table_info.meta.engine == METRIC_ENGINE_NAME
314                    && column == DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
315                    && table_info
316                        .meta
317                        .schema
318                        .column_schema_by_name(&column)
319                        .is_none()
320                {
321                    return error::UndefinedColumnSnafu { column }.fail();
322                }
323                if !columns.contains(&column) {
324                    columns.push(column);
325                }
326            }
327            return Ok((columns, PartitionEvalContext::FromPayload));
328        }
329
330        // Catalog maps only physical partition columns present in the logical schema.
331        // The routing context can additionally supply __table_id.
332        for column in &referenced {
333            if column != DATA_SCHEMA_TABLE_ID_COLUMN_NAME
334                && table_info
335                    .meta
336                    .schema
337                    .column_schema_by_name(column)
338                    .is_none()
339            {
340                return error::UndefinedColumnSnafu { column }.fail();
341            }
342        }
343        Ok((
344            referenced,
345            PartitionEvalContext::WithTableId {
346                table_id: table_info.table_id(),
347            },
348        ))
349    }
350}
351
352/// Creates partitions from region routes.
353pub fn create_partitions_from_region_routes(
354    table_id: TableId,
355    region_routes: &[RegionRoute],
356) -> Result<Vec<PartitionInfo>> {
357    let mut partitions = Vec::with_capacity(region_routes.len());
358    for r in region_routes {
359        let partition_expr = PartitionExpr::from_json_str(&r.region.partition_expr())?;
360
361        // The region routes belong to the physical table but are shared among all logical tables.
362        // That it to say, the region id points to the physical table, so we need to use the actual
363        // table id (which may be a logical table) to renew the region id.
364        let id = RegionId::new(table_id, r.region.id.region_number());
365        partitions.push(PartitionInfo { id, partition_expr });
366    }
367
368    Ok(partitions)
369}