Skip to main content

risingwave_meta/barrier/context/
mod.rs

1// Copyright 2024 RisingWave Labs
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
15mod context_impl;
16pub(crate) mod recovery;
17
18use std::future::Future;
19use std::sync::Arc;
20
21use arc_swap::ArcSwap;
22use risingwave_common::catalog::{DatabaseId, TableId};
23use risingwave_common::id::{JobId, PartialGraphId};
24use risingwave_meta_model::SinkId;
25use risingwave_pb::common::WorkerNode;
26use risingwave_pb::hummock::HummockVersionStats;
27use risingwave_pb::stream_service::barrier_complete_response::{
28    IcebergPkIndexSinkMetadata as PbIcebergPkIndexSinkMetadata, PbListFinishedSource,
29    PbLoadFinishedSource,
30};
31use risingwave_pb::stream_service::streaming_control_stream_request::PbInitRequest;
32use risingwave_rpc_client::StreamingControlHandle;
33
34use crate::MetaResult;
35use crate::barrier::checkpoint::independent_job::BatchRefreshJobTriggerContext;
36use crate::barrier::command::{PostCollectCommand, SinceTimestampResolvedEpoch};
37use crate::barrier::progress::TrackingJob;
38use crate::barrier::schedule::{MarkReadyOptions, ScheduledBarriers};
39use crate::barrier::{
40    BarrierManagerStatus, BarrierScheduler, BarrierWorkerRuntimeInfoSnapshot, BatchRefreshInfo,
41    CreateStreamingJobCommandInfo, CreateStreamingJobType, DatabaseRuntimeInfoSnapshot,
42    RecoveryReason, Scheduled, SnapshotBackfillInfo,
43};
44use crate::hummock::{CommitEpochInfo, HummockManagerRef};
45use crate::manager::iceberg_compaction::IcebergCompactionManagerRef;
46use crate::manager::iceberg_pk_index_sink::IcebergPkIndexSinkManager;
47use crate::manager::sink_coordination::SinkCoordinatorManager;
48use crate::manager::{MetaSrvEnv, MetadataManager};
49use crate::serving::ServingVnodeMappingRef;
50use crate::stream::source_manager::SplitAssignment;
51use crate::stream::{GlobalRefreshManagerRef, ScaleControllerRef, SourceManagerRef};
52
53#[derive(Debug)]
54pub(super) struct CreateSnapshotBackfillJobCommandInfo {
55    pub info: CreateStreamingJobCommandInfo,
56    pub snapshot_backfill_info: SnapshotBackfillInfo,
57    pub cross_db_snapshot_backfill_info: SnapshotBackfillInfo,
58    pub resolved_split_assignment: SplitAssignment,
59    /// If set, this is a batch refresh job rather than a regular snapshot backfill.
60    pub refresh_interval_sec: Option<u64>,
61}
62
63impl CreateSnapshotBackfillJobCommandInfo {
64    pub(super) fn into_post_collect(self) -> PostCollectCommand {
65        let job_type = if let Some(refresh_interval_sec) = self.refresh_interval_sec {
66            CreateStreamingJobType::BatchRefresh(BatchRefreshInfo {
67                snapshot_backfill_info: self.snapshot_backfill_info,
68                refresh_interval_sec,
69            })
70        } else {
71            CreateStreamingJobType::SnapshotBackfill {
72                snapshot_backfill_info: self.snapshot_backfill_info,
73                // `since_epoch` is only used before job creation barriers are injected, and
74                // post-collect snapshot backfill does not go through that path.
75                since_epoch: None,
76            }
77        };
78        PostCollectCommand::CreateStreamingJob {
79            info: self.info,
80            job_type,
81            cross_db_snapshot_backfill_info: self.cross_db_snapshot_backfill_info,
82            resolved_split_assignment: self.resolved_split_assignment,
83        }
84    }
85}
86
87pub(super) trait GlobalBarrierWorkerContext: Send + Sync + 'static {
88    fn commit_epoch(
89        &self,
90        commit_info: CommitEpochInfo,
91    ) -> impl Future<Output = MetaResult<HummockVersionStats>> + Send + '_;
92
93    async fn next_scheduled(&self) -> Scheduled;
94    fn abort_and_mark_blocked(
95        &self,
96        database_id: Option<DatabaseId>,
97        recovery_reason: RecoveryReason,
98    );
99    fn mark_ready(&self, options: MarkReadyOptions);
100    fn resolve_log_store_epoch<'a>(
101        &'a self,
102        upstream_table_ids: impl Iterator<Item = TableId> + Send + 'a,
103        since_epoch: u64,
104    ) -> impl Future<Output = MetaResult<SinceTimestampResolvedEpoch>> + Send + 'a;
105
106    async fn refresh_table_refill_runtime_state_after_recovery(&self) -> MetaResult<()> {
107        Ok(())
108    }
109
110    fn post_collect_command(
111        &self,
112        command: PostCollectCommand,
113    ) -> impl Future<Output = MetaResult<()>> + Send + '_;
114
115    fn notify_creating_job_failed(
116        &self,
117        database_id: Option<DatabaseId>,
118        err: String,
119    ) -> impl Future<Output = ()> + Send + '_;
120
121    fn finish_creating_job(
122        &self,
123        job: TrackingJob,
124    ) -> impl Future<Output = MetaResult<()>> + Send + '_;
125
126    fn finish_cdc_table_backfill(
127        &self,
128        job_id: JobId,
129    ) -> impl Future<Output = MetaResult<()>> + Send + '_;
130
131    fn new_control_stream<'a>(
132        &'a self,
133        node: &'a WorkerNode,
134        init_request: &'a PbInitRequest,
135    ) -> impl Future<Output = MetaResult<StreamingControlHandle>> + Send + 'a;
136
137    fn reload_runtime_info(
138        &self,
139    ) -> impl Future<Output = MetaResult<BarrierWorkerRuntimeInfoSnapshot>> + Send + '_;
140
141    async fn reload_database_runtime_info(
142        &self,
143        database_id: DatabaseId,
144    ) -> MetaResult<DatabaseRuntimeInfoSnapshot>;
145
146    fn handle_list_finished_source_ids(
147        &self,
148        list_finished_source_ids: Vec<PbListFinishedSource>,
149    ) -> impl Future<Output = MetaResult<()>> + Send + '_;
150
151    fn handle_load_finished_source_ids(
152        &self,
153        load_finished_source_ids: Vec<PbLoadFinishedSource>,
154    ) -> impl Future<Output = MetaResult<()>> + Send + '_;
155
156    fn handle_refresh_finished_table_ids(
157        &self,
158        refresh_finished_table_job_ids: Vec<JobId>,
159    ) -> impl Future<Output = MetaResult<()>> + Send + '_;
160
161    /// Load the trigger context for a batch refresh job: fragment metadata, job model,
162    /// upstream log epochs, and target upstream epoch — all bundled in one struct.
163    fn load_batch_refresh_trigger_context(
164        &self,
165        job_id: JobId,
166        database_id: DatabaseId,
167        last_committed_epoch: u64,
168    ) -> impl Future<Output = MetaResult<BatchRefreshJobTriggerContext>> + Send + '_;
169
170    fn pre_commit_iceberg_pk_index_sink_metadata(
171        &self,
172        reports: Vec<PbIcebergPkIndexSinkMetadata>,
173    ) -> impl Future<Output = MetaResult<Vec<SinkId>>> + Send + '_;
174
175    fn commit_iceberg_pk_index_sink_metadata(
176        &self,
177        sink_ids: Vec<SinkId>,
178    ) -> impl Future<Output = MetaResult<()>> + Send + '_;
179
180    /// Advance per-database pk-index committed epochs after a checkpoint completion.
181    fn advance_iceberg_pk_index_sink_committed_epochs(
182        &self,
183        epochs: impl IntoIterator<Item = (PartialGraphId, u64)>,
184    );
185}
186
187pub(super) struct GlobalBarrierWorkerContextImpl {
188    scheduled_barriers: ScheduledBarriers,
189
190    status: Arc<ArcSwap<BarrierManagerStatus>>,
191
192    pub(super) metadata_manager: MetadataManager,
193
194    hummock_manager: HummockManagerRef,
195
196    serving_vnode_mapping: ServingVnodeMappingRef,
197
198    source_manager: SourceManagerRef,
199
200    _scale_controller: ScaleControllerRef,
201
202    pub(super) env: MetaSrvEnv,
203
204    /// Barrier scheduler for scheduling load finish commands
205    barrier_scheduler: BarrierScheduler,
206
207    pub(super) refresh_manager: GlobalRefreshManagerRef,
208
209    sink_manager: SinkCoordinatorManager,
210
211    pub(super) iceberg_pk_index_sink_manager: IcebergPkIndexSinkManager,
212
213    pub(super) iceberg_compaction_manager: IcebergCompactionManagerRef,
214}
215
216impl GlobalBarrierWorkerContextImpl {
217    #[expect(clippy::too_many_arguments)]
218    pub(super) fn new(
219        scheduled_barriers: ScheduledBarriers,
220        status: Arc<ArcSwap<BarrierManagerStatus>>,
221        metadata_manager: MetadataManager,
222        hummock_manager: HummockManagerRef,
223        serving_vnode_mapping: ServingVnodeMappingRef,
224        source_manager: SourceManagerRef,
225        scale_controller: ScaleControllerRef,
226        env: MetaSrvEnv,
227        barrier_scheduler: BarrierScheduler,
228        refresh_manager: GlobalRefreshManagerRef,
229        sink_manager: SinkCoordinatorManager,
230        iceberg_pk_index_sink_manager: IcebergPkIndexSinkManager,
231        iceberg_compaction_manager: IcebergCompactionManagerRef,
232    ) -> Self {
233        Self {
234            scheduled_barriers,
235            status,
236            metadata_manager,
237            hummock_manager,
238            serving_vnode_mapping,
239            source_manager,
240            _scale_controller: scale_controller,
241            env,
242            barrier_scheduler,
243            refresh_manager,
244            sink_manager,
245            iceberg_pk_index_sink_manager,
246            iceberg_compaction_manager,
247        }
248    }
249
250    pub(super) fn status(&self) -> Arc<ArcSwap<BarrierManagerStatus>> {
251        self.status.clone()
252    }
253}