Skip to main content

risingwave_stream/executor/source/
reader_stream.rs

1// Copyright 2025 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::HashMap;
16
17use futures::StreamExt;
18use itertools::Itertools;
19use risingwave_common::array::StreamChunk;
20use risingwave_common::catalog::ColumnId;
21use risingwave_common::id::SourceId;
22use risingwave_common::metrics::GLOBAL_ERROR_METRICS;
23use risingwave_connector::parser::schema_change::SchemaChangeEnvelope;
24use risingwave_connector::source::reader::desc::SourceDesc;
25use risingwave_connector::source::{
26    BoxSourceReaderEventStream, CdcAutoSchemaChangeFailCallback, ConnectorState,
27    CreateSplitReaderResult, SourceContext, SourceCtrlOpts, SourceReaderEvent, SplitId, SplitImpl,
28    SplitMetaData, StreamChunkWithState,
29};
30use risingwave_pb::ddl_service::auto_schema_change_result::Outcome as SchemaChangeOutcome;
31use thiserror_ext::AsReport;
32use tokio::sync::{mpsc, oneshot};
33
34use super::{
35    apply_rate_limit_to_source_reader_event, get_infinite_backoff_strategy,
36    get_split_offset_col_idx,
37};
38use crate::common::rate_limit::limited_chunk_size;
39use crate::executor::prelude::*;
40
41type AutoSchemaChangeSetup = (
42    Option<mpsc::Sender<(SchemaChangeEnvelope, oneshot::Sender<()>)>>,
43    Option<CdcAutoSchemaChangeFailCallback>,
44);
45
46#[derive(Debug)]
47pub(crate) enum SourceReaderEventWithState {
48    Data(StreamChunkWithState),
49    Progress(HashMap<SplitId, SplitImpl>),
50}
51
52pub(crate) struct StreamReaderBuilder {
53    pub source_desc: SourceDesc,
54    pub rate_limit: Option<u32>,
55    pub source_id: SourceId,
56    pub source_name: String,
57    pub reader_stream: Option<BoxSourceReaderEventStream>,
58
59    // cdc related
60    pub is_auto_schema_change_enable: bool,
61    pub actor_ctx: ActorContextRef,
62}
63
64impl StreamReaderBuilder {
65    fn update_offsets_from_chunk(
66        latest_splits_info: &mut HashMap<SplitId, SplitImpl>,
67        chunk: &StreamChunk,
68        split_idx: usize,
69        offset_idx: usize,
70    ) {
71        // All rows (including those visible or invisible) will be used to update the source offset.
72        for i in 0..chunk.capacity() {
73            let (_, row, _) = chunk.row_at(i);
74            let split = row.datum_at(split_idx).unwrap().into_utf8();
75            let offset = row.datum_at(offset_idx).unwrap().into_utf8();
76            latest_splits_info
77                .get_mut(&Arc::from(split.to_owned()))
78                .map(|split_impl| split_impl.update_in_place(offset.to_owned()));
79        }
80    }
81
82    fn apply_split_progress(
83        latest_splits_info: &mut HashMap<SplitId, SplitImpl>,
84        split_progress: HashMap<SplitId, String>,
85    ) {
86        for (split_id, offset) in split_progress {
87            if let Some(split_impl) = latest_splits_info.get_mut(&split_id) {
88                if let Err(e) = split_impl.update_in_place(offset) {
89                    tracing::warn!(
90                        error = %e.as_report(),
91                        split_id = %split_id,
92                        "failed to apply split progress update",
93                    );
94                }
95            } else {
96                tracing::warn!(
97                    split_id = %split_id,
98                    "ignore progress for unknown split",
99                );
100            }
101        }
102    }
103
104    fn setup_auto_schema_change(&self) -> AutoSchemaChangeSetup {
105        if self.is_auto_schema_change_enable {
106            let (schema_change_tx, mut schema_change_rx) =
107                mpsc::channel::<(SchemaChangeEnvelope, oneshot::Sender<()>)>(16);
108            let meta_client = self.actor_ctx.meta_client.clone();
109            // spawn a task to handle schema change event from source parser
110            let _join_handle = tokio::task::spawn(async move {
111                while let Some((schema_change, finish_tx)) = schema_change_rx.recv().await {
112                    // TODO: retry on rpc error
113                    if let Some(ref meta_client) = meta_client {
114                        match meta_client
115                            .auto_schema_change(schema_change.to_protobuf())
116                            .await
117                        {
118                            Ok(response) => {
119                                for result in response.results {
120                                    match result.outcome() {
121                                        SchemaChangeOutcome::Noop => tracing::debug!(
122                                            target: "auto_schema_change",
123                                            cdc_table_id = result.cdc_table_id,
124                                            table_id = ?result.table_id,
125                                            "schema change skipped: no catalog change"),
126                                        SchemaChangeOutcome::Applied => tracing::info!(
127                                            target: "auto_schema_change",
128                                            cdc_table_id = result.cdc_table_id,
129                                            table_id = ?result.table_id,
130                                            "schema change success"),
131                                        SchemaChangeOutcome::Failed => tracing::error!(
132                                            target: "auto_schema_change",
133                                            cdc_table_id = result.cdc_table_id,
134                                            table_id = ?result.table_id,
135                                            "schema change failed; see Meta logs for details"),
136                                        SchemaChangeOutcome::Unspecified => tracing::warn!(
137                                            target: "auto_schema_change",
138                                            cdc_table_id = result.cdc_table_id,
139                                            table_id = ?result.table_id,
140                                            "schema change outcome is unknown"),
141                                    }
142                                }
143                                let _ = finish_tx.send(());
144                            }
145                            Err(e) => {
146                                tracing::error!(
147                                    target: "auto_schema_change",
148                                    cdc_table_ids = ?schema_change.table_ids(),
149                                    error = %e.as_report(), "schema change error");
150
151                                let _ = finish_tx.send(());
152                            }
153                        }
154                    }
155                }
156            });
157
158            // Create callback function for reporting CDC auto schema change fail events
159            let on_cdc_auto_schema_change_failure = if let Some(ref meta_client) =
160                self.actor_ctx.meta_client
161            {
162                let meta_client = meta_client.clone();
163                Some(CdcAutoSchemaChangeFailCallback::new(
164                    move |source_id: SourceId,
165                          table_name: String,
166                          cdc_table_id: String,
167                          upstream_ddl: String,
168                          fail_info: String| {
169                        let meta_client = meta_client.clone();
170                        tokio::spawn(async move {
171                            if let Err(e) = meta_client
172                                .add_cdc_auto_schema_change_fail_event(
173                                    source_id,
174                                    table_name,
175                                    cdc_table_id,
176                                    upstream_ddl,
177                                    fail_info,
178                                )
179                                .await
180                            {
181                                tracing::warn!(
182                                    error = %e.as_report(),
183                                    %source_id,
184                                    "Failed to add CDC auto schema change fail event to event log."
185                                );
186                            }
187                        });
188                    },
189                ))
190            } else {
191                None
192            };
193
194            (Some(schema_change_tx), on_cdc_auto_schema_change_failure)
195        } else {
196            info!("auto schema change is disabled in config");
197            (None, None)
198        }
199    }
200
201    fn prepare_source_stream_build(&self) -> (Vec<ColumnId>, SourceContext) {
202        let column_ids = self
203            .source_desc
204            .columns
205            .iter()
206            .map(|column_desc| column_desc.column_id)
207            .collect_vec();
208        debug_assert!(column_ids.iter().all_unique(), "column_ids must be unique");
209
210        let (schema_change_tx, on_cdc_auto_schema_change_failure) = self.setup_auto_schema_change();
211
212        let source_ctx = SourceContext::new_with_auto_schema_change_callback(
213            self.actor_ctx.id,
214            self.source_id,
215            self.actor_ctx.fragment_id,
216            self.source_name.clone(),
217            self.source_desc.metrics.clone(),
218            SourceCtrlOpts {
219                chunk_size: limited_chunk_size(self.rate_limit),
220                split_txn: self.rate_limit.is_some(), // when rate limiting, we may split txn
221            },
222            self.source_desc.source.config.clone(),
223            schema_change_tx,
224            on_cdc_auto_schema_change_failure,
225        );
226
227        (column_ids, source_ctx)
228    }
229
230    pub(crate) async fn fetch_latest_splits(
231        &mut self,
232        state: ConnectorState,
233        seek_to_latest: bool,
234    ) -> StreamExecutorResult<CreateSplitReaderResult> {
235        let (column_ids, source_ctx) = self.prepare_source_stream_build();
236        let source_ctx_ref = Arc::new(source_ctx);
237        let (stream, res) = self
238            .source_desc
239            .source
240            .build_stream(
241                state.clone(),
242                column_ids.clone(),
243                source_ctx_ref.clone(),
244                seek_to_latest,
245            )
246            .await
247            .map_err(StreamExecutorError::connector_error)?;
248        self.reader_stream = Some(stream);
249        Ok(res)
250    }
251
252    #[try_stream(ok = SourceReaderEventWithState, error = StreamExecutorError)]
253    pub(crate) async fn into_retry_stream(mut self, state: ConnectorState, is_initial_build: bool) {
254        let (column_ids, source_ctx) = self.prepare_source_stream_build();
255        let source_ctx_ref = Arc::new(source_ctx);
256
257        let mut latest_splits_info = {
258            if let Some(splits) = state.as_ref() {
259                splits
260                    .iter()
261                    .map(|split| (split.id(), split.clone()))
262                    .collect::<HashMap<_, _>>()
263            } else {
264                HashMap::new()
265            }
266        };
267
268        let (Some(split_idx), Some(offset_idx), _) =
269            get_split_offset_col_idx(&self.source_desc.columns)
270        else {
271            unreachable!("Partition and offset columns must be set.");
272        };
273
274        let mut backoff = get_infinite_backoff_strategy();
275
276        'build_consume_loop: loop {
277            let bootstrap_state = if latest_splits_info.is_empty() {
278                None
279            } else {
280                Some(latest_splits_info.values().cloned().collect_vec())
281            };
282            tracing::debug!(
283                "build stream source reader with state: {:?}",
284                bootstrap_state
285            );
286            let build_stream_result = if let Some(exist_stream) = self.reader_stream.take() {
287                Ok((exist_stream, CreateSplitReaderResult::default()))
288            } else {
289                self.source_desc
290                    .source
291                    .build_stream(
292                        bootstrap_state,
293                        column_ids.clone(),
294                        source_ctx_ref.clone(),
295                        // just `seek_to_latest` for initial build
296                        is_initial_build,
297                    )
298                    .await
299            };
300            if let Err(e) = build_stream_result {
301                if is_initial_build {
302                    return Err(StreamExecutorError::connector_error(e));
303                } else {
304                    let delay = backoff.next().unwrap();
305                    tracing::error!(
306                        error = %e.as_report(),
307                        source_name = self.source_name,
308                        source_id = %self.source_id,
309                        actor_id = %self.actor_ctx.id,
310                        "build stream source reader error, retry in {delay:?}"
311                    );
312                    GLOBAL_ERROR_METRICS.user_source_error.report([
313                        e.variant_name().to_owned(),
314                        self.source_id.to_string(),
315                        self.source_name.clone(),
316                        self.actor_ctx.fragment_id.to_string(),
317                    ]);
318                    tokio::time::sleep(delay).await;
319                    continue 'build_consume_loop;
320                }
321            }
322
323            let (stream, _) = build_stream_result.unwrap();
324            let stream = apply_rate_limit_to_source_reader_event(stream, self.rate_limit).boxed();
325            let mut is_error = false;
326            let mut has_progress = false;
327            #[for_await]
328            'consume: for event in stream {
329                let event = match event {
330                    Ok(event) => {
331                        has_progress = true;
332                        event
333                    }
334                    Err(e) => {
335                        tracing::error!(
336                            error = %e.as_report(),
337                            source_name = self.source_name,
338                            source_id = %self.source_id,
339                            actor_id = %self.actor_ctx.id,
340                            "stream source reader error"
341                        );
342                        GLOBAL_ERROR_METRICS.user_source_error.report([
343                            e.variant_name().to_owned(),
344                            self.source_id.to_string(),
345                            self.source_name.clone(),
346                            self.actor_ctx.fragment_id.to_string(),
347                        ]);
348                        is_error = true;
349                        break 'consume;
350                    }
351                };
352
353                match event {
354                    SourceReaderEvent::DataChunk(chunk) => {
355                        Self::update_offsets_from_chunk(
356                            &mut latest_splits_info,
357                            &chunk,
358                            split_idx,
359                            offset_idx,
360                        );
361                        yield SourceReaderEventWithState::Data((chunk, latest_splits_info.clone()));
362                    }
363                    SourceReaderEvent::SplitProgress(split_progress) => {
364                        Self::apply_split_progress(&mut latest_splits_info, split_progress);
365                        yield SourceReaderEventWithState::Progress(latest_splits_info.clone());
366                    }
367                }
368            }
369            if !is_error {
370                tracing::info!("stream source reader consume finished");
371                latest_splits_info.values_mut().for_each(|split_impl| {
372                    if let Some(mut batch_split) = split_impl.clone().into_batch_split() {
373                        batch_split.finish();
374                        *split_impl = batch_split.into();
375                    }
376                });
377                yield SourceReaderEventWithState::Data((
378                    StreamChunk::empty(
379                        self.source_desc
380                            .columns
381                            .iter()
382                            .map(|c| c.data_type.clone())
383                            .collect_vec()
384                            .as_slice(),
385                    ),
386                    latest_splits_info.clone(),
387                ));
388                break 'build_consume_loop;
389            }
390            if has_progress {
391                backoff = get_infinite_backoff_strategy();
392            }
393            let delay = backoff.next().unwrap();
394            tracing::info!("stream source reader error, retry in {delay:?}");
395            tokio::time::sleep(delay).await;
396        }
397    }
398}