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