Skip to main content

risingwave_connector/source/
mod.rs

1// Copyright 2022 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
15pub mod prelude {
16    // import all split enumerators
17    pub use crate::source::datagen::DatagenSplitEnumerator;
18    pub use crate::source::filesystem::LegacyS3SplitEnumerator;
19    pub use crate::source::filesystem::opendal_source::OpendalEnumerator;
20    pub use crate::source::google_pubsub::PubsubSplitEnumerator as GooglePubsubSplitEnumerator;
21    pub use crate::source::iceberg::IcebergSplitEnumerator;
22    pub use crate::source::kafka::KafkaSplitEnumerator;
23    pub use crate::source::kinesis::KinesisSplitEnumerator;
24    pub use crate::source::mqtt::MqttSplitEnumerator;
25    pub use crate::source::nats::NatsSplitEnumerator;
26    pub use crate::source::nexmark::NexmarkSplitEnumerator;
27    pub use crate::source::pulsar::PulsarSplitEnumerator;
28    pub use crate::source::test_source::TestSourceSplitEnumerator as TestSplitEnumerator;
29    pub type AzblobSplitEnumerator =
30        OpendalEnumerator<crate::source::filesystem::opendal_source::OpendalAzblob>;
31    pub type GcsSplitEnumerator =
32        OpendalEnumerator<crate::source::filesystem::opendal_source::OpendalGcs>;
33    pub type OpendalS3SplitEnumerator =
34        OpendalEnumerator<crate::source::filesystem::opendal_source::OpendalS3>;
35    pub type PosixFsSplitEnumerator =
36        OpendalEnumerator<crate::source::filesystem::opendal_source::OpendalPosixFs>;
37    pub use crate::source::cdc::enumerator::DebeziumSplitEnumerator;
38    pub use crate::source::filesystem::opendal_source::BatchPosixFsEnumerator as BatchPosixFsSplitEnumerator;
39    pub type MongodbCdcSplitEnumerator = DebeziumSplitEnumerator<crate::source::cdc::Mongodb>;
40    pub type PostgresCdcSplitEnumerator = DebeziumSplitEnumerator<crate::source::cdc::Postgres>;
41    pub type MysqlCdcSplitEnumerator = DebeziumSplitEnumerator<crate::source::cdc::Mysql>;
42    pub type MariadbCdcSplitEnumerator = DebeziumSplitEnumerator<crate::source::cdc::Mariadb>;
43    pub type SqlServerCdcSplitEnumerator = DebeziumSplitEnumerator<crate::source::cdc::SqlServer>;
44    pub type OracleCdcSplitEnumerator = DebeziumSplitEnumerator<crate::source::cdc::Oracle>;
45}
46
47pub mod base;
48pub mod batch;
49pub mod cdc;
50pub mod data_gen_util;
51pub mod datagen;
52pub mod filesystem;
53pub mod google_pubsub;
54pub mod kafka;
55pub mod kinesis;
56pub mod monitor;
57pub mod mqtt;
58pub mod nats;
59pub mod nexmark;
60pub mod pulsar;
61pub mod utils;
62
63mod util;
64use std::collections::HashMap;
65use std::future::IntoFuture;
66use std::time::Duration;
67
68pub use base::{UPSTREAM_SOURCE_KEY, WEBHOOK_CONNECTOR, *};
69pub use batch::BatchSourceSplitImpl;
70pub(crate) use common::*;
71use gcloud_pubsub::subscription::Subscription;
72pub use google_pubsub::GOOGLE_PUBSUB_CONNECTOR;
73pub use kafka::KAFKA_CONNECTOR;
74pub use kinesis::KINESIS_CONNECTOR;
75use monitor::{ConnectorAckFailureType, GLOBAL_SOURCE_METRICS};
76pub use mqtt::MQTT_CONNECTOR;
77pub use nats::NATS_CONNECTOR;
78use utils::feature_gated_source_mod;
79
80pub use self::adbc_snowflake::ADBC_SNOWFLAKE_CONNECTOR;
81mod common;
82pub mod iceberg;
83pub mod ingest_mode;
84mod manager;
85pub mod reader;
86pub mod test_source;
87feature_gated_source_mod!(adbc_snowflake, "adbc_snowflake");
88
89use async_nats::jetstream::consumer::AckPolicy as JetStreamAckPolicy;
90use async_nats::jetstream::context::Context as JetStreamContext;
91pub use manager::{SourceColumnDesc, SourceColumnType};
92use risingwave_common::array::{Array, ArrayRef};
93use risingwave_common::row::OwnedRow;
94use risingwave_pb::id::{ActorId, SourceId};
95use thiserror_ext::AsReport;
96pub use util::fill_adaptive_split;
97
98pub use crate::source::filesystem::LEGACY_S3_CONNECTOR;
99pub use crate::source::filesystem::opendal_source::{
100    AZBLOB_CONNECTOR, BATCH_POSIX_FS_CONNECTOR, GCS_CONNECTOR, OPENDAL_S3_CONNECTOR,
101    POSIX_FS_CONNECTOR,
102};
103pub use crate::source::nexmark::NEXMARK_CONNECTOR;
104pub use crate::source::pulsar::PULSAR_CONNECTOR;
105use crate::source::pulsar::source::reader::PULSAR_ACK_CHANNEL;
106
107pub fn should_copy_to_format_encode_options(key: &str, connector: &str) -> bool {
108    const PREFIXES: &[&str] = &[
109        "schema.registry",
110        "schema.location",
111        "message",
112        "key.message",
113        "without_header",
114        "delimiter",
115        // AwsAuthProps
116        "region",
117        "endpoint_url",
118        "access_key",
119        "secret_key",
120        "session_token",
121        "arn",
122        "external_id",
123        "profile",
124    ];
125    PREFIXES.iter().any(|prefix| key.starts_with(prefix))
126        || (key == "endpoint" && !connector.eq_ignore_ascii_case(KINESIS_CONNECTOR))
127}
128
129/// Tasks executed by `WaitCheckpointWorker`
130pub enum WaitCheckpointTask {
131    CommitCdcOffset(Option<(SplitId, String)>),
132    AckPubsubMessage(Subscription, Vec<ArrayRef>),
133    AckNatsJetStream(JetStreamContext, Vec<ArrayRef>, JetStreamAckPolicy),
134    AckPulsarMessage(Vec<(String, ArrayRef)>),
135}
136
137impl WaitCheckpointTask {
138    /// Create a fresh task for the next epoch, reusing expensive-to-create clients
139    /// (e.g. `PubSub` `Subscription`, NATS `JetStreamContext`) from the current task.
140    /// This avoids re-establishing gRPC/network connections on every checkpoint.
141    pub fn reset_for_next_epoch(&self) -> Self {
142        match self {
143            WaitCheckpointTask::CommitCdcOffset(_) => WaitCheckpointTask::CommitCdcOffset(None),
144            WaitCheckpointTask::AckPubsubMessage(subscription, _) => {
145                WaitCheckpointTask::AckPubsubMessage(subscription.clone(), vec![])
146            }
147            WaitCheckpointTask::AckNatsJetStream(context, _, ack_policy) => {
148                WaitCheckpointTask::AckNatsJetStream(context.clone(), vec![], *ack_policy)
149            }
150            WaitCheckpointTask::AckPulsarMessage(_) => WaitCheckpointTask::AckPulsarMessage(vec![]),
151        }
152    }
153
154    pub async fn run(self, source_id: SourceId, source_name: &str) {
155        self.run_with_on_commit_success(source_id, source_name, |_source_id, _offset| {
156            // Default implementation: no action on commit success
157        })
158        .await;
159    }
160
161    pub async fn run_with_on_commit_success<F>(
162        self,
163        source_id: SourceId,
164        source_name: &str,
165        mut on_commit_success: F,
166    ) where
167        F: FnMut(u64, &str),
168    {
169        use std::str::FromStr;
170        let source_id_label = source_id.to_string();
171        match self {
172            WaitCheckpointTask::CommitCdcOffset(updated_offset) => {
173                if let Some((split_id, offset)) = updated_offset {
174                    let committed_source_id: u64 = u64::from_str(split_id.as_ref()).unwrap();
175                    // notify cdc connector to commit offset
176                    match cdc::jni_source::commit_cdc_offset(committed_source_id, offset.clone()) {
177                        Ok(()) => {
178                            // Execute callback after successful commit
179                            on_commit_success(committed_source_id, &offset);
180                        }
181                        Err(e) => {
182                            tracing::error!(
183                                source_id = committed_source_id,
184                                source_name,
185                                error = %e.as_report(),
186                                "source#{committed_source_id}: failed to commit cdc offset: {offset}.",
187                            )
188                        }
189                    }
190                }
191            }
192            WaitCheckpointTask::AckPulsarMessage(ack_array) => {
193                let mut latest_ack_by_channel = HashMap::new();
194                for (ack_channel_id, to_cumulative_ack) in ack_array {
195                    let encode_message_id_data = to_cumulative_ack
196                        .as_bytea()
197                        .iter()
198                        .flatten()
199                        .last()
200                        .map(|message_id| message_id.to_owned());
201
202                    if let Some(encode_message_id_data) = encode_message_id_data {
203                        latest_ack_by_channel.insert(ack_channel_id, Some(encode_message_id_data));
204                    } else {
205                        latest_ack_by_channel.entry(ack_channel_id).or_insert(None);
206                    }
207                }
208
209                for (ack_channel_id, encode_message_id_data) in latest_ack_by_channel {
210                    let Some(encode_message_id_data) = encode_message_id_data else {
211                        GLOBAL_SOURCE_METRICS.inc_connector_ack_failure_count(
212                            source_name,
213                            "pulsar",
214                            ConnectorAckFailureType::EmptyMessageId,
215                        );
216                        tracing::warn!(
217                            source_id = source_id_label,
218                            source_name,
219                            ack_channel_id,
220                            "skip Pulsar ack because the checkpoint ack batches have no message id",
221                        );
222                        continue;
223                    };
224
225                    let Some(ack_tx) = PULSAR_ACK_CHANNEL.lock().get(&ack_channel_id).cloned()
226                    else {
227                        GLOBAL_SOURCE_METRICS.inc_connector_ack_failure_count(
228                            source_name,
229                            "pulsar",
230                            ConnectorAckFailureType::ChannelMissing,
231                        );
232                        tracing::warn!(
233                            source_id = source_id_label,
234                            source_name,
235                            ack_channel_id,
236                            "skip Pulsar ack because the ack channel is missing",
237                        );
238                        continue;
239                    };
240
241                    if let Err(e) = ack_tx.send(encode_message_id_data) {
242                        GLOBAL_SOURCE_METRICS.inc_connector_ack_failure_count(
243                            source_name,
244                            "pulsar",
245                            ConnectorAckFailureType::ChannelSendError,
246                        );
247                        tracing::warn!(
248                            source_id = source_id_label,
249                            source_name,
250                            ack_channel_id,
251                            error = %e.as_report(),
252                            "failed to send Pulsar ack message id to the reader ack channel",
253                        );
254                    }
255                }
256            }
257            WaitCheckpointTask::AckPubsubMessage(subscription, ack_id_arrs) => {
258                const ACK_RPC_TIMEOUT: Duration = Duration::from_secs(30);
259                async fn ack(
260                    subscription: &Subscription,
261                    ack_ids: Vec<String>,
262                    source_id_label: &str,
263                    source_name: &str,
264                ) {
265                    if ack_ids.is_empty() {
266                        return;
267                    }
268                    tracing::trace!("acking pubsub messages {:?}", ack_ids);
269                    match tokio::time::timeout(ACK_RPC_TIMEOUT, subscription.ack(ack_ids)).await {
270                        Ok(Ok(())) => {
271                            GLOBAL_SOURCE_METRICS
272                                .inc_connector_ack_success_count(source_name, "pubsub");
273                        }
274                        Ok(Err(e)) => {
275                            GLOBAL_SOURCE_METRICS.inc_connector_ack_failure_count(
276                                source_name,
277                                "pubsub",
278                                ConnectorAckFailureType::Error,
279                            );
280                            tracing::error!(
281                                source_id = source_id_label,
282                                source_name,
283                                error = %e.as_report(),
284                                "failed to ack pubsub messages",
285                            )
286                        }
287                        Err(_) => {
288                            GLOBAL_SOURCE_METRICS.inc_connector_ack_failure_count(
289                                source_name,
290                                "pubsub",
291                                ConnectorAckFailureType::Timeout,
292                            );
293                            tracing::error!(
294                                source_id = source_id_label,
295                                source_name,
296                                "pubsub ack timed out after {ACK_RPC_TIMEOUT:?}",
297                            )
298                        }
299                    }
300                }
301                const MAX_ACK_BATCH_SIZE: usize = 1000;
302                let mut ack_ids: Vec<String> = vec![];
303                for arr in ack_id_arrs {
304                    for ack_id in arr.as_utf8().iter().flatten() {
305                        ack_ids.push(ack_id.to_owned());
306                        if ack_ids.len() >= MAX_ACK_BATCH_SIZE {
307                            ack(
308                                &subscription,
309                                std::mem::take(&mut ack_ids),
310                                &source_id_label,
311                                source_name,
312                            )
313                            .await;
314                        }
315                    }
316                }
317                ack(&subscription, ack_ids, &source_id_label, source_name).await;
318            }
319            WaitCheckpointTask::AckNatsJetStream(
320                ref context,
321                reply_subjects_arrs,
322                ref ack_policy,
323            ) => {
324                const ACK_RPC_TIMEOUT: Duration = Duration::from_secs(30);
325                async fn ack(
326                    context: &JetStreamContext,
327                    reply_subject: String,
328                    source_id_label: &str,
329                    source_name: &str,
330                ) {
331                    let fut = async {
332                        let ack_future = context
333                            .publish(reply_subject.clone(), "+ACK".into())
334                            .await
335                            .map_err(|e| e.to_report_string())?;
336                        ack_future
337                            .into_future()
338                            .await
339                            .map_err(|e| e.to_report_string())?;
340                        Ok::<(), String>(())
341                    };
342                    match tokio::time::timeout(ACK_RPC_TIMEOUT, fut).await {
343                        Ok(Ok(())) => {
344                            GLOBAL_SOURCE_METRICS
345                                .inc_connector_ack_success_count(source_name, "nats_jetstream");
346                        }
347                        Ok(Err(e)) => {
348                            GLOBAL_SOURCE_METRICS.inc_connector_ack_failure_count(
349                                source_name,
350                                "nats_jetstream",
351                                ConnectorAckFailureType::Error,
352                            );
353                            tracing::error!(
354                                source_id = source_id_label,
355                                source_name,
356                                error = %e,
357                                subject = ?reply_subject,
358                                "failed to ack NATS JetStream message",
359                            );
360                        }
361                        Err(_) => {
362                            GLOBAL_SOURCE_METRICS.inc_connector_ack_failure_count(
363                                source_name,
364                                "nats_jetstream",
365                                ConnectorAckFailureType::Timeout,
366                            );
367                            tracing::error!(
368                                source_id = source_id_label,
369                                source_name,
370                                subject = ?reply_subject,
371                                "NATS JetStream ack timed out after {ACK_RPC_TIMEOUT:?}",
372                            );
373                        }
374                    }
375                }
376
377                let reply_subjects = reply_subjects_arrs
378                    .iter()
379                    .flat_map(|arr| {
380                        arr.as_utf8()
381                            .iter()
382                            .flatten()
383                            .map(|s| s.to_owned())
384                            .collect::<Vec<String>>()
385                    })
386                    .collect::<Vec<String>>();
387
388                match ack_policy {
389                    JetStreamAckPolicy::None | JetStreamAckPolicy::FlowControl => (),
390                    JetStreamAckPolicy::Explicit => {
391                        for reply_subject in reply_subjects {
392                            if reply_subject.is_empty() {
393                                continue;
394                            }
395                            ack(context, reply_subject, &source_id_label, source_name).await;
396                        }
397                    }
398                    JetStreamAckPolicy::All => {
399                        if let Some(reply_subject) = reply_subjects.last() {
400                            ack(
401                                context,
402                                reply_subject.clone(),
403                                &source_id_label,
404                                source_name,
405                            )
406                            .await;
407                        }
408                    }
409                }
410            }
411        }
412    }
413}
414
415#[derive(Clone, Debug, PartialEq)]
416pub struct CdcTableSnapshotSplitCommon<T: Clone> {
417    pub split_id: i64,
418    pub left_bound_inclusive: T,
419    pub right_bound_exclusive: T,
420}
421
422pub type CdcTableSnapshotSplit = CdcTableSnapshotSplitCommon<OwnedRow>;
423pub type CdcTableSnapshotSplitRaw = CdcTableSnapshotSplitCommon<Vec<u8>>;
424
425/// Build the identifier of the ACK channel for a Pulsar reader.
426///
427/// Multiple actors can consume the same source split in one process, so the actor ID is required
428/// to prevent one reader from replacing another reader's channel.
429#[inline]
430pub fn build_pulsar_ack_channel_id(
431    source_id: SourceId,
432    split_id: &SplitId,
433    actor_id: ActorId,
434) -> String {
435    format!("{}-{}-{}", source_id, split_id, actor_id)
436}
437
438#[cfg(test)]
439mod tests {
440    use risingwave_common::array::{Array, BytesArray};
441    use tokio::sync::mpsc::error::TryRecvError;
442
443    use super::*;
444
445    #[test]
446    fn test_pulsar_ack_channel_id_is_actor_scoped() {
447        let source_id = SourceId::new(7);
448        let split_id: SplitId = "persistent://public/default/topic".into();
449
450        let first = build_pulsar_ack_channel_id(source_id, &split_id, ActorId::new(11));
451        let second = build_pulsar_ack_channel_id(source_id, &split_id, ActorId::new(12));
452
453        assert_ne!(first, second);
454    }
455
456    fn message_ids<const N: usize>(values: [Option<&[u8]>; N]) -> ArrayRef {
457        BytesArray::from_iter(values).into_ref()
458    }
459
460    #[tokio::test]
461    async fn test_ack_pulsar_message_for_each_split() {
462        let split_0_channel = "test-pulsar-ack-multiple-splits-0".to_owned();
463        let split_1_channel = "test-pulsar-ack-multiple-splits-1".to_owned();
464        let empty_split_channel = "test-pulsar-ack-multiple-splits-empty".to_owned();
465        let (split_0_tx, mut split_0_rx) = tokio::sync::mpsc::unbounded_channel();
466        let (split_1_tx, mut split_1_rx) = tokio::sync::mpsc::unbounded_channel();
467        let (empty_split_tx, mut empty_split_rx) = tokio::sync::mpsc::unbounded_channel();
468
469        PULSAR_ACK_CHANNEL
470            .lock()
471            .insert(split_0_channel.clone(), split_0_tx);
472        PULSAR_ACK_CHANNEL
473            .lock()
474            .insert(split_1_channel.clone(), split_1_tx);
475        PULSAR_ACK_CHANNEL
476            .lock()
477            .insert(empty_split_channel.clone(), empty_split_tx);
478
479        WaitCheckpointTask::AckPulsarMessage(vec![
480            (split_0_channel.clone(), message_ids([Some(b"split-0-old")])),
481            (
482                split_1_channel.clone(),
483                message_ids([Some(b"split-1-latest"), None]),
484            ),
485            (
486                split_0_channel.clone(),
487                message_ids([Some(b"split-0-latest")]),
488            ),
489            (split_0_channel.clone(), message_ids([None])),
490            (empty_split_channel.clone(), message_ids([None, None])),
491        ])
492        .run(SourceId::new(26891), "test_pulsar_source")
493        .await;
494
495        assert_eq!(split_0_rx.try_recv().unwrap(), b"split-0-latest");
496        assert_eq!(split_0_rx.try_recv(), Err(TryRecvError::Empty));
497        assert_eq!(split_1_rx.try_recv().unwrap(), b"split-1-latest");
498        assert_eq!(split_1_rx.try_recv(), Err(TryRecvError::Empty));
499        assert_eq!(empty_split_rx.try_recv(), Err(TryRecvError::Empty));
500
501        let mut ack_channels = PULSAR_ACK_CHANNEL.lock();
502        ack_channels.remove(&split_0_channel);
503        ack_channels.remove(&split_1_channel);
504        ack_channels.remove(&empty_split_channel);
505    }
506}