1use std::collections::HashMap;
16use std::fmt::Debug;
17use std::sync::LazyLock;
18
19use anyhow::{Context, bail};
20use auto_enums::auto_enum;
21pub use avro::AvroParserConfig;
22pub use canal::*;
23pub use chunk_builder::{SourceStreamChunkBuilder, SourceStreamChunkRowWriter};
24use csv_parser::CsvParser;
25pub use debezium::*;
26use futures::{Future, Stream, StreamExt, TryFutureExt, TryStreamExt};
27use futures_async_stream::try_stream;
28pub use json_parser::*;
29pub use parquet_parser::ParquetParser;
30pub use protobuf::*;
31use risingwave_common::catalog::{
32 CDC_TABLE_NAME_COLUMN_NAME, Field, KAFKA_TIMESTAMP_COLUMN_NAME, Schema,
33};
34use risingwave_common::log::LogSuppressor;
35use risingwave_common::metrics::GLOBAL_ERROR_METRICS;
36use risingwave_common::row::OwnedRow;
37use risingwave_common::types::{Datum, DatumCow, DatumRef};
38use risingwave_common::util::tracing::InstrumentStream;
39use risingwave_connector_codec::decoder::avro::MapHandling;
40use thiserror_ext::AsReport;
41
42pub use self::mysql::{
43 mysql_datum_to_rw_datum, mysql_row_to_owned_row, mysql_row_to_owned_row_with_strict_pk,
44};
45use self::plain_parser::PlainParser;
46pub use self::postgres::{
47 postgres_cell_to_scalar_impl, postgres_cell_to_scalar_impl_strict, postgres_row_to_owned_row,
48 postgres_row_to_owned_row_with_strict_pk,
49};
50pub use self::sql_server::{ScalarImplTiberiusWrapper, SqlServerRowDecoder};
51pub use self::unified::Access;
52pub use self::unified::json::{
53 BigintUnsignedHandlingMode, JsonAccess, NumericHandling, TimeHandling, TimestampHandling,
54 TimestamptzHandling,
55};
56use self::upsert_parser::UpsertParser;
57use crate::error::ConnectorResult;
58use crate::parser::maxwell::MaxwellParser;
59use crate::schema::schema_registry::SchemaRegistryConfig;
60use crate::source::monitor::GLOBAL_SOURCE_METRICS;
61use crate::source::{
62 BoxSourceMessageEventStream, ConnectorProperties, SourceChunkStream, SourceColumnDesc,
63 SourceColumnType, SourceContext, SourceContextRef, SourceCtrlOpts, SourceMessageEvent,
64 SourceMeta, SourceReaderEvent,
65};
66
67fn debezium_numeric_handling(connector_props: &ConnectorProperties) -> NumericHandling {
71 match connector_props.native_cdc_type() {
72 Some(cdc_type) => cdc_type.debezium_numeric_handling(),
73 None => NumericHandling::Relax {
74 string_parsing: false,
75 },
76 }
77}
78
79fn decode_row_with_strict_pk(
80 connector_name: &str,
81 schema: &Schema,
82 pk_indices: &[usize],
83 mut decode: impl FnMut(usize, &Field) -> anyhow::Result<Datum>,
84 mut log_non_pk_error: impl FnMut(&str, anyhow::Error),
85) -> anyhow::Result<OwnedRow> {
86 if let Some(index) = pk_indices
87 .iter()
88 .copied()
89 .find(|index| *index >= schema.fields.len())
90 {
91 bail!(
92 "{connector_name} snapshot primary-key index {index} is out of bounds for {} columns",
93 schema.fields.len()
94 );
95 }
96
97 let mut datums = Vec::with_capacity(schema.fields.len());
98 for (index, field) in schema.fields.iter().enumerate() {
99 let is_pk = pk_indices.contains(&index);
100 let decode_result = decode(index, field);
101 let datum = if is_pk {
102 decode_result.with_context(|| {
103 format!(
104 "failed to decode {connector_name} snapshot primary key `{}`",
105 field.name
106 )
107 })?
108 } else {
109 match decode_result {
110 Ok(datum) => datum,
111 Err(err) => {
112 log_non_pk_error(&field.name, err);
113 None
114 }
115 }
116 };
117 if is_pk && datum.is_none() {
118 bail!(
119 "{connector_name} snapshot primary key `{}` cannot be NULL",
120 field.name
121 );
122 }
123 datums.push(datum);
124 }
125 Ok(OwnedRow::new(datums))
126}
127
128#[cfg(test)]
129mod strict_pk_tests {
130 use anyhow::anyhow;
131 use risingwave_common::row::Row;
132 use risingwave_common::types::{DataType, ScalarImpl};
133
134 use super::*;
135
136 fn test_schema() -> Schema {
137 Schema::new(vec![
138 Field::with_name(DataType::Int32, "id"),
139 Field::with_name(DataType::Int32, "payload"),
140 ])
141 }
142
143 #[test]
144 fn strict_pk_propagates_decode_error() {
145 let err = decode_row_with_strict_pk(
146 "test",
147 &test_schema(),
148 &[0],
149 |index, _| {
150 if index == 0 {
151 Err(anyhow!("malformed integer"))
152 } else {
153 Ok(Some(ScalarImpl::Int32(1)))
154 }
155 },
156 |_, _| unreachable!(),
157 )
158 .unwrap_err();
159
160 assert!(err.to_string().contains("snapshot primary key `id`"));
161 assert!(format!("{err:#}").contains("malformed integer"));
162 }
163
164 #[test]
165 fn strict_pk_rejects_decoded_null() {
166 let err = decode_row_with_strict_pk(
167 "test",
168 &test_schema(),
169 &[0],
170 |_, _| Ok(None),
171 |_, _| unreachable!(),
172 )
173 .unwrap_err();
174
175 assert!(
176 err.to_string()
177 .contains("snapshot primary key `id` cannot be NULL")
178 );
179 }
180
181 #[test]
182 fn strict_pk_keeps_non_pk_decode_lenient() {
183 let mut logged_columns = Vec::new();
184 let row = decode_row_with_strict_pk(
185 "test",
186 &test_schema(),
187 &[0],
188 |index, _| {
189 if index == 0 {
190 Ok(Some(ScalarImpl::Int32(1)))
191 } else {
192 Err(anyhow!("malformed payload"))
193 }
194 },
195 |name, _| logged_columns.push(name.to_owned()),
196 )
197 .unwrap();
198
199 assert!(row.datum_at(0).is_some());
200 assert!(row.datum_at(1).is_none());
201 assert_eq!(logged_columns, ["payload"]);
202 }
203}
204
205mod access_builder;
206pub mod additional_columns;
207mod avro;
208mod bytes_parser;
209mod canal;
210mod chunk_builder;
211mod config;
212mod csv_parser;
213mod debezium;
214mod json_parser;
215mod maxwell;
216mod mysql;
217pub mod parquet_parser;
218pub mod plain_parser;
219mod postgres;
220mod protobuf;
221pub mod scalar_adapter;
222mod sql_server;
223mod unified;
224mod upsert_parser;
225mod utils;
226
227use access_builder::{AccessBuilder, AccessBuilderImpl};
228pub use config::*;
229
230pub(crate) fn into_data_chunk_stream(
231 stream: impl Stream<Item = ConnectorResult<SourceReaderEvent>> + Send + 'static,
232) -> impl SourceChunkStream {
233 stream
234 .try_filter_map(|event| async move {
235 Ok(match event {
236 SourceReaderEvent::DataChunk(chunk) => Some(chunk),
237 SourceReaderEvent::SplitProgress(_) => None,
238 })
239 })
240 .boxed()
241}
242pub use debezium::DEBEZIUM_IGNORE_KEY;
243use debezium::schema_change::SchemaChangeEnvelope;
244pub use unified::{AccessError, AccessResult};
245
246#[derive(Clone, Copy, Debug)]
250pub struct MessageMeta<'a> {
251 source_meta: &'a SourceMeta,
252 split_id: &'a str,
253 offset: &'a str,
254}
255
256impl<'a> MessageMeta<'a> {
257 fn value_for_column(self, desc: &SourceColumnDesc) -> DatumRef<'a> {
261 let datum: DatumRef<'_> = match desc.column_type {
262 SourceColumnType::RowId => None,
265 SourceColumnType::Offset => Some(self.offset.into()),
267 SourceColumnType::Meta if let SourceMeta::Kafka(kafka_meta) = self.source_meta => {
269 assert_eq!(
270 desc.name.as_str(),
271 KAFKA_TIMESTAMP_COLUMN_NAME,
272 "unexpected kafka meta column name"
273 );
274 kafka_meta.extract_timestamp()
275 }
276 SourceColumnType::Meta if let SourceMeta::DebeziumCdc(cdc_meta) = self.source_meta => {
277 assert_eq!(
278 desc.name.as_str(),
279 CDC_TABLE_NAME_COLUMN_NAME,
280 "unexpected cdc meta column name"
281 );
282 Some(cdc_meta.full_table_name.as_str().into())
283 }
284
285 SourceColumnType::Meta | SourceColumnType::Normal => return None,
287 };
288
289 datum
290 }
291}
292
293#[derive(Debug)]
295pub enum TransactionControl {
296 Begin { id: Box<str> },
297 Commit { id: Box<str> },
298}
299
300#[derive(Debug)]
302pub enum ParseResult {
303 Rows,
305 TransactionControl(TransactionControl),
307
308 SchemaChange(SchemaChangeEnvelope),
310}
311
312#[derive(Clone, Copy, Debug, PartialEq)]
313pub enum ParserFormat {
314 CanalJson,
315 Csv,
316 Json,
317 Maxwell,
318 Debezium,
319 DebeziumMongo,
320 Upsert,
321 Plain,
322}
323
324pub trait ByteStreamSourceParser: Send + Debug + Sized + 'static {
329 fn columns(&self) -> &[SourceColumnDesc];
331
332 fn source_ctx(&self) -> &SourceContext;
334
335 fn parser_format(&self) -> ParserFormat;
337
338 fn parse_one<'a>(
342 &'a mut self,
343 key: Option<Vec<u8>>,
344 payload: Option<Vec<u8>>,
345 writer: SourceStreamChunkRowWriter<'a>,
346 ) -> impl Future<Output = ConnectorResult<()>> + Send + 'a;
347
348 fn parse_one_with_txn<'a>(
356 &'a mut self,
357 key: Option<Vec<u8>>,
358 payload: Option<Vec<u8>>,
359 writer: SourceStreamChunkRowWriter<'a>,
360 ) -> impl Future<Output = ConnectorResult<ParseResult>> + Send + 'a {
361 self.parse_one(key, payload, writer)
362 .map_ok(|_| ParseResult::Rows)
363 }
364}
365
366#[easy_ext::ext(SourceParserIntoStreamExt)]
367impl<P: ByteStreamSourceParser> P {
368 pub fn parse_stream_with_events(
369 self,
370 msg_stream: BoxSourceMessageEventStream,
371 ) -> impl Stream<Item = ConnectorResult<SourceReaderEvent>> + Send {
372 let actor_id = self.source_ctx().actor_id;
373 let source_id = self.source_ctx().source_id.as_raw_id();
374
375 let source_ctrl_opts = self.source_ctx().source_ctrl_opts;
378 parse_message_stream(self, msg_stream, source_ctrl_opts).instrument_with(
379 move || tracing::info_span!("source_parse_chunk", %actor_id, source_id),
380 )
381 }
382}
383
384#[try_stream(ok = SourceReaderEvent, error = crate::error::ConnectorError)]
387async fn parse_message_stream<P: ByteStreamSourceParser>(
388 mut parser: P,
389 msg_stream: BoxSourceMessageEventStream,
390 source_ctrl_opts: SourceCtrlOpts,
391) {
392 let mut chunk_builder =
393 SourceStreamChunkBuilder::new(parser.columns().to_vec(), source_ctrl_opts);
394
395 let mut direct_cdc_event_lag_latency_metrics = HashMap::new();
396
397 #[for_await]
398 for event in msg_stream {
399 let batch = match event? {
405 SourceMessageEvent::Data(batch) => batch,
406 SourceMessageEvent::SplitProgress(progress) => {
407 yield SourceReaderEvent::SplitProgress(progress);
408 continue;
409 }
410 };
411 let batch_len = batch.len();
412 if batch_len == 0 {
413 continue;
414 }
415
416 let mut txn_started_in_last_batch = chunk_builder.is_in_transaction();
417 let process_time_ms = chrono::Utc::now().timestamp_millis();
418 let mut is_heartbeat_emitted = false;
419 for msg in batch {
420 if msg.is_cdc_heartbeat() {
421 if !is_heartbeat_emitted {
422 tracing::debug!(offset = msg.offset, "handling a heartbeat message");
423 chunk_builder.heartbeat(MessageMeta {
424 source_meta: &msg.meta,
425 split_id: &msg.split_id,
426 offset: &msg.offset,
427 });
428 for chunk in chunk_builder.consume_ready_chunks() {
429 yield SourceReaderEvent::DataChunk(chunk);
430 }
431 is_heartbeat_emitted = true;
432 }
433 continue;
434 }
435
436 if let SourceMeta::DebeziumCdc(msg_meta) = &msg.meta {
438 let lag_ms = process_time_ms - msg_meta.source_ts_ms;
439 let full_table_name = msg_meta.full_table_name.clone();
441 let direct_cdc_event_lag_latency = direct_cdc_event_lag_latency_metrics
442 .entry(full_table_name)
443 .or_insert_with(|| {
444 GLOBAL_SOURCE_METRICS
445 .direct_cdc_event_lag_latency
446 .with_guarded_label_values(&[&msg_meta.full_table_name])
447 });
448 direct_cdc_event_lag_latency.observe(lag_ms as f64);
449 }
450
451 match parser
455 .parse_one_with_txn(
456 msg.key,
457 msg.payload,
458 chunk_builder.row_writer().with_meta(MessageMeta {
459 source_meta: &msg.meta,
460 split_id: &msg.split_id,
461 offset: &msg.offset,
462 }),
463 )
464 .await
465 {
466 res @ (Ok(ParseResult::Rows) | Err(_)) => {
469 if let Err(error) = res {
470 static LOG_SUPPRESSOR: LazyLock<LogSuppressor> =
473 LazyLock::new(LogSuppressor::default);
474 if let Ok(suppressed_count) = LOG_SUPPRESSOR.check() {
475 tracing::error!(
476 error = %error.as_report(),
477 split_id = &*msg.split_id,
478 offset = msg.offset,
479 suppressed_count,
480 "failed to parse message, skipping"
481 );
482 }
483
484 let context = parser.source_ctx();
486 GLOBAL_ERROR_METRICS.user_source_error.report([
487 error.variant_name().to_owned(),
488 context.source_id.to_string(),
489 context.source_name.clone(),
490 context.fragment_id.to_string(),
491 ]);
492 }
493
494 for chunk in chunk_builder.consume_ready_chunks() {
495 yield SourceReaderEvent::DataChunk(chunk);
496 }
497 }
498
499 Ok(ParseResult::TransactionControl(txn_ctl)) => match txn_ctl {
500 TransactionControl::Begin { id } => {
501 chunk_builder.begin_transaction(id);
502 }
503 TransactionControl::Commit { id } => {
504 chunk_builder.commit_transaction(id);
505 assert!(!chunk_builder.is_in_transaction());
506
507 if txn_started_in_last_batch {
508 chunk_builder.finish_current_chunk();
511 txn_started_in_last_batch = false;
512 }
513
514 for chunk in chunk_builder.consume_ready_chunks() {
515 yield SourceReaderEvent::DataChunk(chunk);
516 }
517 }
518 },
519
520 Ok(ParseResult::SchemaChange(schema_change)) => {
521 if schema_change.is_empty() {
522 continue;
523 }
524
525 let (oneshot_tx, oneshot_rx) = tokio::sync::oneshot::channel();
526 if let Some(ref tx) = parser.source_ctx().schema_change_tx {
530 tx.send((schema_change, oneshot_tx))
531 .await
532 .expect("send schema change to executor");
533 match oneshot_rx.await {
534 Ok(()) => {}
535 Err(e) => {
536 tracing::error!(error = %e.as_report(), "failed to wait for schema change");
537 }
538 }
539 }
540 }
541 }
542 }
543
544 if !chunk_builder.is_in_transaction() {
546 chunk_builder.finish_current_chunk();
547 }
548 for chunk in chunk_builder.consume_ready_chunks() {
549 yield SourceReaderEvent::DataChunk(chunk);
550 }
551 }
552}
553
554#[derive(Debug)]
555pub enum EncodingType {
556 Key,
557 Value,
558}
559
560#[derive(Debug)]
563pub enum ByteStreamSourceParserImpl {
564 Csv(CsvParser),
565 Debezium(DebeziumParser),
566 Plain(PlainParser),
567 Upsert(UpsertParser),
568 DebeziumMongoJson(DebeziumMongoJsonParser),
569 Maxwell(MaxwellParser),
570 CanalJson(CanalJsonParser),
571}
572
573impl ByteStreamSourceParserImpl {
574 pub fn parse_stream_with_events(
575 self,
576 msg_stream: BoxSourceMessageEventStream,
577 ) -> impl Stream<Item = ConnectorResult<SourceReaderEvent>> + Send {
578 #[auto_enum(futures03::Stream)]
579 let stream = match self {
580 Self::Csv(parser) => parser.parse_stream_with_events(msg_stream),
581 Self::Debezium(parser) => parser.parse_stream_with_events(msg_stream),
582 Self::DebeziumMongoJson(parser) => parser.parse_stream_with_events(msg_stream),
583 Self::Maxwell(parser) => parser.parse_stream_with_events(msg_stream),
584 Self::CanalJson(parser) => parser.parse_stream_with_events(msg_stream),
585 Self::Plain(parser) => parser.parse_stream_with_events(msg_stream),
586 Self::Upsert(parser) => parser.parse_stream_with_events(msg_stream),
587 };
588 Box::pin(stream)
589 }
590}
591
592impl ByteStreamSourceParserImpl {
593 pub async fn create(
594 parser_config: ParserConfig,
595 source_ctx: SourceContextRef,
596 ) -> ConnectorResult<Self> {
597 let CommonParserConfig { rw_columns } = parser_config.common;
598 let protocol = &parser_config.specific.protocol_config;
599 let encode = &parser_config.specific.encoding_config;
600 match (protocol, encode) {
601 (ProtocolProperties::Plain, EncodingProperties::Csv(config)) => {
602 CsvParser::new(rw_columns, *config, source_ctx).map(Self::Csv)
603 }
604 (ProtocolProperties::DebeziumMongo, EncodingProperties::MongoJson(props)) => {
605 DebeziumMongoJsonParser::new(rw_columns, source_ctx, props.clone())
606 .map(Self::DebeziumMongoJson)
607 }
608 (ProtocolProperties::Canal, EncodingProperties::Json(config)) => {
609 CanalJsonParser::new(rw_columns, source_ctx, config).map(Self::CanalJson)
610 }
611 (ProtocolProperties::Native, _) => unreachable!("Native parser should not be created"),
612 (ProtocolProperties::Upsert, _) => {
613 let parser =
614 UpsertParser::new(parser_config.specific, rw_columns, source_ctx).await?;
615 Ok(Self::Upsert(parser))
616 }
617 (ProtocolProperties::Plain, _) => {
618 let parser =
619 PlainParser::new(parser_config.specific, rw_columns, source_ctx).await?;
620 Ok(Self::Plain(parser))
621 }
622 (ProtocolProperties::Debezium(_), _) => {
623 let numeric_handling = debezium_numeric_handling(&source_ctx.connector_props);
624 let parser = DebeziumParser::new(
625 parser_config.specific,
626 rw_columns,
627 source_ctx,
628 numeric_handling,
629 )
630 .await?;
631 Ok(Self::Debezium(parser))
632 }
633 (ProtocolProperties::Maxwell, _) => {
634 let parser =
635 MaxwellParser::new(parser_config.specific, rw_columns, source_ctx).await?;
636 Ok(Self::Maxwell(parser))
637 }
638 _ => unreachable!(),
639 }
640 }
641
642 pub fn create_for_test(parser_config: ParserConfig) -> ConnectorResult<Self> {
644 futures::executor::block_on(Self::create(parser_config, SourceContext::dummy().into()))
645 }
646}
647
648#[cfg(test)]
650pub mod test_utils {
651 use futures::StreamExt;
652 use itertools::Itertools;
653 use risingwave_common::array::StreamChunk;
654
655 use super::*;
656 use crate::source::SourceMessage;
657
658 #[easy_ext::ext(ByteStreamSourceParserImplTestExt)]
659 pub(crate) impl ByteStreamSourceParserImpl {
660 async fn parse(self, payloads: Vec<Vec<u8>>) -> StreamChunk {
662 let source_messages = payloads
663 .into_iter()
664 .map(|p| SourceMessage {
665 payload: (!p.is_empty()).then_some(p),
666 ..SourceMessage::dummy()
667 })
668 .collect_vec();
669
670 into_data_chunk_stream(
671 self.parse_stream_with_events(
672 futures::stream::once(async { Ok(SourceMessageEvent::Data(source_messages)) })
673 .boxed(),
674 ),
675 )
676 .next()
677 .await
678 .unwrap()
679 .unwrap()
680 }
681
682 async fn parse_upsert(self, kvs: Vec<(Vec<u8>, Vec<u8>)>) -> StreamChunk {
684 let source_messages = kvs
685 .into_iter()
686 .map(|(k, v)| SourceMessage {
687 key: (!k.is_empty()).then_some(k),
688 payload: (!v.is_empty()).then_some(v),
689 ..SourceMessage::dummy()
690 })
691 .collect_vec();
692
693 into_data_chunk_stream(
694 self.parse_stream_with_events(
695 futures::stream::once(async { Ok(SourceMessageEvent::Data(source_messages)) })
696 .boxed(),
697 ),
698 )
699 .next()
700 .await
701 .unwrap()
702 .unwrap()
703 }
704 }
705}