Skip to main content

metric_engine/engine/
catchup.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16
17use common_error::ext::BoxedError;
18use snafu::{OptionExt, ResultExt};
19use store_api::region_engine::{BatchResponses, RegionEngine};
20use store_api::region_request::{RegionCatchupRequest, ReplayCheckpoint};
21use store_api::storage::RegionId;
22
23use crate::engine::MetricEngineInner;
24use crate::error::{BatchCatchupMitoRegionSnafu, PhysicalRegionNotFoundSnafu, Result};
25use crate::utils;
26
27impl MetricEngineInner {
28    pub async fn handle_batch_catchup_requests(
29        &self,
30        parallelism: usize,
31        requests: Vec<(RegionId, RegionCatchupRequest)>,
32    ) -> Result<BatchResponses> {
33        let mut all_requests = Vec::with_capacity(requests.len() * 2);
34        let mut physical_region_options_list = Vec::with_capacity(requests.len());
35
36        for (region_id, req) in requests {
37            let data_region_id = utils::to_data_region_id(region_id);
38
39            let physical_region_options = *self
40                .state
41                .read()
42                .unwrap()
43                .physical_region_states()
44                .get(&data_region_id)
45                .context(PhysicalRegionNotFoundSnafu {
46                    region_id: data_region_id,
47                })?
48                .options();
49            physical_region_options_list.push((data_region_id, physical_region_options));
50            all_requests.extend(mito_catchup_requests(region_id, req));
51        }
52
53        let mut results = self
54            .mito
55            .handle_batch_catchup_requests(parallelism, all_requests)
56            .await
57            .context(BatchCatchupMitoRegionSnafu {})?
58            .into_iter()
59            .collect::<HashMap<_, _>>();
60
61        let mut responses = Vec::with_capacity(physical_region_options_list.len());
62        for (physical_region_id, physical_region_options) in physical_region_options_list {
63            let metadata_region_id = utils::to_metadata_region_id(physical_region_id);
64            let data_region_id = utils::to_data_region_id(physical_region_id);
65            let metadata_region_result = results.remove(&metadata_region_id);
66            let data_region_result = results.remove(&data_region_id);
67
68            // Pass the optional `metadata_region_result` and `data_region_result` to
69            // `recover_physical_region_with_results`. This function handles errors for each
70            // catchup physical region request, allowing the process to continue with the
71            // remaining regions even if some requests fail.
72            let response = self
73                .recover_physical_region_with_results(
74                    metadata_region_result,
75                    data_region_result,
76                    physical_region_id,
77                    physical_region_options,
78                    // Note: We intentionally don’t close the region if recovery fails.
79                    // Closing it here might confuse the region server since it links RegionIds to Engines.
80                    // If recovery didn’t succeed, the region should stay open.
81                    false,
82                )
83                .await
84                .map_err(BoxedError::new);
85            responses.push((physical_region_id, response));
86        }
87
88        Ok(responses)
89    }
90}
91
92/// Returns the catchups of the metadata and data regions of the physical region `region_id`.
93fn mito_catchup_requests(
94    region_id: RegionId,
95    req: RegionCatchupRequest,
96) -> [(RegionId, RegionCatchupRequest); 2] {
97    [
98        (
99            utils::to_metadata_region_id(region_id),
100            RegionCatchupRequest {
101                set_writable: req.set_writable,
102                entry_id: req.metadata_entry_id,
103                metadata_entry_id: None,
104                checkpoint: req.checkpoint.map(|c| ReplayCheckpoint {
105                    entry_id: c.metadata_entry_id.unwrap_or_default(),
106                    metadata_entry_id: None,
107                }),
108                // The engine loads the logical tables from the metadata region once the catchup
109                // ends, so the source's unflushed metadata is not left to a background replay: as
110                // the request names no source, a handover fails if the source has entries the
111                // manifest does not cover. In a takeover, this catchup does not recover the
112                // source's unflushed metadata yet: it replays only this node's WAL and commits
113                // with no candidate-lease check. The candidate lease id tells a repeat of the
114                // migration's catchup from one of another migration.
115                // Since this catchup takes no tail, `flush_region` keeps the metadata region fully
116                // flushed on a downgrade; the two change together.
117                source_node_id: None,
118                candidate_lease_id: req.candidate_lease_id,
119            },
120        ),
121        (
122            utils::to_data_region_id(region_id),
123            RegionCatchupRequest {
124                set_writable: req.set_writable,
125                entry_id: req.entry_id,
126                metadata_entry_id: None,
127                checkpoint: req.checkpoint.map(|c| ReplayCheckpoint {
128                    entry_id: c.entry_id,
129                    metadata_entry_id: None,
130                }),
131                source_node_id: req.source_node_id,
132                candidate_lease_id: req.candidate_lease_id,
133            },
134        ),
135    ]
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn test_only_the_data_region_catches_up_from_the_source() {
144        let region_id = RegionId::new(1024, 1);
145        let [(metadata_region_id, metadata), (data_region_id, data)] = mito_catchup_requests(
146            region_id,
147            RegionCatchupRequest {
148                set_writable: true,
149                entry_id: Some(10),
150                metadata_entry_id: Some(5),
151                source_node_id: Some(42),
152                candidate_lease_id: Some(9),
153                ..Default::default()
154            },
155        );
156        assert_eq!(utils::to_metadata_region_id(region_id), metadata_region_id);
157        assert_eq!(
158            (Some(5), None, Some(9)),
159            (
160                metadata.entry_id,
161                metadata.source_node_id,
162                metadata.candidate_lease_id
163            )
164        );
165        assert_eq!(utils::to_data_region_id(region_id), data_region_id);
166        assert_eq!(
167            (Some(10), Some(42), Some(9)),
168            (data.entry_id, data.source_node_id, data.candidate_lease_id)
169        );
170    }
171}