Skip to main content

store_api/
region_engine.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//! Region Engine's definition
16
17use std::any::Any;
18use std::collections::HashMap;
19use std::fmt::{Debug, Display};
20use std::sync::{Arc, Mutex};
21
22use api::greptime_proto::v1::meta::{GrantedRegion as PbGrantedRegion, RegionRole as PbRegionRole};
23use api::region::RegionResponse;
24use async_trait::async_trait;
25use common_error::ext::BoxedError;
26use common_recordbatch::{EmptyRecordBatchStream, QueryMemoryTracker, SendableRecordBatchStream};
27use common_time::Timestamp;
28use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
29use datafusion_physical_plan::{DisplayAs, DisplayFormatType, PhysicalExpr};
30use datatypes::schema::SchemaRef;
31use futures::future::join_all;
32use serde::{Deserialize, Serialize};
33use tokio::sync::Semaphore;
34
35use crate::logstore::entry;
36use crate::metadata::RegionMetadataRef;
37use crate::region_request::{
38    BatchRegionDdlRequest, RegionCatchupRequest, RegionOpenRequest, RegionRequest,
39};
40use crate::storage::{FileId, RegionId, ScanRequest, SequenceNumber};
41
42/// The settable region role state.
43#[derive(Debug, PartialEq, Eq, Clone, Copy)]
44pub enum SettableRegionRoleState {
45    Follower,
46    DowngradingLeader,
47    /// Exit staging mode and return to normal leader state. Only allowed from staging state.
48    Leader,
49    /// Enter staging mode. Region remains writable but disables checkpoint and compaction. Only allowed from normal leader state.
50    StagingLeader,
51}
52
53impl Display for SettableRegionRoleState {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        match self {
56            SettableRegionRoleState::Follower => write!(f, "Follower"),
57            SettableRegionRoleState::DowngradingLeader => write!(f, "Leader(Downgrading)"),
58            SettableRegionRoleState::Leader => write!(f, "Leader"),
59            SettableRegionRoleState::StagingLeader => write!(f, "Leader(Staging)"),
60        }
61    }
62}
63
64impl From<SettableRegionRoleState> for RegionRole {
65    fn from(value: SettableRegionRoleState) -> Self {
66        match value {
67            SettableRegionRoleState::Follower => RegionRole::Follower,
68            SettableRegionRoleState::DowngradingLeader => RegionRole::DowngradingLeader,
69            SettableRegionRoleState::Leader => RegionRole::Leader,
70            SettableRegionRoleState::StagingLeader => RegionRole::StagingLeader,
71        }
72    }
73}
74
75/// The request to set region role state.
76#[derive(Debug, PartialEq, Eq)]
77pub struct SetRegionRoleStateRequest {
78    region_id: RegionId,
79    region_role_state: SettableRegionRoleState,
80}
81
82/// The success response of setting region role state.
83#[derive(Debug, PartialEq, Eq)]
84pub enum SetRegionRoleStateSuccess {
85    File,
86    Mito {
87        last_entry_id: entry::Id,
88    },
89    Metric {
90        last_entry_id: entry::Id,
91        metadata_last_entry_id: entry::Id,
92    },
93}
94
95impl SetRegionRoleStateSuccess {
96    /// Returns a [SetRegionRoleStateSuccess::File].
97    pub fn file() -> Self {
98        Self::File
99    }
100
101    /// Returns a [SetRegionRoleStateSuccess::Mito] with the `last_entry_id`.
102    pub fn mito(last_entry_id: entry::Id) -> Self {
103        SetRegionRoleStateSuccess::Mito { last_entry_id }
104    }
105
106    /// Returns a [SetRegionRoleStateSuccess::Metric] with the `last_entry_id` and `metadata_last_entry_id`.
107    pub fn metric(last_entry_id: entry::Id, metadata_last_entry_id: entry::Id) -> Self {
108        SetRegionRoleStateSuccess::Metric {
109            last_entry_id,
110            metadata_last_entry_id,
111        }
112    }
113}
114
115impl SetRegionRoleStateSuccess {
116    /// Returns the last entry id of the region.
117    pub fn last_entry_id(&self) -> Option<entry::Id> {
118        match self {
119            SetRegionRoleStateSuccess::File => None,
120            SetRegionRoleStateSuccess::Mito { last_entry_id } => Some(*last_entry_id),
121            SetRegionRoleStateSuccess::Metric { last_entry_id, .. } => Some(*last_entry_id),
122        }
123    }
124
125    /// Returns the last entry id of the metadata of the region.
126    pub fn metadata_last_entry_id(&self) -> Option<entry::Id> {
127        match self {
128            SetRegionRoleStateSuccess::File => None,
129            SetRegionRoleStateSuccess::Mito { .. } => None,
130            SetRegionRoleStateSuccess::Metric {
131                metadata_last_entry_id,
132                ..
133            } => Some(*metadata_last_entry_id),
134        }
135    }
136}
137
138/// The response of setting region role state.
139#[derive(Debug)]
140pub enum SetRegionRoleStateResponse {
141    Success(SetRegionRoleStateSuccess),
142    NotFound,
143    InvalidTransition(BoxedError),
144}
145
146impl SetRegionRoleStateResponse {
147    /// Returns a [SetRegionRoleStateResponse::Success] with the `File` success.
148    pub fn success(success: SetRegionRoleStateSuccess) -> Self {
149        Self::Success(success)
150    }
151
152    /// Returns a [SetRegionRoleStateResponse::InvalidTransition] with the error.
153    pub fn invalid_transition(error: BoxedError) -> Self {
154        Self::InvalidTransition(error)
155    }
156
157    /// Returns true if the response is a [SetRegionRoleStateResponse::NotFound].
158    pub fn is_not_found(&self) -> bool {
159        matches!(self, SetRegionRoleStateResponse::NotFound)
160    }
161
162    /// Returns true if the response is a [SetRegionRoleStateResponse::InvalidTransition].
163    pub fn is_invalid_transition(&self) -> bool {
164        matches!(self, SetRegionRoleStateResponse::InvalidTransition(_))
165    }
166}
167
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct GrantedRegion {
170    pub region_id: RegionId,
171    pub region_role: RegionRole,
172    pub extensions: HashMap<String, Vec<u8>>,
173}
174
175impl GrantedRegion {
176    pub fn new(region_id: RegionId, region_role: RegionRole) -> Self {
177        Self {
178            region_id,
179            region_role,
180            extensions: HashMap::new(),
181        }
182    }
183}
184
185impl From<GrantedRegion> for PbGrantedRegion {
186    fn from(value: GrantedRegion) -> Self {
187        PbGrantedRegion {
188            region_id: value.region_id.as_u64(),
189            role: PbRegionRole::from(value.region_role).into(),
190            extensions: value.extensions,
191        }
192    }
193}
194
195impl From<PbGrantedRegion> for GrantedRegion {
196    fn from(value: PbGrantedRegion) -> Self {
197        GrantedRegion {
198            region_id: RegionId::from_u64(value.region_id),
199            region_role: value.role().into(),
200            extensions: value.extensions,
201        }
202    }
203}
204
205/// The role of the region.
206/// TODO(weny): rename it to `RegionRoleState`
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
208pub enum RegionRole {
209    // Readonly region(mito2)
210    Follower,
211    // Writable region(mito2), Readonly region(file).
212    Leader,
213    // Leader is in staging mode.
214    //
215    // This is leader-like and writable, but it follows the staging workflow
216    // semantics instead of a normal leader's steady state.
217    StagingLeader,
218    // Leader is downgrading to follower.
219    //
220    // This state is used to prevent new write requests.
221    DowngradingLeader,
222}
223
224impl Display for RegionRole {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        match self {
227            RegionRole::Follower => write!(f, "Follower"),
228            RegionRole::Leader => write!(f, "Leader"),
229            RegionRole::StagingLeader => write!(f, "Leader(Staging)"),
230            RegionRole::DowngradingLeader => write!(f, "Leader(Downgrading)"),
231        }
232    }
233}
234
235impl RegionRole {
236    pub fn writable(&self) -> bool {
237        matches!(self, RegionRole::Leader | RegionRole::StagingLeader)
238    }
239}
240
241impl From<RegionRole> for PbRegionRole {
242    fn from(value: RegionRole) -> Self {
243        match value {
244            RegionRole::Follower => PbRegionRole::Follower,
245            RegionRole::Leader => PbRegionRole::Leader,
246            RegionRole::StagingLeader => PbRegionRole::StagingLeader,
247            RegionRole::DowngradingLeader => PbRegionRole::DowngradingLeader,
248        }
249    }
250}
251
252impl From<PbRegionRole> for RegionRole {
253    fn from(value: PbRegionRole) -> Self {
254        match value {
255            PbRegionRole::Leader => RegionRole::Leader,
256            PbRegionRole::StagingLeader => RegionRole::StagingLeader,
257            PbRegionRole::Follower => RegionRole::Follower,
258            PbRegionRole::DowngradingLeader => RegionRole::DowngradingLeader,
259        }
260    }
261}
262
263/// Output partition properties of the [RegionScanner].
264#[derive(Debug)]
265pub enum ScannerPartitioning {
266    /// Unknown partitioning scheme with a known number of partitions
267    Unknown(usize),
268}
269
270impl ScannerPartitioning {
271    /// Returns the number of partitions.
272    pub fn num_partitions(&self) -> usize {
273        match self {
274            ScannerPartitioning::Unknown(num_partitions) => *num_partitions,
275        }
276    }
277}
278
279/// Represents one data range within a partition
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub struct PartitionRange {
282    /// Start time of time index column. Inclusive.
283    pub start: Timestamp,
284    /// End time of time index column. Exclusive.
285    pub end: Timestamp,
286    /// Number of rows in this range. Is used to balance ranges between partitions.
287    pub num_rows: usize,
288    /// Identifier to this range. Assigned by storage engine.
289    pub identifier: usize,
290}
291
292/// Properties of the [RegionScanner].
293#[derive(Debug, Default)]
294pub struct ScannerProperties {
295    /// A 2-dim partition ranges.
296    ///
297    /// The first dim vector's length represents the output partition number. The second
298    /// dim is ranges within one partition.
299    pub partitions: Vec<Vec<PartitionRange>>,
300
301    /// Whether scanner is in append-only mode.
302    append_mode: bool,
303
304    /// Total rows that **may** return by scanner. This field is only read iff
305    /// [ScannerProperties::append_mode] is true.
306    total_rows: usize,
307
308    /// Whether to yield an empty batch to distinguish partition ranges.
309    pub distinguish_partition_range: bool,
310
311    /// The target partitions of the scanner. 0 indicates using the number of partitions as target partitions.
312    target_partitions: usize,
313
314    /// Whether the scanner is scanning a logical region.
315    logical_region: bool,
316}
317
318impl ScannerProperties {
319    /// Sets append mode for scanner.
320    pub fn with_append_mode(mut self, append_mode: bool) -> Self {
321        self.append_mode = append_mode;
322        self
323    }
324
325    /// Sets total rows for scanner.
326    pub fn with_total_rows(mut self, total_rows: usize) -> Self {
327        self.total_rows = total_rows;
328        self
329    }
330
331    /// Creates a new [`ScannerProperties`] with the given partitioning.
332    pub fn new(partitions: Vec<Vec<PartitionRange>>, append_mode: bool, total_rows: usize) -> Self {
333        Self {
334            partitions,
335            append_mode,
336            total_rows,
337            distinguish_partition_range: false,
338            target_partitions: 0,
339            logical_region: false,
340        }
341    }
342
343    /// Updates the properties with the given [PrepareRequest].
344    pub fn prepare(&mut self, request: PrepareRequest) {
345        if let Some(ranges) = request.ranges {
346            self.partitions = ranges;
347        }
348        if let Some(distinguish_partition_range) = request.distinguish_partition_range {
349            self.distinguish_partition_range = distinguish_partition_range;
350        }
351        if let Some(target_partitions) = request.target_partitions {
352            self.target_partitions = target_partitions;
353        }
354    }
355
356    /// Returns the number of actual partitions.
357    pub fn num_partitions(&self) -> usize {
358        self.partitions.len()
359    }
360
361    pub fn append_mode(&self) -> bool {
362        self.append_mode
363    }
364
365    pub fn total_rows(&self) -> usize {
366        self.total_rows
367    }
368
369    /// Returns whether the scanner is scanning a logical region.
370    pub fn is_logical_region(&self) -> bool {
371        self.logical_region
372    }
373
374    /// Returns the target partitions of the scanner. If it is not set, returns the number of partitions.
375    pub fn target_partitions(&self) -> usize {
376        if self.target_partitions == 0 {
377            self.num_partitions()
378        } else {
379            self.target_partitions
380        }
381    }
382
383    /// Sets whether the scanner is reading a logical region.
384    pub fn set_logical_region(&mut self, logical_region: bool) {
385        self.logical_region = logical_region;
386    }
387}
388
389/// Request to override the scanner properties.
390#[derive(Default)]
391pub struct PrepareRequest {
392    /// Assigned partition ranges.
393    pub ranges: Option<Vec<Vec<PartitionRange>>>,
394    /// Distringuishes partition range by empty batches.
395    pub distinguish_partition_range: Option<bool>,
396    /// The expected number of target partitions.
397    pub target_partitions: Option<usize>,
398}
399
400impl PrepareRequest {
401    /// Sets the ranges.
402    pub fn with_ranges(mut self, ranges: Vec<Vec<PartitionRange>>) -> Self {
403        self.ranges = Some(ranges);
404        self
405    }
406
407    /// Sets the distinguish partition range flag.
408    pub fn with_distinguish_partition_range(mut self, distinguish_partition_range: bool) -> Self {
409        self.distinguish_partition_range = Some(distinguish_partition_range);
410        self
411    }
412
413    /// Sets the target partitions.
414    pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
415        self.target_partitions = Some(target_partitions);
416        self
417    }
418}
419
420/// Necessary context of the query for the scanner.
421#[derive(Clone, Default)]
422pub struct QueryScanContext {
423    /// Whether the query is EXPLAIN ANALYZE VERBOSE.
424    pub explain_verbose: bool,
425}
426
427/// A scanner that provides a way to scan the region concurrently.
428///
429/// The scanner splits the region into partitions so that each partition can be scanned concurrently.
430/// You can use this trait to implement an [`ExecutionPlan`](datafusion_physical_plan::ExecutionPlan).
431pub trait RegionScanner: Debug + DisplayAs + Send {
432    fn name(&self) -> &str;
433
434    /// Returns the properties of the scanner.
435    fn properties(&self) -> &ScannerProperties;
436
437    /// Returns the schema of the record batches.
438    fn schema(&self) -> SchemaRef;
439
440    /// Returns the metadata of the region.
441    fn metadata(&self) -> RegionMetadataRef;
442
443    /// Prepares the scanner with the given partition ranges.
444    ///
445    /// This method is for the planner to adjust the scanner's behavior based on the partition ranges.
446    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError>;
447
448    /// Scans the partition and returns a stream of record batches.
449    ///
450    /// # Panics
451    /// Panics if the `partition` is out of bound.
452    fn scan_partition(
453        &self,
454        ctx: &QueryScanContext,
455        metrics_set: &ExecutionPlanMetricsSet,
456        partition: usize,
457    ) -> Result<SendableRecordBatchStream, BoxedError>;
458
459    /// Check if there is any predicate exclude region partition exprs that may be executed in this scanner.
460    fn has_predicate_without_region(&self) -> bool;
461
462    /// Add the given dynamic filter expressions to the predicate of the scanner.
463    /// Returns a vector of booleans indicating which filter expressions were applied.
464    /// true indicates the filter expression was applied(will be use by scanner to prune by stat for row group),
465    /// false otherwise.
466    fn add_dyn_filter_to_predicate(
467        &mut self,
468        filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
469    ) -> Vec<bool>;
470
471    /// Sets whether the scanner is reading a logical region.
472    fn set_logical_region(&mut self, logical_region: bool);
473
474    fn snapshot_sequence(&self) -> Option<SequenceNumber> {
475        None
476    }
477}
478
479pub type RegionScannerRef = Box<dyn RegionScanner>;
480
481pub type BatchResponses = Vec<(RegionId, Result<RegionResponse, BoxedError>)>;
482
483/// Represents the statistics of a region.
484#[derive(Debug, Deserialize, Serialize, Default)]
485pub struct RegionStatistic {
486    /// The number of rows stored in SST files owned by this region plus rows in memtables.
487    ///
488    /// Rows from SST files referenced from other regions, for example after repartition,
489    /// are not counted to avoid table-level double counting when summing region statistics.
490    #[serde(default)]
491    pub num_rows: u64,
492    /// The size of memtable in bytes.
493    pub memtable_size: u64,
494    /// The size of WAL in bytes.
495    pub wal_size: u64,
496    /// The size of manifest in bytes.
497    pub manifest_size: u64,
498    /// The size of SST data files owned by this region in bytes.
499    ///
500    /// SST files referenced from other regions, for example after repartition, are not counted.
501    pub sst_size: u64,
502    /// The number of SST files owned by this region.
503    ///
504    /// SST files referenced from other regions, for example after repartition, are not counted.
505    pub sst_num: u64,
506    /// The size of SST index files owned by this region in bytes.
507    ///
508    /// SST index files referenced from other regions, for example after repartition, are not counted.
509    #[serde(default)]
510    pub index_size: u64,
511    /// The details of the region.
512    #[serde(default)]
513    pub manifest: RegionManifestInfo,
514    #[serde(default)]
515    /// The total bytes written of the region since region opened.
516    pub written_bytes: u64,
517    /// The latest entry id of the region's remote WAL since last flush.
518    /// For metric engine, there're two latest entry ids, one for data and one for metadata.
519    /// TODO(weny): remove this two fields and use single instead.
520    #[serde(default)]
521    pub data_topic_latest_entry_id: u64,
522    #[serde(default)]
523    pub metadata_topic_latest_entry_id: u64,
524}
525
526/// The manifest info of a region.
527#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
528pub enum RegionManifestInfo {
529    Mito {
530        manifest_version: u64,
531        flushed_entry_id: u64,
532        /// Number of files removed in the manifest's `removed_files` field.
533        file_removed_cnt: u64,
534    },
535    Metric {
536        data_manifest_version: u64,
537        data_flushed_entry_id: u64,
538        metadata_manifest_version: u64,
539        metadata_flushed_entry_id: u64,
540    },
541}
542
543impl RegionManifestInfo {
544    /// Creates a new [RegionManifestInfo] for mito2 engine.
545    pub fn mito(manifest_version: u64, flushed_entry_id: u64, file_removal_rate: u64) -> Self {
546        Self::Mito {
547            manifest_version,
548            flushed_entry_id,
549            file_removed_cnt: file_removal_rate,
550        }
551    }
552
553    /// Creates a new [RegionManifestInfo] for metric engine.
554    pub fn metric(
555        data_manifest_version: u64,
556        data_flushed_entry_id: u64,
557        metadata_manifest_version: u64,
558        metadata_flushed_entry_id: u64,
559    ) -> Self {
560        Self::Metric {
561            data_manifest_version,
562            data_flushed_entry_id,
563            metadata_manifest_version,
564            metadata_flushed_entry_id,
565        }
566    }
567
568    /// Returns true if the region is a mito2 region.
569    pub fn is_mito(&self) -> bool {
570        matches!(self, RegionManifestInfo::Mito { .. })
571    }
572
573    /// Returns true if the region is a metric region.
574    pub fn is_metric(&self) -> bool {
575        matches!(self, RegionManifestInfo::Metric { .. })
576    }
577
578    /// Returns the flushed entry id of the data region.
579    pub fn data_flushed_entry_id(&self) -> u64 {
580        match self {
581            RegionManifestInfo::Mito {
582                flushed_entry_id, ..
583            } => *flushed_entry_id,
584            RegionManifestInfo::Metric {
585                data_flushed_entry_id,
586                ..
587            } => *data_flushed_entry_id,
588        }
589    }
590
591    /// Returns the manifest version of the data region.
592    pub fn data_manifest_version(&self) -> u64 {
593        match self {
594            RegionManifestInfo::Mito {
595                manifest_version, ..
596            } => *manifest_version,
597            RegionManifestInfo::Metric {
598                data_manifest_version,
599                ..
600            } => *data_manifest_version,
601        }
602    }
603
604    /// Returns the manifest version of the metadata region.
605    pub fn metadata_manifest_version(&self) -> Option<u64> {
606        match self {
607            RegionManifestInfo::Mito { .. } => None,
608            RegionManifestInfo::Metric {
609                metadata_manifest_version,
610                ..
611            } => Some(*metadata_manifest_version),
612        }
613    }
614
615    /// Returns the flushed entry id of the metadata region.
616    pub fn metadata_flushed_entry_id(&self) -> Option<u64> {
617        match self {
618            RegionManifestInfo::Mito { .. } => None,
619            RegionManifestInfo::Metric {
620                metadata_flushed_entry_id,
621                ..
622            } => Some(*metadata_flushed_entry_id),
623        }
624    }
625
626    /// Encodes a list of ([RegionId], [RegionManifestInfo]) to a byte array.
627    pub fn encode_list(manifest_infos: &[(RegionId, Self)]) -> serde_json::Result<Vec<u8>> {
628        serde_json::to_vec(manifest_infos)
629    }
630
631    /// Decodes a list of ([RegionId], [RegionManifestInfo]) from a byte array.
632    pub fn decode_list(value: &[u8]) -> serde_json::Result<Vec<(RegionId, Self)>> {
633        serde_json::from_slice(value)
634    }
635}
636
637impl Default for RegionManifestInfo {
638    fn default() -> Self {
639        Self::Mito {
640            manifest_version: 0,
641            flushed_entry_id: 0,
642            file_removed_cnt: 0,
643        }
644    }
645}
646
647impl RegionStatistic {
648    /// Deserializes the region statistic to a byte array.
649    ///
650    /// Returns None if the deserialization fails.
651    pub fn deserialize_from_slice(value: &[u8]) -> Option<RegionStatistic> {
652        serde_json::from_slice(value).ok()
653    }
654
655    /// Serializes the region statistic to a byte array.
656    ///
657    /// Returns None if the serialization fails.
658    pub fn serialize_to_vec(&self) -> Option<Vec<u8>> {
659        serde_json::to_vec(self).ok()
660    }
661}
662
663impl RegionStatistic {
664    /// Returns the estimated disk size of the region.
665    pub fn estimated_disk_size(&self) -> u64 {
666        self.wal_size + self.sst_size + self.manifest_size + self.index_size
667    }
668}
669
670/// Request to sync the region from a manifest or a region.
671#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
672pub enum SyncRegionFromRequest {
673    /// Syncs the region using manifest information.
674    /// Used in leader-follower manifest sync scenarios.
675    FromManifest(RegionManifestInfo),
676    /// Syncs the region from another region.
677    ///
678    /// Used by the metric engine to sync logical regions from a source physical region
679    /// to a target physical region. This copies metadata region SST files and transforms
680    /// logical region entries to use the target's region number.
681    FromRegion {
682        /// The [`RegionId`] of the source region.
683        source_region_id: RegionId,
684        /// The parallelism of the sync operation.
685        parallelism: usize,
686    },
687}
688
689impl From<RegionManifestInfo> for SyncRegionFromRequest {
690    fn from(manifest_info: RegionManifestInfo) -> Self {
691        SyncRegionFromRequest::FromManifest(manifest_info)
692    }
693}
694
695impl SyncRegionFromRequest {
696    /// Creates a new request from a manifest info.
697    pub fn from_manifest(manifest_info: RegionManifestInfo) -> Self {
698        SyncRegionFromRequest::FromManifest(manifest_info)
699    }
700
701    /// Creates a new request from a region.
702    pub fn from_region(source_region_id: RegionId, parallelism: usize) -> Self {
703        SyncRegionFromRequest::FromRegion {
704            source_region_id,
705            parallelism,
706        }
707    }
708
709    /// Returns true if the request is from a manifest.
710    pub fn is_from_manifest(&self) -> bool {
711        matches!(self, SyncRegionFromRequest::FromManifest { .. })
712    }
713
714    /// Converts the request to a region manifest info.
715    ///
716    /// Returns None if the request is not from a manifest.
717    pub fn into_region_manifest_info(self) -> Option<RegionManifestInfo> {
718        match self {
719            SyncRegionFromRequest::FromManifest(manifest_info) => Some(manifest_info),
720            SyncRegionFromRequest::FromRegion { .. } => None,
721        }
722    }
723}
724
725/// The response of syncing the region.
726#[derive(Debug)]
727pub enum SyncRegionFromResponse {
728    NotSupported,
729    Mito {
730        /// Indicates if the data region was synced.
731        synced: bool,
732    },
733    Metric {
734        /// Indicates if the metadata region was synced.
735        metadata_synced: bool,
736        /// Indicates if the data region was synced.
737        data_synced: bool,
738        /// The logical regions that were newly opened during the sync operation.
739        /// This only occurs after the metadata region has been successfully synced.
740        new_opened_logical_region_ids: Vec<RegionId>,
741    },
742}
743
744impl SyncRegionFromResponse {
745    /// Returns true if data region is synced.
746    pub fn is_data_synced(&self) -> bool {
747        match self {
748            SyncRegionFromResponse::NotSupported => false,
749            SyncRegionFromResponse::Mito { synced } => *synced,
750            SyncRegionFromResponse::Metric { data_synced, .. } => *data_synced,
751        }
752    }
753
754    /// Returns true if the engine is a mito2 engine.
755    pub fn is_mito(&self) -> bool {
756        matches!(self, SyncRegionFromResponse::Mito { .. })
757    }
758
759    /// Returns true if the engine is a metric engine.
760    pub fn is_metric(&self) -> bool {
761        matches!(self, SyncRegionFromResponse::Metric { .. })
762    }
763
764    /// Returns the new opened logical region ids.
765    pub fn new_opened_logical_region_ids(self) -> Option<Vec<RegionId>> {
766        match self {
767            SyncRegionFromResponse::Metric {
768                new_opened_logical_region_ids,
769                ..
770            } => Some(new_opened_logical_region_ids),
771            _ => None,
772        }
773    }
774}
775
776/// Request to remap manifests from old regions to new regions.
777#[derive(Debug, Clone)]
778pub struct RemapManifestsRequest {
779    /// The [`RegionId`] of a staging region used to obtain table directory and storage configuration for the remap operation.
780    pub region_id: RegionId,
781    /// Regions to remap manifests from.
782    pub input_regions: Vec<RegionId>,
783    /// For each old region, which new regions should receive its files
784    pub region_mapping: HashMap<RegionId, Vec<RegionId>>,
785    /// New partition expressions for the new regions.
786    pub new_partition_exprs: HashMap<RegionId, String>,
787}
788
789/// Response to remap manifests from old regions to new regions.
790#[derive(Debug, Clone)]
791pub struct RemapManifestsResponse {
792    /// Maps region id to its staging manifest path.
793    ///
794    /// These paths are relative paths within the central region's staging blob storage,
795    /// and should be passed to [`ApplyStagingManifestRequest`](RegionRequest::ApplyStagingManifest) to finalize the repartition.
796    pub manifest_paths: HashMap<RegionId, String>,
797}
798
799/// Request to copy files from a source region to a target region.
800#[derive(Debug, Clone)]
801pub struct MitoCopyRegionFromRequest {
802    /// The [`RegionId`] of the source region.
803    pub source_region_id: RegionId,
804    /// The parallelism of the copy operation.
805    pub parallelism: usize,
806}
807
808#[derive(Debug, Clone)]
809pub struct MitoCopyRegionFromResponse {
810    /// The file ids that were copied from the source region to the target region.
811    pub copied_file_ids: Vec<FileId>,
812}
813
814#[async_trait]
815pub trait RegionEngine: Send + Sync {
816    /// Name of this engine
817    fn name(&self) -> &str;
818
819    /// Handles batch open region requests.
820    async fn handle_batch_open_requests(
821        &self,
822        parallelism: usize,
823        requests: Vec<(RegionId, RegionOpenRequest)>,
824    ) -> Result<BatchResponses, BoxedError> {
825        let semaphore = Arc::new(Semaphore::new(parallelism));
826        let mut tasks = Vec::with_capacity(requests.len());
827
828        for (region_id, request) in requests {
829            let semaphore_moved = semaphore.clone();
830
831            tasks.push(async move {
832                // Safety: semaphore must exist
833                let _permit = semaphore_moved.acquire().await.unwrap();
834                let result = self
835                    .handle_request(region_id, RegionRequest::Open(request))
836                    .await;
837                (region_id, result)
838            });
839        }
840
841        Ok(join_all(tasks).await)
842    }
843
844    async fn handle_batch_catchup_requests(
845        &self,
846        parallelism: usize,
847        requests: Vec<(RegionId, RegionCatchupRequest)>,
848    ) -> Result<BatchResponses, BoxedError> {
849        let semaphore = Arc::new(Semaphore::new(parallelism));
850        let mut tasks = Vec::with_capacity(requests.len());
851
852        for (region_id, request) in requests {
853            let semaphore_moved = semaphore.clone();
854
855            tasks.push(async move {
856                // Safety: semaphore must exist
857                let _permit = semaphore_moved.acquire().await.unwrap();
858                let result = self
859                    .handle_request(region_id, RegionRequest::Catchup(request))
860                    .await;
861                (region_id, result)
862            });
863        }
864
865        Ok(join_all(tasks).await)
866    }
867
868    async fn handle_batch_ddl_requests(
869        &self,
870        request: BatchRegionDdlRequest,
871    ) -> Result<RegionResponse, BoxedError> {
872        let requests = request.into_region_requests();
873
874        let mut affected_rows = 0;
875        let mut extensions = HashMap::new();
876
877        for (region_id, request) in requests {
878            let result = self.handle_request(region_id, request).await?;
879            affected_rows += result.affected_rows;
880            extensions.extend(result.extensions);
881        }
882
883        Ok(RegionResponse {
884            affected_rows,
885            extensions,
886            metadata: Vec::new(),
887        })
888    }
889
890    /// Handles non-query request to the region. Returns the count of affected rows.
891    async fn handle_request(
892        &self,
893        region_id: RegionId,
894        request: RegionRequest,
895    ) -> Result<RegionResponse, BoxedError>;
896
897    /// Returns the committed sequence (sequence of latest written data).
898    async fn get_committed_sequence(
899        &self,
900        region_id: RegionId,
901    ) -> Result<SequenceNumber, BoxedError>;
902
903    /// Handles query and return a scanner that can be used to scan the region concurrently.
904    async fn handle_query(
905        &self,
906        region_id: RegionId,
907        request: ScanRequest,
908    ) -> Result<RegionScannerRef, BoxedError>;
909
910    /// Returns the query memory tracker for scan execution.
911    fn query_memory_tracker(&self) -> Option<QueryMemoryTracker> {
912        None
913    }
914
915    /// Retrieves region's metadata.
916    async fn get_metadata(&self, region_id: RegionId) -> Result<RegionMetadataRef, BoxedError>;
917
918    /// Retrieves region's statistic.
919    fn region_statistic(&self, region_id: RegionId) -> Option<RegionStatistic>;
920
921    /// Stops the engine
922    async fn stop(&self) -> Result<(), BoxedError>;
923
924    /// Sets [RegionRole] for a region.
925    ///
926    /// The engine checks whether the region is writable before writing to the region. Setting
927    /// the region as readonly doesn't guarantee that write operations in progress will not
928    /// take effect.
929    fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>;
930
931    /// Syncs the region manifest to the given manifest version.
932    async fn sync_region(
933        &self,
934        region_id: RegionId,
935        request: SyncRegionFromRequest,
936    ) -> Result<SyncRegionFromResponse, BoxedError>;
937
938    /// Remaps manifests from old regions to new regions.
939    async fn remap_manifests(
940        &self,
941        request: RemapManifestsRequest,
942    ) -> Result<RemapManifestsResponse, BoxedError>;
943
944    /// Sets region role state gracefully.
945    ///
946    /// After the call returns, the engine ensures no more write operations will succeed in the region.
947    async fn set_region_role_state_gracefully(
948        &self,
949        region_id: RegionId,
950        region_role_state: SettableRegionRoleState,
951    ) -> Result<SetRegionRoleStateResponse, BoxedError>;
952
953    /// Indicates region role.
954    ///
955    /// Returns the `None` if the region is not found.
956    fn role(&self, region_id: RegionId) -> Option<RegionRole>;
957
958    fn as_any(&self) -> &dyn Any;
959}
960
961pub type RegionEngineRef = Arc<dyn RegionEngine>;
962
963/// A [RegionScanner] that only scans a single partition.
964pub struct SinglePartitionScanner {
965    stream: Mutex<Option<SendableRecordBatchStream>>,
966    schema: SchemaRef,
967    properties: ScannerProperties,
968    metadata: RegionMetadataRef,
969    snapshot_sequence: Option<SequenceNumber>,
970}
971
972impl SinglePartitionScanner {
973    /// Creates a new [SinglePartitionScanner] with the given stream and metadata.
974    pub fn new(
975        stream: SendableRecordBatchStream,
976        append_mode: bool,
977        metadata: RegionMetadataRef,
978        snapshot_sequence: Option<SequenceNumber>,
979    ) -> Self {
980        let schema = stream.schema();
981        Self {
982            stream: Mutex::new(Some(stream)),
983            schema,
984            properties: ScannerProperties::default().with_append_mode(append_mode),
985            metadata,
986            snapshot_sequence,
987        }
988    }
989}
990
991impl Debug for SinglePartitionScanner {
992    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
993        write!(f, "SinglePartitionScanner: <SendableRecordBatchStream>")
994    }
995}
996
997impl RegionScanner for SinglePartitionScanner {
998    fn name(&self) -> &str {
999        "SinglePartition"
1000    }
1001
1002    fn properties(&self) -> &ScannerProperties {
1003        &self.properties
1004    }
1005
1006    fn schema(&self) -> SchemaRef {
1007        self.schema.clone()
1008    }
1009
1010    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
1011        self.properties.prepare(request);
1012        Ok(())
1013    }
1014
1015    fn scan_partition(
1016        &self,
1017        _ctx: &QueryScanContext,
1018        _metrics_set: &ExecutionPlanMetricsSet,
1019        _partition: usize,
1020    ) -> Result<SendableRecordBatchStream, BoxedError> {
1021        let mut stream = self.stream.lock().unwrap();
1022        let result = stream
1023            .take()
1024            .or_else(|| Some(Box::pin(EmptyRecordBatchStream::new(self.schema.clone()))));
1025        Ok(result.unwrap())
1026    }
1027
1028    fn has_predicate_without_region(&self) -> bool {
1029        false
1030    }
1031
1032    fn add_dyn_filter_to_predicate(
1033        &mut self,
1034        filter_exprs: Vec<Arc<dyn datafusion_physical_plan::PhysicalExpr>>,
1035    ) -> Vec<bool> {
1036        vec![false; filter_exprs.len()]
1037    }
1038
1039    fn metadata(&self) -> RegionMetadataRef {
1040        self.metadata.clone()
1041    }
1042
1043    fn set_logical_region(&mut self, logical_region: bool) {
1044        self.properties.set_logical_region(logical_region);
1045    }
1046
1047    fn snapshot_sequence(&self) -> Option<SequenceNumber> {
1048        self.snapshot_sequence
1049    }
1050}
1051
1052impl DisplayAs for SinglePartitionScanner {
1053    fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1054        write!(f, "{:?}", self)
1055    }
1056}