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