Skip to main content

mito2/worker/
handle_apply_staging.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 chrono::Utc;
16use common_telemetry::{debug, info};
17use store_api::logstore::LogStore;
18use store_api::region_request::ApplyStagingManifestRequest;
19use store_api::storage::RegionId;
20use tokio::sync::oneshot;
21
22use crate::error::{RegionStateSnafu, Result, StagingPartitionExprMismatchSnafu, UnexpectedSnafu};
23use crate::manifest::action::{RegionEdit, RegionManifest};
24use crate::manifest::storage::manifest_dir;
25use crate::manifest::storage::staging::{StagingBlobStorage, staging_blob_path};
26use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState};
27use crate::request::{OptionOutputTx, RegionEditRequest, WorkerRequest, WorkerRequestWithTime};
28use crate::sst::location::region_dir_from_table_dir;
29use crate::worker::RegionWorkerLoop;
30use crate::worker::drain_ended_staging;
31use crate::worker::handle_reload::notify_if_fenced;
32
33impl<S: LogStore> RegionWorkerLoop<S> {
34    pub(crate) async fn handle_apply_staging_manifest_request(
35        &mut self,
36        region_id: RegionId,
37        request: ApplyStagingManifestRequest,
38        sender: OptionOutputTx,
39    ) {
40        let region = match self.regions.writable_region(region_id) {
41            Ok(region) => region,
42            Err(e) => {
43                sender.send(Err(e));
44                return;
45            }
46        };
47
48        if !region.is_staging() {
49            let manifest_partition_expr = region.metadata().partition_expr.as_ref().cloned();
50            let is_match = manifest_partition_expr.as_ref() == Some(&request.partition_expr);
51            debug!(
52                "region {} manifest partition expr: {:?}, request partition expr: {:?}",
53                region_id, manifest_partition_expr, request.partition_expr
54            );
55            if is_match {
56                // If current partition expr is already the same as the request,
57                // treats the region already applied the staging manifest.
58                info!(
59                    "Region {} already applied the staging manifest, partition expr: {}, ignore the apply staging manifest request",
60                    region_id, request.partition_expr
61                );
62                sender.send(Ok(0));
63                return;
64            }
65
66            sender.send(
67                RegionStateSnafu {
68                    region_id,
69                    state: region.state(),
70                    expect: RegionRoleState::Leader(RegionLeaderState::Staging),
71                }
72                .fail(),
73            );
74            return;
75        }
76
77        let staging_partition_info = region.manifest_ctx.staging_partition_info();
78
79        let staging_partition_expr = staging_partition_info
80            .as_ref()
81            .and_then(|info| info.partition_expr());
82        // If the partition expr mismatch, return error.
83        if staging_partition_expr != Some(request.partition_expr.as_str()) {
84            sender.send(
85                StagingPartitionExprMismatchSnafu {
86                    manifest_expr: staging_partition_info
87                        .as_ref()
88                        .and_then(|info| info.partition_expr().map(ToString::to_string)),
89                    request_expr: request.partition_expr,
90                }
91                .fail(),
92            );
93            return;
94        }
95
96        let worker_sender = self.sender.clone();
97        common_runtime::spawn_global(async move {
98            let staging_manifest = match Self::fetch_staging_manifest(
99                &region,
100                request.central_region_id,
101                &request.manifest_path,
102            )
103            .await
104            {
105                Ok(staging_manifest) => staging_manifest,
106                Err(e) => {
107                    sender.send(Err(e));
108                    return;
109                }
110            };
111            if staging_manifest.metadata.partition_expr.as_ref() != Some(&request.partition_expr) {
112                sender.send(Err(StagingPartitionExprMismatchSnafu {
113                    manifest_expr: staging_manifest.metadata.partition_expr.clone(),
114                    request_expr: request.partition_expr,
115                }
116                .build()));
117                return;
118            }
119
120            let files_to_add = staging_manifest
121                .files
122                .values()
123                .map(|meta| meta.as_ref().clone())
124                .collect::<Vec<_>>();
125            let edit = RegionEdit {
126                files_to_add,
127                files_to_remove: vec![],
128                timestamp_ms: Some(Utc::now().timestamp_millis()),
129                compaction_time_window: None,
130                flushed_entry_id: None,
131                flushed_sequence: None,
132                committed_sequence: None,
133                ..Default::default()
134            };
135
136            let (tx, rx) = oneshot::channel();
137            info!(
138                "Applying staging manifest request to region {}",
139                region.region_id,
140            );
141            let _ = worker_sender
142                .send(WorkerRequestWithTime::new(WorkerRequest::EditRegion(
143                    RegionEditRequest::new(
144                        region_id, edit,
145                        // we don't need to preload sst cache during repartition, as it may cause extra network overhead.
146                        false, tx,
147                    )
148                    .for_staging(request.partition_expr),
149                )))
150                .await;
151
152            // Await the result from the region edit and forward the outcome to the original sender.
153            // If the operation completes successfully, respond with Ok(0); otherwise, respond with an appropriate error.
154            if let Ok(result) = rx.await {
155                let Ok(()) = result else {
156                    sender.send(result.map(|_| 0));
157                    return;
158                };
159                let manager = region.manifest_ctx.manifest_manager.write().await;
160                let drain = drain_ended_staging(&worker_sender, region_id);
161                let hook_payload = match region.end_staging(manager, drain).await {
162                    Ok(payload) => payload,
163                    Err(e) => {
164                        notify_if_fenced(&worker_sender, &region).await;
165                        sender.send(Err(e));
166                        return;
167                    }
168                };
169                if let Some(pending) = hook_payload {
170                    pending.fire().await;
171                }
172                sender.send(Ok(0));
173            } else {
174                sender.send(
175                    UnexpectedSnafu {
176                        reason: "edit region receiver channel closed",
177                    }
178                    .fail(),
179                );
180            }
181        });
182    }
183
184    /// Fetches the staging manifest from the central region's staging blob storage.
185    ///
186    /// The `central_region_id` is used to locate the staging directory because the staging
187    /// manifest was created by the central region during `remap_manifests` operation.
188    async fn fetch_staging_manifest(
189        region: &MitoRegionRef,
190        central_region_id: RegionId,
191        manifest_path: &str,
192    ) -> Result<RegionManifest> {
193        let region_dir =
194            region_dir_from_table_dir(region.table_dir(), central_region_id, region.path_type());
195        let staging_blob_path = staging_blob_path(&manifest_dir(&region_dir));
196        let staging_blob_storage = StagingBlobStorage::new(
197            staging_blob_path,
198            region.access_layer().object_store().clone(),
199        );
200        let staging_manifest = staging_blob_storage.get(manifest_path).await?;
201
202        RegionManifest::decode(&staging_manifest)
203    }
204}