risingwave_meta/manager/
metadata.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
15use std::collections::{BTreeMap, HashMap, HashSet};
16use std::fmt::{Debug, Formatter};
17
18use anyhow::anyhow;
19use itertools::Itertools;
20use risingwave_common::catalog::{DatabaseId, TableId, TableOption};
21use risingwave_common::id::JobId;
22use risingwave_meta_model::refresh_job::{self, RefreshState};
23use risingwave_meta_model::{SinkId, SourceId, WorkerId};
24use risingwave_pb::catalog::{PbSink, PbSource, PbTable};
25use risingwave_pb::common::worker_node::{PbResource, Property as AddNodeProperty, State};
26use risingwave_pb::common::{HostAddress, PbWorkerNode, PbWorkerType, WorkerNode, WorkerType};
27use risingwave_pb::meta::list_rate_limits_response::RateLimitInfo;
28use risingwave_pb::stream_plan::{PbDispatcherType, PbStreamNode, PbStreamScanType};
29use sea_orm::prelude::DateTime;
30use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
31use tokio::sync::oneshot;
32use tracing::warn;
33
34use crate::MetaResult;
35use crate::barrier::SharedFragmentInfo;
36use crate::controller::catalog::CatalogControllerRef;
37use crate::controller::cluster::{ClusterControllerRef, StreamingClusterInfo, WorkerExtraInfo};
38use crate::controller::fragment::FragmentParallelismInfo;
39use crate::manager::{LocalNotification, NotificationVersion};
40use crate::model::{ActorId, ClusterId, FragmentId, StreamJobFragments, SubscriptionId};
41use crate::stream::SplitAssignment;
42use crate::telemetry::MetaTelemetryJobDesc;
43
44#[derive(Clone)]
45pub struct MetadataManager {
46    pub cluster_controller: ClusterControllerRef,
47    pub catalog_controller: CatalogControllerRef,
48}
49
50#[derive(Debug)]
51pub(crate) enum ActiveStreamingWorkerChange {
52    Add(WorkerNode),
53    Remove(WorkerNode),
54    Update(WorkerNode),
55}
56
57pub struct ActiveStreamingWorkerNodes {
58    worker_nodes: HashMap<WorkerId, WorkerNode>,
59    rx: UnboundedReceiver<LocalNotification>,
60    #[cfg_attr(not(debug_assertions), expect(dead_code))]
61    meta_manager: Option<MetadataManager>,
62}
63
64impl Debug for ActiveStreamingWorkerNodes {
65    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("ActiveStreamingWorkerNodes")
67            .field("worker_nodes", &self.worker_nodes)
68            .finish()
69    }
70}
71
72impl ActiveStreamingWorkerNodes {
73    pub(crate) fn uninitialized() -> Self {
74        Self {
75            worker_nodes: Default::default(),
76            rx: unbounded_channel().1,
77            meta_manager: None,
78        }
79    }
80
81    #[cfg(test)]
82    pub(crate) fn for_test(worker_nodes: HashMap<WorkerId, WorkerNode>) -> Self {
83        let (tx, rx) = unbounded_channel();
84        let _join_handle = tokio::spawn(async move {
85            let _tx = tx;
86            std::future::pending::<()>().await
87        });
88        Self {
89            worker_nodes,
90            rx,
91            meta_manager: None,
92        }
93    }
94
95    /// Return an uninitialized one as a placeholder for future initialized
96    pub(crate) async fn new_snapshot(meta_manager: MetadataManager) -> MetaResult<Self> {
97        let (nodes, rx) = meta_manager
98            .subscribe_active_streaming_compute_nodes()
99            .await?;
100        Ok(Self {
101            worker_nodes: nodes.into_iter().map(|node| (node.id, node)).collect(),
102            rx,
103            meta_manager: Some(meta_manager),
104        })
105    }
106
107    pub(crate) fn current(&self) -> &HashMap<WorkerId, WorkerNode> {
108        &self.worker_nodes
109    }
110
111    pub(crate) async fn changed(&mut self) -> ActiveStreamingWorkerChange {
112        loop {
113            let notification = self
114                .rx
115                .recv()
116                .await
117                .expect("notification stopped or uninitialized");
118            match notification {
119                LocalNotification::WorkerNodeDeleted(worker) => {
120                    let is_streaming_compute_node = worker.r#type == WorkerType::ComputeNode as i32
121                        && worker.property.as_ref().unwrap().is_streaming;
122                    let Some(prev_worker) = self.worker_nodes.remove(&worker.id) else {
123                        if is_streaming_compute_node {
124                            warn!(
125                                ?worker,
126                                "notify to delete an non-existing streaming compute worker"
127                            );
128                        }
129                        continue;
130                    };
131                    if !is_streaming_compute_node {
132                        warn!(
133                            ?worker,
134                            ?prev_worker,
135                            "deleted worker has a different recent type"
136                        );
137                    }
138                    if worker.state == State::Starting as i32 {
139                        warn!(
140                            id = %worker.id,
141                            host = ?worker.host,
142                            state = worker.state,
143                            "a starting streaming worker is deleted"
144                        );
145                    }
146                    break ActiveStreamingWorkerChange::Remove(prev_worker);
147                }
148                LocalNotification::WorkerNodeActivated(worker) => {
149                    if worker.r#type != WorkerType::ComputeNode as i32
150                        || !worker.property.as_ref().unwrap().is_streaming
151                    {
152                        if let Some(prev_worker) = self.worker_nodes.remove(&worker.id) {
153                            warn!(
154                                ?worker,
155                                ?prev_worker,
156                                "the type of a streaming worker is changed"
157                            );
158                            break ActiveStreamingWorkerChange::Remove(prev_worker);
159                        } else {
160                            continue;
161                        }
162                    }
163                    assert_eq!(
164                        worker.state,
165                        State::Running as i32,
166                        "not started worker added: {:?}",
167                        worker
168                    );
169                    if let Some(prev_worker) = self.worker_nodes.insert(worker.id, worker.clone()) {
170                        assert_eq!(prev_worker.host, worker.host);
171                        assert_eq!(prev_worker.r#type, worker.r#type);
172                        warn!(
173                            ?prev_worker,
174                            ?worker,
175                            eq = prev_worker == worker,
176                            "notify to update an existing active worker"
177                        );
178                        if prev_worker == worker {
179                            continue;
180                        } else {
181                            break ActiveStreamingWorkerChange::Update(worker);
182                        }
183                    } else {
184                        break ActiveStreamingWorkerChange::Add(worker);
185                    }
186                }
187                _ => {
188                    continue;
189                }
190            }
191        }
192    }
193
194    #[cfg(debug_assertions)]
195    pub(crate) async fn validate_change(&self) {
196        use risingwave_pb::common::WorkerNode;
197        use thiserror_ext::AsReport;
198        let Some(meta_manager) = &self.meta_manager else {
199            return;
200        };
201        match meta_manager.list_active_streaming_compute_nodes().await {
202            Ok(worker_nodes) => {
203                let ignore_irrelevant_info = |node: &WorkerNode| {
204                    (
205                        node.id,
206                        WorkerNode {
207                            id: node.id,
208                            r#type: node.r#type,
209                            host: node.host.clone(),
210                            property: node.property.clone(),
211                            resource: node.resource.clone(),
212                            ..Default::default()
213                        },
214                    )
215                };
216                let worker_nodes: HashMap<_, _> =
217                    worker_nodes.iter().map(ignore_irrelevant_info).collect();
218                let curr_worker_nodes: HashMap<_, _> = self
219                    .current()
220                    .values()
221                    .map(ignore_irrelevant_info)
222                    .collect();
223                if worker_nodes != curr_worker_nodes {
224                    warn!(
225                        ?worker_nodes,
226                        ?curr_worker_nodes,
227                        "different to global snapshot"
228                    );
229                }
230            }
231            Err(e) => {
232                warn!(e = ?e.as_report(), "fail to list_active_streaming_compute_nodes to compare with local snapshot");
233            }
234        }
235    }
236}
237
238impl MetadataManager {
239    pub fn new(
240        cluster_controller: ClusterControllerRef,
241        catalog_controller: CatalogControllerRef,
242    ) -> Self {
243        Self {
244            cluster_controller,
245            catalog_controller,
246        }
247    }
248
249    pub async fn get_worker_by_id(&self, worker_id: WorkerId) -> MetaResult<Option<PbWorkerNode>> {
250        self.cluster_controller.get_worker_by_id(worker_id).await
251    }
252
253    pub async fn count_worker_node(&self) -> MetaResult<HashMap<WorkerType, u64>> {
254        let node_map = self.cluster_controller.count_worker_by_type().await?;
255        Ok(node_map
256            .into_iter()
257            .map(|(ty, cnt)| (ty.into(), cnt as u64))
258            .collect())
259    }
260
261    pub async fn get_worker_info_by_id(&self, worker_id: WorkerId) -> Option<WorkerExtraInfo> {
262        self.cluster_controller
263            .get_worker_info_by_id(worker_id as _)
264            .await
265    }
266
267    pub async fn add_worker_node(
268        &self,
269        r#type: PbWorkerType,
270        host_address: HostAddress,
271        property: AddNodeProperty,
272        resource: PbResource,
273    ) -> MetaResult<WorkerId> {
274        self.cluster_controller
275            .add_worker(r#type, host_address, property, resource)
276            .await
277            .map(|id| id as WorkerId)
278    }
279
280    pub async fn list_worker_node(
281        &self,
282        worker_type: Option<WorkerType>,
283        worker_state: Option<State>,
284    ) -> MetaResult<Vec<PbWorkerNode>> {
285        self.cluster_controller
286            .list_workers(worker_type.map(Into::into), worker_state.map(Into::into))
287            .await
288    }
289
290    pub async fn subscribe_active_streaming_compute_nodes(
291        &self,
292    ) -> MetaResult<(Vec<WorkerNode>, UnboundedReceiver<LocalNotification>)> {
293        self.cluster_controller
294            .subscribe_active_streaming_compute_nodes()
295            .await
296    }
297
298    pub async fn list_active_streaming_compute_nodes(&self) -> MetaResult<Vec<PbWorkerNode>> {
299        self.cluster_controller
300            .list_active_streaming_workers()
301            .await
302    }
303
304    pub async fn list_active_serving_compute_nodes(&self) -> MetaResult<Vec<PbWorkerNode>> {
305        self.cluster_controller.list_active_serving_workers().await
306    }
307
308    pub async fn list_active_database_ids(&self) -> MetaResult<HashSet<DatabaseId>> {
309        Ok(self
310            .catalog_controller
311            .list_fragment_database_ids(None)
312            .await?
313            .into_iter()
314            .map(|(_, database_id)| database_id)
315            .collect())
316    }
317
318    pub async fn split_fragment_map_by_database<T: Debug>(
319        &self,
320        fragment_map: HashMap<FragmentId, T>,
321    ) -> MetaResult<HashMap<DatabaseId, HashMap<FragmentId, T>>> {
322        let fragment_to_database_map: HashMap<_, _> = self
323            .catalog_controller
324            .list_fragment_database_ids(Some(
325                fragment_map
326                    .keys()
327                    .map(|fragment_id| *fragment_id as _)
328                    .collect(),
329            ))
330            .await?
331            .into_iter()
332            .map(|(fragment_id, database_id)| (fragment_id as FragmentId, database_id))
333            .collect();
334        let mut ret: HashMap<_, HashMap<_, _>> = HashMap::new();
335        for (fragment_id, value) in fragment_map {
336            let database_id = *fragment_to_database_map
337                .get(&fragment_id)
338                .ok_or_else(|| anyhow!("cannot get database_id of fragment {fragment_id}"))?;
339            ret.entry(database_id)
340                .or_default()
341                .try_insert(fragment_id, value)
342                .expect("non duplicate");
343        }
344        Ok(ret)
345    }
346
347    pub async fn list_background_creating_jobs(&self) -> MetaResult<HashSet<JobId>> {
348        self.catalog_controller
349            .list_background_creating_jobs(false, None)
350            .await
351    }
352
353    pub async fn list_sources(&self) -> MetaResult<Vec<PbSource>> {
354        self.catalog_controller.list_sources().await
355    }
356
357    pub fn running_fragment_parallelisms(
358        &self,
359        id_filter: Option<HashSet<FragmentId>>,
360    ) -> MetaResult<HashMap<FragmentId, FragmentParallelismInfo>> {
361        let id_filter = id_filter.map(|ids| ids.into_iter().map(|id| id as _).collect());
362        Ok(self
363            .catalog_controller
364            .running_fragment_parallelisms(id_filter)?
365            .into_iter()
366            .map(|(k, v)| (k as FragmentId, v))
367            .collect())
368    }
369
370    /// Get and filter the "**root**" fragments of the specified relations.
371    /// The root fragment is the bottom-most fragment of its fragment graph, and can be a `MView` or a `Source`.
372    ///
373    /// See also [`crate::controller::catalog::CatalogController::get_root_fragments`].
374    pub async fn get_upstream_root_fragments(
375        &self,
376        upstream_table_ids: &HashSet<TableId>,
377    ) -> MetaResult<(
378        HashMap<JobId, (SharedFragmentInfo, PbStreamNode)>,
379        HashMap<ActorId, WorkerId>,
380    )> {
381        let (upstream_root_fragments, actors) = self
382            .catalog_controller
383            .get_root_fragments(upstream_table_ids.iter().map(|id| id.as_job_id()).collect())
384            .await?;
385
386        Ok((upstream_root_fragments, actors))
387    }
388
389    pub async fn get_streaming_cluster_info(&self) -> MetaResult<StreamingClusterInfo> {
390        self.cluster_controller.get_streaming_cluster_info().await
391    }
392
393    pub async fn get_all_table_options(&self) -> MetaResult<HashMap<TableId, TableOption>> {
394        self.catalog_controller.get_all_table_options().await
395    }
396
397    pub async fn get_table_name_type_mapping(
398        &self,
399    ) -> MetaResult<HashMap<TableId, (String, String)>> {
400        self.catalog_controller.get_table_name_type_mapping().await
401    }
402
403    pub async fn get_created_table_ids(&self) -> MetaResult<Vec<TableId>> {
404        self.catalog_controller.get_created_table_ids().await
405    }
406
407    pub async fn get_table_associated_source_id(
408        &self,
409        table_id: TableId,
410    ) -> MetaResult<Option<SourceId>> {
411        self.catalog_controller
412            .get_table_associated_source_id(table_id)
413            .await
414    }
415
416    pub async fn get_table_catalog_by_ids(&self, ids: &[TableId]) -> MetaResult<Vec<PbTable>> {
417        self.catalog_controller
418            .get_table_by_ids(ids.to_vec(), false)
419            .await
420    }
421
422    pub async fn get_table_incoming_sinks(&self, table_id: TableId) -> MetaResult<Vec<PbSink>> {
423        self.catalog_controller
424            .get_table_incoming_sinks(table_id)
425            .await
426    }
427
428    pub async fn list_refresh_jobs(&self) -> MetaResult<Vec<refresh_job::Model>> {
429        self.catalog_controller.list_refresh_jobs().await
430    }
431
432    pub async fn list_refreshable_table_ids(&self) -> MetaResult<Vec<TableId>> {
433        self.catalog_controller.list_refreshable_table_ids().await
434    }
435
436    pub async fn ensure_refresh_job(&self, table_id: TableId) -> MetaResult<()> {
437        self.catalog_controller.ensure_refresh_job(table_id).await
438    }
439
440    pub async fn update_refresh_job_status(
441        &self,
442        table_id: TableId,
443        status: RefreshState,
444        trigger_time: Option<DateTime>,
445        is_success: bool,
446    ) -> MetaResult<()> {
447        self.catalog_controller
448            .update_refresh_job_status(table_id, status, trigger_time, is_success)
449            .await
450    }
451
452    pub async fn reset_all_refresh_jobs_to_idle(&self) -> MetaResult<()> {
453        self.catalog_controller
454            .reset_all_refresh_jobs_to_idle()
455            .await
456    }
457
458    pub async fn update_refresh_job_interval(
459        &self,
460        table_id: TableId,
461        trigger_interval_secs: Option<i64>,
462    ) -> MetaResult<()> {
463        self.catalog_controller
464            .update_refresh_job_interval(table_id, trigger_interval_secs)
465            .await
466    }
467
468    pub async fn get_sink_state_table_ids(&self, sink_id: SinkId) -> MetaResult<Vec<TableId>> {
469        self.catalog_controller
470            .get_sink_state_table_ids(sink_id)
471            .await
472    }
473
474    pub async fn get_table_catalog_by_cdc_table_id(
475        &self,
476        cdc_table_id: &String,
477    ) -> MetaResult<Vec<PbTable>> {
478        self.catalog_controller
479            .get_table_by_cdc_table_id(cdc_table_id)
480            .await
481    }
482
483    pub async fn get_downstream_fragments(
484        &self,
485        job_id: JobId,
486    ) -> MetaResult<(
487        Vec<(PbDispatcherType, SharedFragmentInfo, PbStreamNode)>,
488        HashMap<ActorId, WorkerId>,
489    )> {
490        let (fragments, actors) = self
491            .catalog_controller
492            .get_downstream_fragments(job_id)
493            .await?;
494
495        Ok((fragments, actors))
496    }
497
498    pub async fn get_job_id_to_internal_table_ids_mapping(
499        &self,
500    ) -> Option<Vec<(JobId, Vec<TableId>)>> {
501        self.catalog_controller.get_job_internal_table_ids().await
502    }
503
504    pub async fn get_job_fragments_by_id(&self, job_id: JobId) -> MetaResult<StreamJobFragments> {
505        self.catalog_controller
506            .get_job_fragments_by_id(job_id)
507            .await
508    }
509
510    pub fn get_running_actors_of_fragment(&self, id: FragmentId) -> MetaResult<HashSet<ActorId>> {
511        self.catalog_controller
512            .get_running_actors_of_fragment(id as _)
513    }
514
515    // (backfill_actor_id, upstream_source_actor_id)
516    pub async fn get_running_actors_for_source_backfill(
517        &self,
518        source_backfill_fragment_id: FragmentId,
519        source_fragment_id: FragmentId,
520    ) -> MetaResult<HashSet<(ActorId, ActorId)>> {
521        let actor_ids = self
522            .catalog_controller
523            .get_running_actors_for_source_backfill(
524                source_backfill_fragment_id as _,
525                source_fragment_id as _,
526            )
527            .await?;
528        Ok(actor_ids
529            .into_iter()
530            .map(|(id, upstream)| (id as ActorId, upstream as ActorId))
531            .collect())
532    }
533
534    pub fn worker_actor_count(&self) -> MetaResult<HashMap<WorkerId, usize>> {
535        let actor_cnt = self.catalog_controller.worker_actor_count()?;
536        Ok(actor_cnt
537            .into_iter()
538            .map(|(id, cnt)| (id as WorkerId, cnt))
539            .collect())
540    }
541
542    pub async fn count_streaming_job(&self) -> MetaResult<usize> {
543        self.catalog_controller.count_streaming_jobs().await
544    }
545
546    pub async fn list_stream_job_desc(&self) -> MetaResult<Vec<MetaTelemetryJobDesc>> {
547        self.catalog_controller
548            .list_stream_job_desc_for_telemetry()
549            .await
550    }
551
552    pub async fn update_source_rate_limit_by_source_id(
553        &self,
554        source_id: SourceId,
555        rate_limit: Option<u32>,
556    ) -> MetaResult<(HashSet<JobId>, HashSet<FragmentId>)> {
557        self.catalog_controller
558            .update_source_rate_limit_by_source_id(source_id as _, rate_limit)
559            .await
560    }
561
562    pub async fn update_backfill_rate_limit_by_job_id(
563        &self,
564        job_id: JobId,
565        rate_limit: Option<u32>,
566    ) -> MetaResult<HashSet<FragmentId>> {
567        self.catalog_controller
568            .update_backfill_rate_limit_by_job_id(job_id, rate_limit)
569            .await
570    }
571
572    pub async fn update_sink_rate_limit_by_sink_id(
573        &self,
574        sink_id: SinkId,
575        rate_limit: Option<u32>,
576    ) -> MetaResult<HashSet<FragmentId>> {
577        self.catalog_controller
578            .update_sink_rate_limit_by_job_id(sink_id, rate_limit)
579            .await
580    }
581
582    pub async fn update_dml_rate_limit_by_job_id(
583        &self,
584        job_id: JobId,
585        rate_limit: Option<u32>,
586    ) -> MetaResult<HashSet<FragmentId>> {
587        self.catalog_controller
588            .update_dml_rate_limit_by_job_id(job_id, rate_limit)
589            .await
590    }
591
592    pub async fn update_sink_props_by_sink_id(
593        &self,
594        sink_id: SinkId,
595        props: BTreeMap<String, String>,
596    ) -> MetaResult<HashMap<String, String>> {
597        let new_props = self
598            .catalog_controller
599            .update_sink_props_by_sink_id(sink_id, props)
600            .await?;
601        Ok(new_props)
602    }
603
604    pub async fn update_iceberg_table_props_by_table_id(
605        &self,
606        table_id: TableId,
607        props: BTreeMap<String, String>,
608        alter_iceberg_table_props: Option<
609            risingwave_pb::meta::alter_connector_props_request::PbExtraOptions,
610        >,
611    ) -> MetaResult<(HashMap<String, String>, SinkId)> {
612        let (new_props, sink_id) = self
613            .catalog_controller
614            .update_iceberg_table_props_by_table_id(table_id, props, alter_iceberg_table_props)
615            .await?;
616        Ok((new_props, sink_id))
617    }
618
619    pub async fn update_fragment_rate_limit_by_fragment_id(
620        &self,
621        fragment_id: FragmentId,
622        rate_limit: Option<u32>,
623    ) -> MetaResult<()> {
624        self.catalog_controller
625            .update_fragment_rate_limit_by_fragment_id(fragment_id as _, rate_limit)
626            .await
627    }
628
629    #[await_tree::instrument]
630    pub async fn update_fragment_splits(
631        &self,
632        split_assignment: &SplitAssignment,
633    ) -> MetaResult<()> {
634        let fragment_splits = split_assignment
635            .iter()
636            .map(|(fragment_id, splits)| {
637                (
638                    *fragment_id as _,
639                    splits.values().flatten().cloned().collect_vec(),
640                )
641            })
642            .collect();
643
644        let inner = self.catalog_controller.inner.write().await;
645
646        self.catalog_controller
647            .update_fragment_splits(&inner.db, &fragment_splits)
648            .await
649    }
650
651    pub async fn get_mv_depended_subscriptions(
652        &self,
653        database_id: Option<DatabaseId>,
654    ) -> MetaResult<HashMap<TableId, HashMap<SubscriptionId, u64>>> {
655        Ok(self
656            .catalog_controller
657            .get_mv_depended_subscriptions(database_id)
658            .await?
659            .into_iter()
660            .map(|(table_id, subscriptions)| {
661                (
662                    table_id,
663                    subscriptions
664                        .into_iter()
665                        .map(|(subscription_id, retention_time)| {
666                            (subscription_id as SubscriptionId, retention_time)
667                        })
668                        .collect(),
669                )
670            })
671            .collect())
672    }
673
674    pub async fn get_job_max_parallelism(&self, job_id: JobId) -> MetaResult<usize> {
675        self.catalog_controller
676            .get_max_parallelism_by_id(job_id)
677            .await
678    }
679
680    pub async fn get_existing_job_resource_group(
681        &self,
682        streaming_job_id: JobId,
683    ) -> MetaResult<String> {
684        self.catalog_controller
685            .get_existing_job_resource_group(streaming_job_id)
686            .await
687    }
688
689    pub async fn get_database_resource_group(&self, database_id: DatabaseId) -> MetaResult<String> {
690        self.catalog_controller
691            .get_database_resource_group(database_id)
692            .await
693    }
694
695    pub fn cluster_id(&self) -> &ClusterId {
696        self.cluster_controller.cluster_id()
697    }
698
699    pub async fn list_rate_limits(&self) -> MetaResult<Vec<RateLimitInfo>> {
700        let rate_limits = self.catalog_controller.list_rate_limits().await?;
701        Ok(rate_limits)
702    }
703
704    pub async fn get_job_backfill_scan_types(
705        &self,
706        job_id: JobId,
707    ) -> MetaResult<HashMap<FragmentId, PbStreamScanType>> {
708        let backfill_types = self
709            .catalog_controller
710            .get_job_fragment_backfill_scan_type(job_id)
711            .await?;
712        Ok(backfill_types)
713    }
714
715    pub async fn collect_unreschedulable_backfill_jobs(
716        &self,
717        job_ids: impl IntoIterator<Item = &JobId>,
718    ) -> MetaResult<HashSet<JobId>> {
719        let mut unreschedulable = HashSet::new();
720
721        for job_id in job_ids {
722            let scan_types = self
723                .catalog_controller
724                .get_job_fragment_backfill_scan_type(*job_id)
725                .await?;
726            if scan_types
727                .values()
728                .any(|scan_type| !scan_type.is_reschedulable())
729            {
730                unreschedulable.insert(*job_id);
731            }
732        }
733
734        Ok(unreschedulable)
735    }
736}
737
738impl MetadataManager {
739    /// Wait for job finishing notification in `TrackingJob::finish`.
740    /// The progress is updated per barrier.
741    #[await_tree::instrument]
742    pub async fn wait_streaming_job_finished(
743        &self,
744        database_id: DatabaseId,
745        id: JobId,
746    ) -> MetaResult<NotificationVersion> {
747        tracing::debug!("wait_streaming_job_finished: {id:?}");
748        let mut mgr = self.catalog_controller.get_inner_write_guard().await;
749        if mgr.streaming_job_is_finished(id).await? {
750            return Ok(self.catalog_controller.current_notification_version().await);
751        }
752        let (tx, rx) = oneshot::channel();
753
754        mgr.register_finish_notifier(database_id, id, tx);
755        drop(mgr);
756        rx.await
757            .map_err(|_| "no received reason".to_owned())
758            .and_then(|result| result)
759            .map_err(|reason| anyhow!("failed to wait streaming job finish: {}", reason).into())
760    }
761
762    pub(crate) async fn notify_finish_failed(&self, database_id: Option<DatabaseId>, err: String) {
763        let mut mgr = self.catalog_controller.get_inner_write_guard().await;
764        mgr.notify_finish_failed(database_id, err);
765    }
766}