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
487    #[serde(default)]
488    pub num_rows: u64,
489    /// The size of memtable in bytes.
490    pub memtable_size: u64,
491    /// The size of WAL in bytes.
492    pub wal_size: u64,
493    /// The size of manifest in bytes.
494    pub manifest_size: u64,
495    /// The size of SST data files in bytes.
496    pub sst_size: u64,
497    /// The num of SST files.
498    pub sst_num: u64,
499    /// The size of SST index files in bytes.
500    #[serde(default)]
501    pub index_size: u64,
502    /// The details of the region.
503    #[serde(default)]
504    pub manifest: RegionManifestInfo,
505    #[serde(default)]
506    /// The total bytes written of the region since region opened.
507    pub written_bytes: u64,
508    /// The latest entry id of the region's remote WAL since last flush.
509    /// For metric engine, there're two latest entry ids, one for data and one for metadata.
510    /// TODO(weny): remove this two fields and use single instead.
511    #[serde(default)]
512    pub data_topic_latest_entry_id: u64,
513    #[serde(default)]
514    pub metadata_topic_latest_entry_id: u64,
515}
516
517/// The manifest info of a region.
518#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
519pub enum RegionManifestInfo {
520    Mito {
521        manifest_version: u64,
522        flushed_entry_id: u64,
523        /// Number of files removed in the manifest's `removed_files` field.
524        file_removed_cnt: u64,
525    },
526    Metric {
527        data_manifest_version: u64,
528        data_flushed_entry_id: u64,
529        metadata_manifest_version: u64,
530        metadata_flushed_entry_id: u64,
531    },
532}
533
534impl RegionManifestInfo {
535    /// Creates a new [RegionManifestInfo] for mito2 engine.
536    pub fn mito(manifest_version: u64, flushed_entry_id: u64, file_removal_rate: u64) -> Self {
537        Self::Mito {
538            manifest_version,
539            flushed_entry_id,
540            file_removed_cnt: file_removal_rate,
541        }
542    }
543
544    /// Creates a new [RegionManifestInfo] for metric engine.
545    pub fn metric(
546        data_manifest_version: u64,
547        data_flushed_entry_id: u64,
548        metadata_manifest_version: u64,
549        metadata_flushed_entry_id: u64,
550    ) -> Self {
551        Self::Metric {
552            data_manifest_version,
553            data_flushed_entry_id,
554            metadata_manifest_version,
555            metadata_flushed_entry_id,
556        }
557    }
558
559    /// Returns true if the region is a mito2 region.
560    pub fn is_mito(&self) -> bool {
561        matches!(self, RegionManifestInfo::Mito { .. })
562    }
563
564    /// Returns true if the region is a metric region.
565    pub fn is_metric(&self) -> bool {
566        matches!(self, RegionManifestInfo::Metric { .. })
567    }
568
569    /// Returns the flushed entry id of the data region.
570    pub fn data_flushed_entry_id(&self) -> u64 {
571        match self {
572            RegionManifestInfo::Mito {
573                flushed_entry_id, ..
574            } => *flushed_entry_id,
575            RegionManifestInfo::Metric {
576                data_flushed_entry_id,
577                ..
578            } => *data_flushed_entry_id,
579        }
580    }
581
582    /// Returns the manifest version of the data region.
583    pub fn data_manifest_version(&self) -> u64 {
584        match self {
585            RegionManifestInfo::Mito {
586                manifest_version, ..
587            } => *manifest_version,
588            RegionManifestInfo::Metric {
589                data_manifest_version,
590                ..
591            } => *data_manifest_version,
592        }
593    }
594
595    /// Returns the manifest version of the metadata region.
596    pub fn metadata_manifest_version(&self) -> Option<u64> {
597        match self {
598            RegionManifestInfo::Mito { .. } => None,
599            RegionManifestInfo::Metric {
600                metadata_manifest_version,
601                ..
602            } => Some(*metadata_manifest_version),
603        }
604    }
605
606    /// Returns the flushed entry id of the metadata region.
607    pub fn metadata_flushed_entry_id(&self) -> Option<u64> {
608        match self {
609            RegionManifestInfo::Mito { .. } => None,
610            RegionManifestInfo::Metric {
611                metadata_flushed_entry_id,
612                ..
613            } => Some(*metadata_flushed_entry_id),
614        }
615    }
616
617    /// Encodes a list of ([RegionId], [RegionManifestInfo]) to a byte array.
618    pub fn encode_list(manifest_infos: &[(RegionId, Self)]) -> serde_json::Result<Vec<u8>> {
619        serde_json::to_vec(manifest_infos)
620    }
621
622    /// Decodes a list of ([RegionId], [RegionManifestInfo]) from a byte array.
623    pub fn decode_list(value: &[u8]) -> serde_json::Result<Vec<(RegionId, Self)>> {
624        serde_json::from_slice(value)
625    }
626}
627
628impl Default for RegionManifestInfo {
629    fn default() -> Self {
630        Self::Mito {
631            manifest_version: 0,
632            flushed_entry_id: 0,
633            file_removed_cnt: 0,
634        }
635    }
636}
637
638impl RegionStatistic {
639    /// Deserializes the region statistic to a byte array.
640    ///
641    /// Returns None if the deserialization fails.
642    pub fn deserialize_from_slice(value: &[u8]) -> Option<RegionStatistic> {
643        serde_json::from_slice(value).ok()
644    }
645
646    /// Serializes the region statistic to a byte array.
647    ///
648    /// Returns None if the serialization fails.
649    pub fn serialize_to_vec(&self) -> Option<Vec<u8>> {
650        serde_json::to_vec(self).ok()
651    }
652}
653
654impl RegionStatistic {
655    /// Returns the estimated disk size of the region.
656    pub fn estimated_disk_size(&self) -> u64 {
657        self.wal_size + self.sst_size + self.manifest_size + self.index_size
658    }
659}
660
661/// Request to sync the region from a manifest or a region.
662#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
663pub enum SyncRegionFromRequest {
664    /// Syncs the region using manifest information.
665    /// Used in leader-follower manifest sync scenarios.
666    FromManifest(RegionManifestInfo),
667    /// Syncs the region from another region.
668    ///
669    /// Used by the metric engine to sync logical regions from a source physical region
670    /// to a target physical region. This copies metadata region SST files and transforms
671    /// logical region entries to use the target's region number.
672    FromRegion {
673        /// The [`RegionId`] of the source region.
674        source_region_id: RegionId,
675        /// The parallelism of the sync operation.
676        parallelism: usize,
677    },
678}
679
680impl From<RegionManifestInfo> for SyncRegionFromRequest {
681    fn from(manifest_info: RegionManifestInfo) -> Self {
682        SyncRegionFromRequest::FromManifest(manifest_info)
683    }
684}
685
686impl SyncRegionFromRequest {
687    /// Creates a new request from a manifest info.
688    pub fn from_manifest(manifest_info: RegionManifestInfo) -> Self {
689        SyncRegionFromRequest::FromManifest(manifest_info)
690    }
691
692    /// Creates a new request from a region.
693    pub fn from_region(source_region_id: RegionId, parallelism: usize) -> Self {
694        SyncRegionFromRequest::FromRegion {
695            source_region_id,
696            parallelism,
697        }
698    }
699
700    /// Returns true if the request is from a manifest.
701    pub fn is_from_manifest(&self) -> bool {
702        matches!(self, SyncRegionFromRequest::FromManifest { .. })
703    }
704
705    /// Converts the request to a region manifest info.
706    ///
707    /// Returns None if the request is not from a manifest.
708    pub fn into_region_manifest_info(self) -> Option<RegionManifestInfo> {
709        match self {
710            SyncRegionFromRequest::FromManifest(manifest_info) => Some(manifest_info),
711            SyncRegionFromRequest::FromRegion { .. } => None,
712        }
713    }
714}
715
716/// The response of syncing the region.
717#[derive(Debug)]
718pub enum SyncRegionFromResponse {
719    NotSupported,
720    Mito {
721        /// Indicates if the data region was synced.
722        synced: bool,
723    },
724    Metric {
725        /// Indicates if the metadata region was synced.
726        metadata_synced: bool,
727        /// Indicates if the data region was synced.
728        data_synced: bool,
729        /// The logical regions that were newly opened during the sync operation.
730        /// This only occurs after the metadata region has been successfully synced.
731        new_opened_logical_region_ids: Vec<RegionId>,
732    },
733}
734
735impl SyncRegionFromResponse {
736    /// Returns true if data region is synced.
737    pub fn is_data_synced(&self) -> bool {
738        match self {
739            SyncRegionFromResponse::NotSupported => false,
740            SyncRegionFromResponse::Mito { synced } => *synced,
741            SyncRegionFromResponse::Metric { data_synced, .. } => *data_synced,
742        }
743    }
744
745    /// Returns true if the engine is a mito2 engine.
746    pub fn is_mito(&self) -> bool {
747        matches!(self, SyncRegionFromResponse::Mito { .. })
748    }
749
750    /// Returns true if the engine is a metric engine.
751    pub fn is_metric(&self) -> bool {
752        matches!(self, SyncRegionFromResponse::Metric { .. })
753    }
754
755    /// Returns the new opened logical region ids.
756    pub fn new_opened_logical_region_ids(self) -> Option<Vec<RegionId>> {
757        match self {
758            SyncRegionFromResponse::Metric {
759                new_opened_logical_region_ids,
760                ..
761            } => Some(new_opened_logical_region_ids),
762            _ => None,
763        }
764    }
765}
766
767/// Request to remap manifests from old regions to new regions.
768#[derive(Debug, Clone)]
769pub struct RemapManifestsRequest {
770    /// The [`RegionId`] of a staging region used to obtain table directory and storage configuration for the remap operation.
771    pub region_id: RegionId,
772    /// Regions to remap manifests from.
773    pub input_regions: Vec<RegionId>,
774    /// For each old region, which new regions should receive its files
775    pub region_mapping: HashMap<RegionId, Vec<RegionId>>,
776    /// New partition expressions for the new regions.
777    pub new_partition_exprs: HashMap<RegionId, String>,
778}
779
780/// Response to remap manifests from old regions to new regions.
781#[derive(Debug, Clone)]
782pub struct RemapManifestsResponse {
783    /// Maps region id to its staging manifest path.
784    ///
785    /// These paths are relative paths within the central region's staging blob storage,
786    /// and should be passed to [`ApplyStagingManifestRequest`](RegionRequest::ApplyStagingManifest) to finalize the repartition.
787    pub manifest_paths: HashMap<RegionId, String>,
788}
789
790/// Request to copy files from a source region to a target region.
791#[derive(Debug, Clone)]
792pub struct MitoCopyRegionFromRequest {
793    /// The [`RegionId`] of the source region.
794    pub source_region_id: RegionId,
795    /// The parallelism of the copy operation.
796    pub parallelism: usize,
797}
798
799#[derive(Debug, Clone)]
800pub struct MitoCopyRegionFromResponse {
801    /// The file ids that were copied from the source region to the target region.
802    pub copied_file_ids: Vec<FileId>,
803}
804
805#[async_trait]
806pub trait RegionEngine: Send + Sync {
807    /// Name of this engine
808    fn name(&self) -> &str;
809
810    /// Handles batch open region requests.
811    async fn handle_batch_open_requests(
812        &self,
813        parallelism: usize,
814        requests: Vec<(RegionId, RegionOpenRequest)>,
815    ) -> Result<BatchResponses, BoxedError> {
816        let semaphore = Arc::new(Semaphore::new(parallelism));
817        let mut tasks = Vec::with_capacity(requests.len());
818
819        for (region_id, request) in requests {
820            let semaphore_moved = semaphore.clone();
821
822            tasks.push(async move {
823                // Safety: semaphore must exist
824                let _permit = semaphore_moved.acquire().await.unwrap();
825                let result = self
826                    .handle_request(region_id, RegionRequest::Open(request))
827                    .await;
828                (region_id, result)
829            });
830        }
831
832        Ok(join_all(tasks).await)
833    }
834
835    async fn handle_batch_catchup_requests(
836        &self,
837        parallelism: usize,
838        requests: Vec<(RegionId, RegionCatchupRequest)>,
839    ) -> Result<BatchResponses, BoxedError> {
840        let semaphore = Arc::new(Semaphore::new(parallelism));
841        let mut tasks = Vec::with_capacity(requests.len());
842
843        for (region_id, request) in requests {
844            let semaphore_moved = semaphore.clone();
845
846            tasks.push(async move {
847                // Safety: semaphore must exist
848                let _permit = semaphore_moved.acquire().await.unwrap();
849                let result = self
850                    .handle_request(region_id, RegionRequest::Catchup(request))
851                    .await;
852                (region_id, result)
853            });
854        }
855
856        Ok(join_all(tasks).await)
857    }
858
859    async fn handle_batch_ddl_requests(
860        &self,
861        request: BatchRegionDdlRequest,
862    ) -> Result<RegionResponse, BoxedError> {
863        let requests = request.into_region_requests();
864
865        let mut affected_rows = 0;
866        let mut extensions = HashMap::new();
867
868        for (region_id, request) in requests {
869            let result = self.handle_request(region_id, request).await?;
870            affected_rows += result.affected_rows;
871            extensions.extend(result.extensions);
872        }
873
874        Ok(RegionResponse {
875            affected_rows,
876            extensions,
877            metadata: Vec::new(),
878        })
879    }
880
881    /// Handles non-query request to the region. Returns the count of affected rows.
882    async fn handle_request(
883        &self,
884        region_id: RegionId,
885        request: RegionRequest,
886    ) -> Result<RegionResponse, BoxedError>;
887
888    /// Returns the committed sequence (sequence of latest written data).
889    async fn get_committed_sequence(
890        &self,
891        region_id: RegionId,
892    ) -> Result<SequenceNumber, BoxedError>;
893
894    /// Handles query and return a scanner that can be used to scan the region concurrently.
895    async fn handle_query(
896        &self,
897        region_id: RegionId,
898        request: ScanRequest,
899    ) -> Result<RegionScannerRef, BoxedError>;
900
901    /// Returns the query memory tracker for scan execution.
902    fn query_memory_tracker(&self) -> Option<QueryMemoryTracker> {
903        None
904    }
905
906    /// Retrieves region's metadata.
907    async fn get_metadata(&self, region_id: RegionId) -> Result<RegionMetadataRef, BoxedError>;
908
909    /// Retrieves region's statistic.
910    fn region_statistic(&self, region_id: RegionId) -> Option<RegionStatistic>;
911
912    /// Stops the engine
913    async fn stop(&self) -> Result<(), BoxedError>;
914
915    /// Sets [RegionRole] for a region.
916    ///
917    /// The engine checks whether the region is writable before writing to the region. Setting
918    /// the region as readonly doesn't guarantee that write operations in progress will not
919    /// take effect.
920    fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>;
921
922    /// Syncs the region manifest to the given manifest version.
923    async fn sync_region(
924        &self,
925        region_id: RegionId,
926        request: SyncRegionFromRequest,
927    ) -> Result<SyncRegionFromResponse, BoxedError>;
928
929    /// Remaps manifests from old regions to new regions.
930    async fn remap_manifests(
931        &self,
932        request: RemapManifestsRequest,
933    ) -> Result<RemapManifestsResponse, BoxedError>;
934
935    /// Sets region role state gracefully.
936    ///
937    /// After the call returns, the engine ensures no more write operations will succeed in the region.
938    async fn set_region_role_state_gracefully(
939        &self,
940        region_id: RegionId,
941        region_role_state: SettableRegionRoleState,
942    ) -> Result<SetRegionRoleStateResponse, BoxedError>;
943
944    /// Indicates region role.
945    ///
946    /// Returns the `None` if the region is not found.
947    fn role(&self, region_id: RegionId) -> Option<RegionRole>;
948
949    fn as_any(&self) -> &dyn Any;
950}
951
952pub type RegionEngineRef = Arc<dyn RegionEngine>;
953
954/// A [RegionScanner] that only scans a single partition.
955pub struct SinglePartitionScanner {
956    stream: Mutex<Option<SendableRecordBatchStream>>,
957    schema: SchemaRef,
958    properties: ScannerProperties,
959    metadata: RegionMetadataRef,
960    snapshot_sequence: Option<SequenceNumber>,
961}
962
963impl SinglePartitionScanner {
964    /// Creates a new [SinglePartitionScanner] with the given stream and metadata.
965    pub fn new(
966        stream: SendableRecordBatchStream,
967        append_mode: bool,
968        metadata: RegionMetadataRef,
969        snapshot_sequence: Option<SequenceNumber>,
970    ) -> Self {
971        let schema = stream.schema();
972        Self {
973            stream: Mutex::new(Some(stream)),
974            schema,
975            properties: ScannerProperties::default().with_append_mode(append_mode),
976            metadata,
977            snapshot_sequence,
978        }
979    }
980}
981
982impl Debug for SinglePartitionScanner {
983    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
984        write!(f, "SinglePartitionScanner: <SendableRecordBatchStream>")
985    }
986}
987
988impl RegionScanner for SinglePartitionScanner {
989    fn name(&self) -> &str {
990        "SinglePartition"
991    }
992
993    fn properties(&self) -> &ScannerProperties {
994        &self.properties
995    }
996
997    fn schema(&self) -> SchemaRef {
998        self.schema.clone()
999    }
1000
1001    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
1002        self.properties.prepare(request);
1003        Ok(())
1004    }
1005
1006    fn scan_partition(
1007        &self,
1008        _ctx: &QueryScanContext,
1009        _metrics_set: &ExecutionPlanMetricsSet,
1010        _partition: usize,
1011    ) -> Result<SendableRecordBatchStream, BoxedError> {
1012        let mut stream = self.stream.lock().unwrap();
1013        let result = stream
1014            .take()
1015            .or_else(|| Some(Box::pin(EmptyRecordBatchStream::new(self.schema.clone()))));
1016        Ok(result.unwrap())
1017    }
1018
1019    fn has_predicate_without_region(&self) -> bool {
1020        false
1021    }
1022
1023    fn add_dyn_filter_to_predicate(
1024        &mut self,
1025        filter_exprs: Vec<Arc<dyn datafusion_physical_plan::PhysicalExpr>>,
1026    ) -> Vec<bool> {
1027        vec![false; filter_exprs.len()]
1028    }
1029
1030    fn metadata(&self) -> RegionMetadataRef {
1031        self.metadata.clone()
1032    }
1033
1034    fn set_logical_region(&mut self, logical_region: bool) {
1035        self.properties.set_logical_region(logical_region);
1036    }
1037
1038    fn snapshot_sequence(&self) -> Option<SequenceNumber> {
1039        self.snapshot_sequence
1040    }
1041}
1042
1043impl DisplayAs for SinglePartitionScanner {
1044    fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1045        write!(f, "{:?}", self)
1046    }
1047}