1feature_gated_sink_mod!(big_query, "bigquery");
16pub mod batching_log_sink;
17pub mod boxed;
18pub mod catalog;
19feature_gated_sink_mod!(clickhouse, ClickHouse, "clickhouse");
20pub mod coordinate;
21pub mod decouple_checkpoint_log_sink;
22feature_gated_sink_mod!(deltalake, DeltaLake, "deltalake");
23feature_gated_sink_mod!(doris, "doris");
24#[cfg(any(feature = "sink-doris", feature = "sink-starrocks"))]
25pub mod doris_starrocks_connector;
26pub mod dynamodb;
27pub mod elasticsearch_opensearch;
28pub mod encoder;
29pub mod file_sink;
30pub mod firestore;
31pub mod formatter;
32feature_gated_sink_mod!(google_pubsub, GooglePubSub, "google_pubsub");
33feature_gated_sink_mod!(lancedb, LanceDb, "lancedb");
34pub mod http;
35pub mod iceberg;
36pub mod kafka;
37pub mod kinesis;
38use risingwave_common::bail;
39use risingwave_pb::stream_plan::PbSinkSchemaChange;
40pub mod jdbc_jni_client;
41pub mod log_store;
42pub mod mock_coordination_client;
43pub mod mongodb;
44pub mod mqtt;
45pub mod nats;
46pub mod postgres;
47pub mod pulsar;
48pub mod redis;
49pub mod remote;
50pub mod snowflake_redshift;
51pub mod sqlserver;
52feature_gated_sink_mod!(starrocks, "starrocks");
53pub mod test_sink;
54pub mod trivial;
55pub mod turbopuffer;
56pub mod utils;
57pub mod writer;
58pub mod prelude {
59 pub use crate::sink::{
60 Result, SINK_TYPE_APPEND_ONLY, SINK_USER_FORCE_APPEND_ONLY_OPTION,
61 SINK_USER_FORCE_COMPACTION, Sink, SinkError, SinkParam, SinkWriterParam,
62 };
63}
64
65use std::collections::{BTreeMap, HashMap};
66use std::future::Future;
67use std::sync::{Arc, LazyLock};
68
69use ::redis::RedisError;
70use anyhow::anyhow;
71use async_trait::async_trait;
72use chrono_tz::{Tz, UTC};
73use decouple_checkpoint_log_sink::{
74 COMMIT_CHECKPOINT_INTERVAL, DEFAULT_COMMIT_CHECKPOINT_INTERVAL_WITH_SINK_DECOUPLE,
75 DEFAULT_COMMIT_CHECKPOINT_INTERVAL_WITHOUT_SINK_DECOUPLE,
76};
77use futures::future::BoxFuture;
78use opendal::Error as OpendalError;
79use prometheus::Registry;
80use risingwave_common::array::ArrayError;
81use risingwave_common::bitmap::Bitmap;
82use risingwave_common::catalog::{ColumnDesc, Field, Schema};
83use risingwave_common::config::{MetricLevel, StreamingConfig};
84use risingwave_common::hash::{ActorId, VnodeBitmapExt};
85use risingwave_common::metrics::{
86 GaugeAggregation, IntGaugeVecRelabelExt, LabelGuardedHistogram, LabelGuardedIntCounter,
87 LabelGuardedIntGaugeVec, MetricVecRelabelExt, RelabeledAggregatedIntGaugeVec,
88 RelabeledGuardedHistogramVec, RelabeledGuardedIntCounterVec,
89};
90use risingwave_common::monitor::GLOBAL_METRICS_REGISTRY;
91use risingwave_common::secret::{LocalSecretManager, SecretError};
92use risingwave_common::session_config::sink_decouple::SinkDecouple;
93use risingwave_common::{
94 register_guarded_histogram_vec_with_registry, register_guarded_int_counter_vec_with_registry,
95 register_guarded_int_gauge_vec_with_registry,
96};
97use risingwave_pb::catalog::PbSinkType;
98use risingwave_pb::connector_service::{PbSinkParam, SinkMetadata, TableSchema};
99use risingwave_pb::id::ExecutorId;
100use risingwave_rpc_client::MetaClient;
101use risingwave_rpc_client::error::RpcError;
102use starrocks::STARROCKS_SINK;
103use thiserror::Error;
104use thiserror_ext::AsReport;
105use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
106pub use tracing;
107
108use self::catalog::{SinkFormatDesc, SinkType};
109use self::clickhouse::CLICKHOUSE_SINK;
110use self::deltalake::DELTALAKE_SINK;
111use self::iceberg::ICEBERG_SINK;
112use self::lancedb::LANCEDB_SINK;
113use self::mock_coordination_client::{MockMetaClient, SinkCoordinationRpcClientEnum};
114use crate::connector_common::IcebergSinkCompactionUpdate;
115use crate::error::{ConnectorError, ConnectorResult};
116use crate::sink::boxed::{BoxSinglePhaseCoordinator, BoxTwoPhaseCoordinator};
117use crate::sink::catalog::desc::SinkDesc;
118use crate::sink::catalog::{SinkCatalog, SinkId};
119use crate::sink::decouple_checkpoint_log_sink::ICEBERG_DEFAULT_COMMIT_CHECKPOINT_INTERVAL;
120use crate::sink::file_sink::fs::FsSink;
121use crate::sink::log_store::{LogReader, LogStoreReadItem, LogStoreResult, TruncateOffset};
122use crate::sink::snowflake_redshift::snowflake::SNOWFLAKE_SINK_V2;
123use crate::sink::utils::feature_gated_sink_mod;
124use crate::{WithPropertiesExt, connector_metrics_level};
125
126const BOUNDED_CHANNEL_SIZE: usize = 16;
127#[macro_export]
128macro_rules! for_all_sinks {
129 ($macro:path $(, $arg:tt)*) => {
130 $macro! {
131 {
132 { Redis, $crate::sink::redis::RedisSink, $crate::sink::redis::RedisConfig },
133 { Kafka, $crate::sink::kafka::KafkaSink, $crate::sink::kafka::KafkaConfig },
134 { Pulsar, $crate::sink::pulsar::PulsarSink, $crate::sink::pulsar::PulsarConfig },
135 { BlackHole, $crate::sink::trivial::BlackHoleSink, () },
136 { Http, $crate::sink::http::HttpSink, $crate::sink::http::HttpConfig },
137 { Turbopuffer, $crate::sink::turbopuffer::TurbopufferSink, $crate::sink::turbopuffer::TurbopufferConfig },
138 { Kinesis, $crate::sink::kinesis::KinesisSink, $crate::sink::kinesis::KinesisSinkConfig },
139 { ClickHouse, $crate::sink::clickhouse::ClickHouseSink, $crate::sink::clickhouse::ClickHouseConfig },
140 { Iceberg, $crate::sink::iceberg::IcebergSink, $crate::sink::iceberg::IcebergConfig },
141 { Mqtt, $crate::sink::mqtt::MqttSink, $crate::sink::mqtt::MqttConfig },
142 { GooglePubSub, $crate::sink::google_pubsub::GooglePubSubSink, $crate::sink::google_pubsub::GooglePubSubConfig },
143 { Nats, $crate::sink::nats::NatsSink, $crate::sink::nats::NatsConfig },
144 { Jdbc, $crate::sink::remote::JdbcSink, () },
145 { ElasticSearch, $crate::sink::elasticsearch_opensearch::elasticsearch::ElasticSearchSink, $crate::sink::elasticsearch_opensearch::elasticsearch_opensearch_config::ElasticSearchConfig },
146 { Opensearch, $crate::sink::elasticsearch_opensearch::opensearch::OpenSearchSink, $crate::sink::elasticsearch_opensearch::elasticsearch_opensearch_config::OpenSearchConfig },
147 { Cassandra, $crate::sink::remote::CassandraSink, () },
148 { Doris, $crate::sink::doris::DorisSink, $crate::sink::doris::DorisConfig },
149 { Starrocks, $crate::sink::starrocks::StarrocksSink, $crate::sink::starrocks::StarrocksConfig },
150 { S3, $crate::sink::file_sink::opendal_sink::FileSink<$crate::sink::file_sink::s3::S3Sink>, $crate::sink::file_sink::s3::S3Config },
151
152 { Gcs, $crate::sink::file_sink::opendal_sink::FileSink<$crate::sink::file_sink::gcs::GcsSink>, $crate::sink::file_sink::gcs::GcsConfig },
153 { Azblob, $crate::sink::file_sink::opendal_sink::FileSink<$crate::sink::file_sink::azblob::AzblobSink>, $crate::sink::file_sink::azblob::AzblobConfig },
154 { Webhdfs, $crate::sink::file_sink::opendal_sink::FileSink<$crate::sink::file_sink::webhdfs::WebhdfsSink>, $crate::sink::file_sink::webhdfs::WebhdfsConfig },
155
156 { Fs, $crate::sink::file_sink::opendal_sink::FileSink<FsSink>, $crate::sink::file_sink::fs::FsConfig },
157 { SnowflakeV2, $crate::sink::snowflake_redshift::snowflake::SnowflakeV2Sink, $crate::sink::snowflake_redshift::snowflake::SnowflakeV2Config },
158 { Snowflake, $crate::sink::file_sink::opendal_sink::FileSink<$crate::sink::file_sink::s3::SnowflakeSink>, $crate::sink::file_sink::s3::SnowflakeConfig },
159 { RedShift, $crate::sink::snowflake_redshift::redshift::RedshiftSink, $crate::sink::snowflake_redshift::redshift::RedShiftConfig },
160 { DeltaLake, $crate::sink::deltalake::DeltaLakeSink, $crate::sink::deltalake::DeltaLakeConfig },
161 { LanceDb, $crate::sink::lancedb::LanceDbSink, $crate::sink::lancedb::LanceDbConfig },
162 { BigQuery, $crate::sink::big_query::BigQuerySink, $crate::sink::big_query::BigQueryConfig },
163 { DynamoDb, $crate::sink::dynamodb::DynamoDbSink, $crate::sink::dynamodb::DynamoDbConfig },
164 { Firestore, $crate::sink::firestore::FirestoreSink, $crate::sink::firestore::FirestoreConfig },
165 { Mongodb, $crate::sink::mongodb::MongodbSink, $crate::sink::mongodb::MongodbConfig },
166 { SqlServer, $crate::sink::sqlserver::SqlServerSink, $crate::sink::sqlserver::SqlServerConfig },
167 { Postgres, $crate::sink::postgres::PostgresSink, $crate::sink::postgres::PostgresConfig },
168
169 { Test, $crate::sink::test_sink::TestSink, () },
170 { Table, $crate::sink::trivial::TableSink, () }
171 }
172 $(,$arg)*
173 }
174 };
175}
176
177#[macro_export]
178macro_rules! generate_config_use_clauses {
179 ({$({ $variant_name:ident, $sink_type:ty, $($config_type:tt)+ }), *}) => {
180 $(
181 $crate::generate_config_use_single! { $($config_type)+ }
182 )*
183 };
184}
185
186#[macro_export]
187macro_rules! generate_config_use_single {
188 (()) => {};
190
191 ($config_type:path) => {
193 #[allow(unused_imports)]
194 pub(super) use $config_type;
195 };
196}
197
198#[macro_export]
200macro_rules! use_all_sink_configs {
201 () => {
202 $crate::for_all_sinks! { $crate::generate_config_use_clauses }
203 };
204}
205
206#[macro_export]
207macro_rules! dispatch_sink {
208 ({$({$variant_name:ident, $sink_type:ty, $config_type:ty}),*}, $impl:tt, $sink:tt, $body:tt) => {{
209 use $crate::sink::SinkImpl;
210
211 match $impl {
212 $(
213 SinkImpl::$variant_name($sink) => $body,
214 )*
215 }
216 }};
217 ($impl:expr, $sink:ident, $body:expr) => {{
218 $crate::for_all_sinks! {$crate::dispatch_sink, {$impl}, $sink, {$body}}
219 }};
220}
221
222#[macro_export]
223macro_rules! match_sink_name_str {
224 ({$({$variant_name:ident, $sink_type:ty, $config_type:ty}),*}, $name_str:tt, $type_name:ident, $body:tt, $on_other_closure:tt) => {{
225 use $crate::sink::Sink;
226 match $name_str {
227 $(
228 <$sink_type>::SINK_NAME => {
229 type $type_name = $sink_type;
230 {
231 $body
232 }
233 },
234 )*
235 other => ($on_other_closure)(other),
236 }
237 }};
238 ($name_str:expr, $type_name:ident, $body:expr, $on_other_closure:expr) => {{
239 $crate::for_all_sinks! {$crate::match_sink_name_str, {$name_str}, $type_name, {$body}, {$on_other_closure}}
240 }};
241}
242
243pub const CONNECTOR_TYPE_KEY: &str = "connector";
244pub const SINK_TYPE_OPTION: &str = "type";
245pub const SINK_SNAPSHOT_OPTION: &str = "snapshot";
247pub const SINK_TYPE_APPEND_ONLY: &str = "append-only";
248pub const SINK_TYPE_DEBEZIUM: &str = "debezium";
249pub const SINK_TYPE_UPSERT: &str = "upsert";
250pub const SINK_TYPE_RETRACT: &str = "retract";
251pub const SINK_USER_IGNORE_DELETE_OPTION: &str = "ignore_delete";
253pub const SINK_USER_FORCE_APPEND_ONLY_OPTION: &str = "force_append_only";
255pub const SINK_USER_FORCE_COMPACTION: &str = "force_compaction";
256pub const SINK_USER_PRESERVE_ROW_LEVEL_CHANGES: &str = "preserve_row_level_changes";
260
261pub fn sink_is_exactly_once(properties: &BTreeMap<String, String>) -> Result<bool> {
266 let sink_type = properties
267 .get(CONNECTOR_TYPE_KEY)
268 .ok_or_else(|| SinkError::Config(anyhow!("missing config: {}", CONNECTOR_TYPE_KEY)))?
269 .to_lowercase();
270
271 match_sink_name_str!(
272 sink_type.as_str(),
273 SinkType,
274 SinkType::is_exactly_once(properties),
275 |other| Err(SinkError::Config(anyhow!(
276 "unsupported sink connector {}",
277 other
278 )))
279 )
280}
281
282pub trait UnknownFields {
283 fn unknown_fields(&self) -> HashMap<String, String>;
285}
286
287impl UnknownFields for () {
288 fn unknown_fields(&self) -> HashMap<String, String> {
289 HashMap::new()
290 }
291}
292
293impl UnknownFields for HashMap<String, String> {
294 fn unknown_fields(&self) -> HashMap<String, String> {
295 self.clone()
296 }
297}
298
299#[macro_export]
300macro_rules! impl_sink_unknown_fields {
301 ($config_type:ty) => {
302 impl $crate::sink::UnknownFields for $config_type {
303 fn unknown_fields(&self) -> std::collections::HashMap<String, String> {
304 self.unknown_fields.clone()
305 }
306 }
307 };
308}
309
310#[macro_export]
311macro_rules! impl_validate_sink_unknown_fields {
312 () => {
313 fn validate_unknown_fields(&self) -> $crate::sink::Result<()> {
314 $crate::sink::validate_sink_unknown_fields(&self.config)
315 }
316 };
317}
318
319pub fn validate_sink_unknown_fields(config: &impl UnknownFields) -> Result<()> {
320 let mut unknown_fields = config.unknown_fields();
321 for key in [
324 CONNECTOR_TYPE_KEY,
325 SINK_TYPE_OPTION,
326 SINK_SNAPSHOT_OPTION,
327 SINK_USER_IGNORE_DELETE_OPTION,
328 SINK_USER_FORCE_APPEND_ONLY_OPTION,
329 SINK_USER_FORCE_COMPACTION,
330 SINK_USER_PRESERVE_ROW_LEVEL_CHANGES,
331 "backfill_rate_limit",
332 "primary_key",
333 "sink_rate_limit",
334 ] {
335 unknown_fields.remove(key);
336 }
337 if unknown_fields.is_empty() {
338 Ok(())
339 } else {
340 Err(SinkError::Config(anyhow!(
341 "Unknown fields in the WITH clause: {:?}",
342 unknown_fields
343 )))
344 }
345}
346
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct SinkParam {
349 pub sink_id: SinkId,
350 pub sink_name: String,
351 pub properties: BTreeMap<String, String>,
352 pub columns: Vec<ColumnDesc>,
353 pub downstream_pk: Option<Vec<usize>>,
355 pub sink_type: SinkType,
356 pub ignore_delete: bool,
358 pub format_desc: Option<SinkFormatDesc>,
359 pub db_name: String,
360
361 pub sink_from_name: String,
367}
368
369impl SinkParam {
370 pub fn from_proto(pb_param: PbSinkParam) -> Self {
371 let ignore_delete = pb_param.ignore_delete();
372 let table_schema = pb_param.table_schema.expect("should contain table schema");
373 let format_desc = match pb_param.format_desc {
374 Some(f) => f.try_into().ok(),
375 None => {
376 let connector = pb_param.properties.get(CONNECTOR_TYPE_KEY);
377 let r#type = pb_param.properties.get(SINK_TYPE_OPTION);
378 match (connector, r#type) {
379 (Some(c), Some(t)) => SinkFormatDesc::from_legacy_type(c, t).ok().flatten(),
380 _ => None,
381 }
382 }
383 };
384 Self {
385 sink_id: SinkId::from(pb_param.sink_id),
386 sink_name: pb_param.sink_name,
387 properties: pb_param.properties,
388 columns: table_schema.columns.iter().map(ColumnDesc::from).collect(),
389 downstream_pk: if table_schema.pk_indices.is_empty() {
390 None
391 } else {
392 Some(
393 (table_schema.pk_indices.iter())
394 .map(|i| *i as usize)
395 .collect(),
396 )
397 },
398 sink_type: SinkType::from_proto(
399 PbSinkType::try_from(pb_param.sink_type).expect("should be able to convert"),
400 ),
401 ignore_delete,
402 format_desc,
403 db_name: pb_param.db_name,
404 sink_from_name: pb_param.sink_from_name,
405 }
406 }
407
408 pub fn to_proto(&self) -> PbSinkParam {
409 PbSinkParam {
410 sink_id: self.sink_id,
411 sink_name: self.sink_name.clone(),
412 properties: self.properties.clone(),
413 table_schema: Some(TableSchema {
414 columns: self.columns.iter().map(|col| col.to_protobuf()).collect(),
415 pk_indices: (self.downstream_pk.as_ref())
416 .map_or_else(Vec::new, |pk| pk.iter().map(|i| *i as u32).collect()),
417 }),
418 sink_type: self.sink_type.to_proto().into(),
419 format_desc: self.format_desc.as_ref().map(|f| f.to_proto()),
420 db_name: self.db_name.clone(),
421 sink_from_name: self.sink_from_name.clone(),
422 raw_ignore_delete: self.ignore_delete,
423 }
424 }
425
426 pub fn schema(&self) -> Schema {
427 Schema {
428 fields: self.columns.iter().map(Field::from).collect(),
429 }
430 }
431
432 pub fn downstream_pk_or_empty(&self) -> Vec<usize> {
438 self.downstream_pk.clone().unwrap_or_default()
439 }
440
441 pub fn fill_secret_for_format_desc(
444 format_desc: Option<SinkFormatDesc>,
445 ) -> Result<Option<SinkFormatDesc>> {
446 match format_desc {
447 Some(mut format_desc) => {
448 format_desc.options = LocalSecretManager::global()
449 .fill_secrets(format_desc.options, format_desc.secret_refs.clone())?;
450 Ok(Some(format_desc))
451 }
452 None => Ok(None),
453 }
454 }
455
456 pub fn try_from_sink_catalog(sink_catalog: SinkCatalog) -> Result<Self> {
458 let columns = sink_catalog
459 .visible_columns()
460 .map(|col| col.column_desc.clone())
461 .collect();
462 let properties_with_secret = LocalSecretManager::global()
463 .fill_secrets(sink_catalog.properties, sink_catalog.secret_refs)?;
464 let format_desc_with_secret = Self::fill_secret_for_format_desc(sink_catalog.format_desc)?;
465 Ok(Self {
466 sink_id: sink_catalog.id,
467 sink_name: sink_catalog.name,
468 properties: properties_with_secret,
469 columns,
470 downstream_pk: sink_catalog.downstream_pk,
471 sink_type: sink_catalog.sink_type,
472 ignore_delete: sink_catalog.ignore_delete,
473 format_desc: format_desc_with_secret,
474 db_name: sink_catalog.db_name,
475 sink_from_name: sink_catalog.sink_from_name,
476 })
477 }
478}
479
480pub fn enforce_secret_sink(props: &impl WithPropertiesExt) -> ConnectorResult<()> {
481 use crate::enforce_secret::EnforceSecret;
482
483 let connector = props
484 .get_connector()
485 .ok_or_else(|| anyhow!("Must specify 'connector' in WITH clause"))?;
486 let key_iter = props.key_iter();
487 match_sink_name_str!(
488 connector.as_str(),
489 PropType,
490 PropType::enforce_secret(key_iter),
491 |other| bail!("connector '{}' is not supported", other)
492 )
493}
494
495pub static GLOBAL_SINK_METRICS: LazyLock<SinkMetrics> =
496 LazyLock::new(|| SinkMetrics::new(&GLOBAL_METRICS_REGISTRY, connector_metrics_level()));
497
498#[derive(Clone)]
499pub struct SinkMetrics {
500 pub sink_commit_duration: RelabeledGuardedHistogramVec,
501 pub connector_sink_rows_received: RelabeledGuardedIntCounterVec,
502
503 pub log_store_first_write_epoch: RelabeledAggregatedIntGaugeVec,
505 pub log_store_latest_write_epoch: RelabeledAggregatedIntGaugeVec,
506 pub log_store_write_rows: RelabeledGuardedIntCounterVec,
507
508 pub log_store_latest_read_epoch: RelabeledAggregatedIntGaugeVec,
510 pub log_store_read_rows: RelabeledGuardedIntCounterVec,
511 pub log_store_read_bytes: RelabeledGuardedIntCounterVec,
512 pub log_store_reader_wait_new_future_duration_ns: RelabeledGuardedIntCounterVec,
513
514 pub iceberg_write_qps: RelabeledGuardedIntCounterVec,
516 pub iceberg_write_latency: RelabeledGuardedHistogramVec,
517 pub iceberg_rolling_unflushed_data_file: RelabeledAggregatedIntGaugeVec,
518 pub iceberg_position_delete_cache_num: RelabeledAggregatedIntGaugeVec,
519 pub iceberg_partition_num: RelabeledAggregatedIntGaugeVec,
520 pub iceberg_write_bytes: RelabeledGuardedIntCounterVec,
521 pub iceberg_snapshot_num: LabelGuardedIntGaugeVec,
522}
523
524impl SinkMetrics {
525 pub fn new(registry: &Registry, metric_level: MetricLevel) -> Self {
526 let sink_commit_duration = register_guarded_histogram_vec_with_registry!(
527 "sink_commit_duration",
528 "Duration of commit op in sink",
529 &["actor_id", "connector", "sink_id", "sink_name"],
530 registry
531 )
532 .unwrap()
533 .relabel_debug_1(metric_level);
534
535 let connector_sink_rows_received = register_guarded_int_counter_vec_with_registry!(
536 "connector_sink_rows_received",
537 "Number of rows received by sink",
538 &["actor_id", "connector_type", "sink_id", "sink_name"],
539 registry
540 )
541 .unwrap()
542 .relabel_debug_1(metric_level);
543
544 let log_store_first_write_epoch = register_guarded_int_gauge_vec_with_registry!(
545 "log_store_first_write_epoch",
546 "The first write epoch of log store",
547 &["actor_id", "sink_id", "sink_name"],
548 registry
549 )
550 .unwrap()
551 .relabel_debug_1_with_aggregation(metric_level, GaugeAggregation::Min);
552
553 let log_store_latest_write_epoch = register_guarded_int_gauge_vec_with_registry!(
554 "log_store_latest_write_epoch",
555 "The latest write epoch of log store",
556 &["actor_id", "sink_id", "sink_name"],
557 registry
558 )
559 .unwrap()
560 .relabel_debug_1_with_aggregation(metric_level, GaugeAggregation::Min);
561
562 let log_store_write_rows = register_guarded_int_counter_vec_with_registry!(
563 "log_store_write_rows",
564 "The write rate of rows",
565 &["actor_id", "sink_id", "sink_name"],
566 registry
567 )
568 .unwrap()
569 .relabel_debug_1(metric_level);
570
571 let log_store_latest_read_epoch = register_guarded_int_gauge_vec_with_registry!(
572 "log_store_latest_read_epoch",
573 "The latest read epoch of log store",
574 &["actor_id", "connector", "sink_id", "sink_name"],
575 registry
576 )
577 .unwrap()
578 .relabel_debug_1_with_aggregation(metric_level, GaugeAggregation::Min);
579
580 let log_store_read_rows = register_guarded_int_counter_vec_with_registry!(
581 "log_store_read_rows",
582 "The read rate of rows",
583 &["actor_id", "connector", "sink_id", "sink_name"],
584 registry
585 )
586 .unwrap()
587 .relabel_debug_1(metric_level);
588
589 let log_store_read_bytes = register_guarded_int_counter_vec_with_registry!(
590 "log_store_read_bytes",
591 "Total size of chunks read by log reader",
592 &["actor_id", "connector", "sink_id", "sink_name"],
593 registry
594 )
595 .unwrap()
596 .relabel_debug_1(metric_level);
597
598 let log_store_reader_wait_new_future_duration_ns =
599 register_guarded_int_counter_vec_with_registry!(
600 "log_store_reader_wait_new_future_duration_ns",
601 "Accumulated duration of LogReader to wait for next call to create future",
602 &["actor_id", "connector", "sink_id", "sink_name"],
603 registry
604 )
605 .unwrap()
606 .relabel_debug_1(metric_level);
607
608 let iceberg_write_qps = register_guarded_int_counter_vec_with_registry!(
609 "iceberg_write_qps",
610 "The qps of iceberg writer",
611 &["actor_id", "sink_id", "sink_name"],
612 registry
613 )
614 .unwrap()
615 .relabel_debug_1(metric_level);
616
617 let iceberg_write_latency = register_guarded_histogram_vec_with_registry!(
618 "iceberg_write_latency",
619 "The latency of iceberg writer",
620 &["actor_id", "sink_id", "sink_name"],
621 registry
622 )
623 .unwrap()
624 .relabel_debug_1(metric_level);
625
626 let iceberg_rolling_unflushed_data_file = register_guarded_int_gauge_vec_with_registry!(
627 "iceberg_rolling_unflushed_data_file",
628 "The unflushed data file count of iceberg rolling writer",
629 &["actor_id", "sink_id", "sink_name"],
630 registry
631 )
632 .unwrap()
633 .relabel_debug_1_with_aggregation(metric_level, GaugeAggregation::Sum);
634
635 let iceberg_position_delete_cache_num = register_guarded_int_gauge_vec_with_registry!(
636 "iceberg_position_delete_cache_num",
637 "The delete cache num of iceberg position delete writer",
638 &["actor_id", "sink_id", "sink_name"],
639 registry
640 )
641 .unwrap()
642 .relabel_debug_1_with_aggregation(metric_level, GaugeAggregation::Sum);
643
644 let iceberg_partition_num = register_guarded_int_gauge_vec_with_registry!(
645 "iceberg_partition_num",
646 "The partition num of iceberg partition writer",
647 &["actor_id", "sink_id", "sink_name"],
648 registry
649 )
650 .unwrap()
651 .relabel_debug_1_with_aggregation(metric_level, GaugeAggregation::Sum);
652
653 let iceberg_write_bytes = register_guarded_int_counter_vec_with_registry!(
654 "iceberg_write_bytes",
655 "The write bytes of iceberg writer",
656 &["actor_id", "sink_id", "sink_name"],
657 registry
658 )
659 .unwrap()
660 .relabel_debug_1(metric_level);
661
662 let iceberg_snapshot_num = register_guarded_int_gauge_vec_with_registry!(
663 "iceberg_snapshot_num",
664 "The snapshot number of iceberg table",
665 &["sink_name", "catalog_name", "table_name"],
666 registry
667 )
668 .unwrap();
669
670 Self {
671 sink_commit_duration,
672 connector_sink_rows_received,
673 log_store_first_write_epoch,
674 log_store_latest_write_epoch,
675 log_store_write_rows,
676 log_store_latest_read_epoch,
677 log_store_read_rows,
678 log_store_read_bytes,
679 log_store_reader_wait_new_future_duration_ns,
680 iceberg_write_qps,
681 iceberg_write_latency,
682 iceberg_rolling_unflushed_data_file,
683 iceberg_position_delete_cache_num,
684 iceberg_partition_num,
685 iceberg_write_bytes,
686 iceberg_snapshot_num,
687 }
688 }
689}
690
691#[derive(Clone)]
692pub struct SinkWriterParam {
693 pub executor_id: ExecutorId,
695 pub vnode_bitmap: Bitmap,
696 pub meta_client: Option<SinkMetaClient>,
697 pub extra_partition_col_idx: Option<usize>,
702
703 pub actor_id: ActorId,
704 pub sink_id: SinkId,
705 pub sink_name: String,
706 pub connector: String,
707 pub streaming_config: StreamingConfig,
708 pub time_zone: Tz,
709}
710
711#[derive(Clone)]
712pub struct SinkWriterMetrics {
713 pub sink_commit_duration: LabelGuardedHistogram,
714 pub connector_sink_rows_received: LabelGuardedIntCounter,
715}
716
717impl SinkWriterMetrics {
718 pub fn new(writer_param: &SinkWriterParam) -> Self {
719 let labels = [
720 &writer_param.actor_id.to_string(),
721 writer_param.connector.as_str(),
722 &writer_param.sink_id.to_string(),
723 writer_param.sink_name.as_str(),
724 ];
725 let sink_commit_duration = GLOBAL_SINK_METRICS
726 .sink_commit_duration
727 .with_guarded_label_values(&labels);
728 let connector_sink_rows_received = GLOBAL_SINK_METRICS
729 .connector_sink_rows_received
730 .with_guarded_label_values(&labels);
731 Self {
732 sink_commit_duration,
733 connector_sink_rows_received,
734 }
735 }
736
737 #[cfg(test)]
738 pub fn for_test() -> Self {
739 Self {
740 sink_commit_duration: LabelGuardedHistogram::test_histogram::<4>(),
741 connector_sink_rows_received: LabelGuardedIntCounter::test_int_counter::<4>(),
742 }
743 }
744}
745
746#[derive(Clone)]
747pub enum SinkMetaClient {
748 MetaClient(MetaClient),
749 MockMetaClient(MockMetaClient),
750}
751
752impl SinkMetaClient {
753 pub async fn sink_coordinate_client(&self) -> SinkCoordinationRpcClientEnum {
754 match self {
755 SinkMetaClient::MetaClient(meta_client) => {
756 SinkCoordinationRpcClientEnum::SinkCoordinationRpcClient(
757 meta_client.sink_coordinate_client().await,
758 )
759 }
760 SinkMetaClient::MockMetaClient(mock_meta_client) => {
761 SinkCoordinationRpcClientEnum::MockSinkCoordinationRpcClient(
762 mock_meta_client.sink_coordinate_client(),
763 )
764 }
765 }
766 }
767
768 pub async fn add_sink_fail_evet_log(
769 &self,
770 sink_id: SinkId,
771 sink_name: String,
772 connector: String,
773 error: String,
774 ) {
775 match self {
776 SinkMetaClient::MetaClient(meta_client) => {
777 match meta_client
778 .add_sink_fail_evet(sink_id, sink_name, connector, error)
779 .await
780 {
781 Ok(_) => {}
782 Err(e) => {
783 tracing::warn!(
784 error = %e.as_report(),
785 %sink_id,
786 "failed to add the sink failure event to the event log",
787 );
788 }
789 }
790 }
791 SinkMetaClient::MockMetaClient(_) => {}
792 }
793 }
794}
795
796impl SinkWriterParam {
797 pub fn for_test() -> Self {
798 SinkWriterParam {
799 executor_id: Default::default(),
800 vnode_bitmap: Bitmap::singleton().clone(),
801 meta_client: Default::default(),
802 extra_partition_col_idx: Default::default(),
803
804 actor_id: 1.into(),
805 sink_id: SinkId::new(1),
806 sink_name: "test_sink".to_owned(),
807 connector: "test_connector".to_owned(),
808 streaming_config: StreamingConfig::default(),
809 time_zone: UTC,
810 }
811 }
812}
813
814fn is_sink_support_commit_checkpoint_interval(sink_name: &str) -> bool {
815 matches!(
816 sink_name,
817 ICEBERG_SINK
818 | CLICKHOUSE_SINK
819 | STARROCKS_SINK
820 | DELTALAKE_SINK
821 | SNOWFLAKE_SINK_V2
822 | LANCEDB_SINK
823 )
824}
825pub trait Sink: TryFrom<SinkParam, Error = SinkError> {
826 const SINK_NAME: &'static str;
827
828 type LogSinker: LogSinker;
829
830 fn is_exactly_once(_properties: &BTreeMap<String, String>) -> Result<bool> {
832 Ok(false)
833 }
834
835 fn set_default_commit_checkpoint_interval(
836 desc: &mut SinkDesc,
837 user_specified: &SinkDecouple,
838 ) -> Result<()> {
839 if is_sink_support_commit_checkpoint_interval(Self::SINK_NAME) {
840 match desc.properties.get(COMMIT_CHECKPOINT_INTERVAL) {
841 Some(commit_checkpoint_interval) => {
842 let commit_checkpoint_interval = commit_checkpoint_interval
843 .parse::<u64>()
844 .map_err(|e| SinkError::Config(anyhow!(e)))?;
845 if matches!(user_specified, SinkDecouple::Disable)
846 && commit_checkpoint_interval > 1
847 {
848 return Err(SinkError::Config(anyhow!(
849 "config conflict: `commit_checkpoint_interval` larger than 1 means that sink decouple must be enabled, but session config sink_decouple is disabled"
850 )));
851 }
852 }
853 None => match user_specified {
854 SinkDecouple::Default | SinkDecouple::Enable => {
855 if matches!(Self::SINK_NAME, ICEBERG_SINK) {
856 desc.properties.insert(
857 COMMIT_CHECKPOINT_INTERVAL.to_owned(),
858 ICEBERG_DEFAULT_COMMIT_CHECKPOINT_INTERVAL.to_string(),
859 );
860 } else {
861 desc.properties.insert(
862 COMMIT_CHECKPOINT_INTERVAL.to_owned(),
863 DEFAULT_COMMIT_CHECKPOINT_INTERVAL_WITH_SINK_DECOUPLE.to_string(),
864 );
865 }
866 }
867 SinkDecouple::Disable => {
868 desc.properties.insert(
869 COMMIT_CHECKPOINT_INTERVAL.to_owned(),
870 DEFAULT_COMMIT_CHECKPOINT_INTERVAL_WITHOUT_SINK_DECOUPLE.to_string(),
871 );
872 }
873 },
874 }
875 }
876 Ok(())
877 }
878
879 fn is_sink_decouple(user_specified: &SinkDecouple) -> Result<bool> {
881 match user_specified {
882 SinkDecouple::Default | SinkDecouple::Enable => Ok(true),
883 SinkDecouple::Disable => Ok(false),
884 }
885 }
886
887 fn support_schema_change() -> bool {
888 false
889 }
890
891 fn validate_alter_config_change(
896 config: &BTreeMap<String, String>,
897 _alter_props: &BTreeMap<String, String>,
898 ) -> Result<()> {
899 Self::validate_alter_config(config)
900 }
901
902 fn validate_alter_config(_config: &BTreeMap<String, String>) -> Result<()> {
903 Ok(())
904 }
905
906 fn validate_unknown_fields(&self) -> Result<()> {
907 Ok(())
908 }
909
910 async fn validate(&self) -> Result<()>;
911 async fn new_log_sinker(&self, writer_param: SinkWriterParam) -> Result<Self::LogSinker>;
912
913 fn is_coordinated_sink(&self) -> bool {
914 false
915 }
916
917 async fn new_coordinator(
918 &self,
919 _iceberg_compact_stat_sender: Option<UnboundedSender<IcebergSinkCompactionUpdate>>,
920 ) -> Result<SinkCommitCoordinator> {
921 Err(SinkError::Coordinator(anyhow!("no coordinator")))
922 }
923}
924
925pub trait SinkLogReader: Send {
926 fn start_from(
927 &mut self,
928 start_offset: Option<u64>,
929 ) -> impl Future<Output = LogStoreResult<()>> + Send + '_;
930 fn next_item(
934 &mut self,
935 ) -> impl Future<Output = LogStoreResult<(u64, LogStoreReadItem)>> + Send + '_;
936
937 fn truncate(&mut self, offset: TruncateOffset) -> LogStoreResult<()>;
940}
941
942impl<R: LogReader> SinkLogReader for &mut R {
943 fn next_item(
944 &mut self,
945 ) -> impl Future<Output = LogStoreResult<(u64, LogStoreReadItem)>> + Send + '_ {
946 <R as LogReader>::next_item(*self)
947 }
948
949 fn truncate(&mut self, offset: TruncateOffset) -> LogStoreResult<()> {
950 <R as LogReader>::truncate(*self, offset)
951 }
952
953 fn start_from(
954 &mut self,
955 start_offset: Option<u64>,
956 ) -> impl Future<Output = LogStoreResult<()>> + Send + '_ {
957 <R as LogReader>::start_from(*self, start_offset)
958 }
959}
960
961#[async_trait]
962pub trait LogSinker: 'static + Send {
963 async fn consume_log_and_sink(self, log_reader: impl SinkLogReader) -> Result<!>;
965}
966pub type SinkCommittedEpochSubscriber = Arc<
967 dyn Fn(SinkId) -> BoxFuture<'static, Result<(u64, UnboundedReceiver<u64>)>>
968 + Send
969 + Sync
970 + 'static,
971>;
972
973pub enum SinkCommitCoordinator {
974 SinglePhase(BoxSinglePhaseCoordinator),
975 TwoPhase(BoxTwoPhaseCoordinator),
976}
977
978#[async_trait]
979pub trait SinglePhaseCommitCoordinator {
980 async fn init(&mut self) -> Result<()>;
982
983 async fn commit_data(&mut self, epoch: u64, metadata: Vec<SinkMetadata>) -> Result<()>;
985
986 async fn commit_schema_change(
989 &mut self,
990 _epoch: u64,
991 _schema_change: PbSinkSchemaChange,
992 ) -> Result<()> {
993 Err(SinkError::Coordinator(anyhow!(
994 "Schema change is not implemented for single-phase commit coordinator {}",
995 std::any::type_name::<Self>()
996 )))
997 }
998}
999
1000#[async_trait]
1001pub trait TwoPhaseCommitCoordinator {
1002 async fn init(&mut self) -> Result<()>;
1004
1005 async fn pre_commit(
1007 &mut self,
1008 epoch: u64,
1009 metadata: Vec<SinkMetadata>,
1010 schema_change: Option<PbSinkSchemaChange>,
1011 ) -> Result<Option<Vec<u8>>>;
1012
1013 async fn commit_data(&mut self, epoch: u64, commit_metadata: Vec<u8>) -> Result<()>;
1015
1016 async fn commit_schema_change(
1019 &mut self,
1020 _epoch: u64,
1021 _schema_change: PbSinkSchemaChange,
1022 ) -> Result<()> {
1023 Err(SinkError::Coordinator(anyhow!(
1024 "Schema change is not implemented for two-phase commit coordinator {}",
1025 std::any::type_name::<Self>()
1026 )))
1027 }
1028
1029 async fn abort(&mut self, epoch: u64, commit_metadata: Vec<u8>);
1031}
1032
1033impl SinkImpl {
1034 pub fn new(mut param: SinkParam) -> Result<Self> {
1035 const PRIVATE_LINK_TARGET_KEY: &str = "privatelink.targets";
1036
1037 param.properties.remove(PRIVATE_LINK_TARGET_KEY);
1039
1040 let sink_type = param
1041 .properties
1042 .get(CONNECTOR_TYPE_KEY)
1043 .ok_or_else(|| SinkError::Config(anyhow!("missing config: {}", CONNECTOR_TYPE_KEY)))?;
1044
1045 let sink_type = sink_type.to_lowercase();
1046 match_sink_name_str!(
1047 sink_type.as_str(),
1048 SinkType,
1049 Ok(SinkType::try_from(param)?.into()),
1050 |other| {
1051 Err(SinkError::Config(anyhow!(
1052 "unsupported sink connector {}",
1053 other
1054 )))
1055 }
1056 )
1057 }
1058
1059 pub fn is_sink_into_table(&self) -> bool {
1060 matches!(self, SinkImpl::Table(_))
1061 }
1062
1063 pub fn is_blackhole(&self) -> bool {
1064 matches!(self, SinkImpl::BlackHole(_))
1065 }
1066
1067 pub fn is_coordinated_sink(&self) -> bool {
1068 dispatch_sink!(self, sink, sink.is_coordinated_sink())
1069 }
1070
1071 pub fn validate_unknown_fields(&self) -> Result<()> {
1072 dispatch_sink!(self, sink, sink.validate_unknown_fields())
1073 }
1074}
1075
1076pub fn build_sink(param: SinkParam) -> Result<SinkImpl> {
1077 SinkImpl::new(param)
1078}
1079
1080macro_rules! def_sink_impl {
1081 () => {
1082 $crate::for_all_sinks! { def_sink_impl }
1083 };
1084 ({ $({ $variant_name:ident, $sink_type:ty, $config_type:ty }),* }) => {
1085 #[derive(Debug)]
1086 pub enum SinkImpl {
1087 $(
1088 $variant_name(Box<$sink_type>),
1089 )*
1090 }
1091
1092 $(
1093 impl From<$sink_type> for SinkImpl {
1094 fn from(sink: $sink_type) -> SinkImpl {
1095 SinkImpl::$variant_name(Box::new(sink))
1096 }
1097 }
1098 )*
1099 };
1100}
1101
1102def_sink_impl!();
1103
1104pub type Result<T> = std::result::Result<T, SinkError>;
1105
1106#[derive(Error, Debug)]
1107pub enum SinkError {
1108 #[error("Kafka error: {0}")]
1109 Kafka(#[from] rdkafka::error::KafkaError),
1110 #[error("Kinesis error: {0}")]
1111 Kinesis(
1112 #[source]
1113 #[backtrace]
1114 anyhow::Error,
1115 ),
1116 #[error("Remote sink error: {0}")]
1117 Remote(
1118 #[source]
1119 #[backtrace]
1120 anyhow::Error,
1121 ),
1122 #[error("Encode error: {0}")]
1123 Encode(String),
1124 #[error("Avro error: {0}")]
1125 Avro(#[from] apache_avro::Error),
1126 #[error("Iceberg error: {0}")]
1127 Iceberg(
1128 #[source]
1129 #[backtrace]
1130 anyhow::Error,
1131 ),
1132 #[error("config error: {0}")]
1133 Config(
1134 #[source]
1135 #[backtrace]
1136 anyhow::Error,
1137 ),
1138 #[error("coordinator error: {0}")]
1139 Coordinator(
1140 #[source]
1141 #[backtrace]
1142 anyhow::Error,
1143 ),
1144 #[error("ClickHouse error: {0}")]
1145 ClickHouse(String),
1146 #[error("Redis error: {0}")]
1147 Redis(String),
1148 #[error("Http error: {0}")]
1149 Http(
1150 #[source]
1151 #[backtrace]
1152 anyhow::Error,
1153 ),
1154 #[error("Mqtt error: {0}")]
1155 Mqtt(
1156 #[source]
1157 #[backtrace]
1158 anyhow::Error,
1159 ),
1160 #[error("Nats error: {0}")]
1161 Nats(
1162 #[source]
1163 #[backtrace]
1164 anyhow::Error,
1165 ),
1166 #[error("Google Pub/Sub error: {0}")]
1167 GooglePubSub(
1168 #[source]
1169 #[backtrace]
1170 anyhow::Error,
1171 ),
1172 #[error("Doris/Starrocks connect error: {0}")]
1173 DorisStarrocksConnect(
1174 #[source]
1175 #[backtrace]
1176 anyhow::Error,
1177 ),
1178 #[error("Doris error: {0}")]
1179 Doris(String),
1180 #[error("DeltaLake error: {0}")]
1181 DeltaLake(
1182 #[source]
1183 #[backtrace]
1184 anyhow::Error,
1185 ),
1186 #[error("LanceDB error: {0}")]
1187 LanceDb(
1188 #[source]
1189 #[backtrace]
1190 anyhow::Error,
1191 ),
1192 #[error("ElasticSearch/OpenSearch error: {0}")]
1193 ElasticSearchOpenSearch(
1194 #[source]
1195 #[backtrace]
1196 anyhow::Error,
1197 ),
1198 #[error("Starrocks error: {0}")]
1199 Starrocks(String),
1200 #[error("File error: {0}")]
1201 File(String),
1202 #[error("Pulsar error: {0}")]
1203 Pulsar(
1204 #[source]
1205 #[backtrace]
1206 anyhow::Error,
1207 ),
1208 #[error(transparent)]
1209 Internal(
1210 #[from]
1211 #[backtrace]
1212 anyhow::Error,
1213 ),
1214 #[error("BigQuery error: {0}")]
1215 BigQuery(
1216 #[source]
1217 #[backtrace]
1218 anyhow::Error,
1219 ),
1220 #[error("DynamoDB error: {0}")]
1221 DynamoDb(
1222 #[source]
1223 #[backtrace]
1224 anyhow::Error,
1225 ),
1226 #[error("Firestore error: {0}")]
1227 Firestore(
1228 #[source]
1229 #[backtrace]
1230 anyhow::Error,
1231 ),
1232 #[error("SQL Server error: {0}")]
1233 SqlServer(
1234 #[source]
1235 #[backtrace]
1236 anyhow::Error,
1237 ),
1238 #[error("Postgres error: {0}")]
1239 Postgres(
1240 #[source]
1241 #[backtrace]
1242 anyhow::Error,
1243 ),
1244 #[error(transparent)]
1245 Connector(
1246 #[from]
1247 #[backtrace]
1248 ConnectorError,
1249 ),
1250 #[error("Secret error: {0}")]
1251 Secret(
1252 #[from]
1253 #[backtrace]
1254 SecretError,
1255 ),
1256 #[error("Mongodb error: {0}")]
1257 Mongodb(
1258 #[source]
1259 #[backtrace]
1260 anyhow::Error,
1261 ),
1262 #[error("Redshift error: {0}")]
1263 Redshift(
1264 #[source]
1265 #[backtrace]
1266 anyhow::Error,
1267 ),
1268}
1269
1270#[allow(clippy::disallowed_types)]
1271impl From<::iceberg::Error> for SinkError {
1272 fn from(err: ::iceberg::Error) -> Self {
1273 SinkError::Iceberg(anyhow!(err))
1274 }
1275}
1276
1277impl From<sea_orm::DbErr> for SinkError {
1278 fn from(err: sea_orm::DbErr) -> Self {
1279 SinkError::Iceberg(anyhow!(err))
1280 }
1281}
1282
1283impl From<OpendalError> for SinkError {
1284 fn from(error: OpendalError) -> Self {
1285 SinkError::File(error.to_report_string())
1286 }
1287}
1288
1289impl From<parquet::errors::ParquetError> for SinkError {
1290 fn from(error: parquet::errors::ParquetError) -> Self {
1291 SinkError::File(error.to_report_string())
1292 }
1293}
1294
1295impl From<ArrayError> for SinkError {
1296 fn from(error: ArrayError) -> Self {
1297 SinkError::File(error.to_report_string())
1298 }
1299}
1300
1301impl From<RpcError> for SinkError {
1302 fn from(value: RpcError) -> Self {
1303 SinkError::Remote(anyhow!(value))
1304 }
1305}
1306
1307impl From<RedisError> for SinkError {
1308 fn from(value: RedisError) -> Self {
1309 SinkError::Redis(value.to_report_string())
1310 }
1311}
1312
1313impl From<tiberius::error::Error> for SinkError {
1314 fn from(err: tiberius::error::Error) -> Self {
1315 SinkError::SqlServer(anyhow!(err))
1316 }
1317}
1318
1319impl From<::elasticsearch::Error> for SinkError {
1320 fn from(err: ::elasticsearch::Error) -> Self {
1321 SinkError::ElasticSearchOpenSearch(anyhow!(err))
1322 }
1323}
1324
1325impl From<::opensearch::Error> for SinkError {
1326 fn from(err: ::opensearch::Error) -> Self {
1327 SinkError::ElasticSearchOpenSearch(anyhow!(err))
1328 }
1329}
1330
1331impl From<tokio_postgres::Error> for SinkError {
1332 fn from(err: tokio_postgres::Error) -> Self {
1333 SinkError::Postgres(anyhow!(err))
1334 }
1335}
1336
1337#[cfg(test)]
1338mod tests {
1339 use std::collections::BTreeMap;
1340
1341 use super::*;
1342
1343 fn assert_aggregation(
1344 gauge_vec: &RelabeledAggregatedIntGaugeVec,
1345 first_labels: &[&str],
1346 second_labels: &[&str],
1347 expected: i64,
1348 ) {
1349 let first = gauge_vec.with_guarded_label_values(first_labels);
1350 let second = gauge_vec.with_guarded_label_values(second_labels);
1351 first.set(5);
1352 second.set(7);
1353 assert_eq!(first.get(), expected);
1354 assert_eq!(second.get(), expected);
1355 }
1356
1357 fn btreemap<const N: usize>(entries: [(&str, &str); N]) -> BTreeMap<String, String> {
1358 entries
1359 .into_iter()
1360 .map(|(key, value)| (key.to_owned(), value.to_owned()))
1361 .collect()
1362 }
1363
1364 #[test]
1365 fn test_validate_sink_unknown_fields() {
1366 let config = crate::sink::redis::RedisConfig::from_btreemap(btreemap([
1367 (CONNECTOR_TYPE_KEY, "redis"),
1368 (SINK_TYPE_OPTION, SINK_TYPE_APPEND_ONLY),
1369 ("primary_key", "id"),
1370 (SINK_USER_FORCE_COMPACTION, "true"),
1371 (SINK_USER_PRESERVE_ROW_LEVEL_CHANGES, "true"),
1372 ("redis.url", "redis://127.0.0.1:6379"),
1373 ]))
1374 .unwrap();
1375 validate_sink_unknown_fields(&config).unwrap();
1376
1377 let config = crate::sink::redis::RedisConfig::from_btreemap(btreemap([
1378 (CONNECTOR_TYPE_KEY, "redis"),
1379 (SINK_TYPE_OPTION, SINK_TYPE_APPEND_ONLY),
1380 ("redis.url", "redis://127.0.0.1:6379"),
1381 ("bogus_with", "1"),
1382 ]))
1383 .unwrap();
1384 let err = validate_sink_unknown_fields(&config).unwrap_err();
1385 let report = err.to_report_string();
1386 assert!(report.contains("bogus_with"), "{report}");
1387
1388 let err = crate::sink::kafka::KafkaConfig::from_btreemap(btreemap([
1389 (CONNECTOR_TYPE_KEY, "kafka"),
1390 (SINK_TYPE_OPTION, SINK_TYPE_APPEND_ONLY),
1391 ]))
1392 .unwrap_err();
1393 assert!(err.to_report_string().contains("missing field `topic`"));
1394 }
1395
1396 #[test]
1397 fn test_sink_exactly_once_policy() {
1398 assert!(sink_is_exactly_once(&btreemap([(CONNECTOR_TYPE_KEY, ICEBERG_SINK)])).unwrap());
1399 assert!(
1400 !sink_is_exactly_once(&btreemap([
1401 (CONNECTOR_TYPE_KEY, ICEBERG_SINK),
1402 ("is_exactly_once", "false"),
1403 ]))
1404 .unwrap()
1405 );
1406
1407 #[cfg(feature = "sink-deltalake")]
1408 {
1409 assert!(
1410 !sink_is_exactly_once(&btreemap([(CONNECTOR_TYPE_KEY, DELTALAKE_SINK)])).unwrap()
1411 );
1412 assert!(
1413 sink_is_exactly_once(&btreemap([
1414 (CONNECTOR_TYPE_KEY, DELTALAKE_SINK),
1415 ("is_exactly_once", "true"),
1416 ]))
1417 .unwrap()
1418 );
1419 }
1420
1421 #[cfg(feature = "sink-lancedb")]
1422 assert!(sink_is_exactly_once(&btreemap([(CONNECTOR_TYPE_KEY, LANCEDB_SINK)])).unwrap());
1423
1424 let error = sink_is_exactly_once(&btreemap([
1425 (CONNECTOR_TYPE_KEY, ICEBERG_SINK),
1426 ("is_exactly_once", "invalid"),
1427 ]))
1428 .unwrap_err();
1429 assert!(error.to_report_string().contains("is_exactly_once"));
1430 }
1431
1432 #[test]
1433 fn actor_relabeled_gauges_use_the_assigned_reducers() {
1434 for level in [MetricLevel::Critical, MetricLevel::Info] {
1435 let registry = Registry::new();
1436 let metrics = SinkMetrics::new(®istry, level);
1437
1438 for gauge_vec in [
1439 &metrics.log_store_first_write_epoch,
1440 &metrics.log_store_latest_write_epoch,
1441 ] {
1442 assert_aggregation(gauge_vec, &["1", "sink", "name"], &["2", "sink", "name"], 5);
1443 }
1444 assert_aggregation(
1445 &metrics.log_store_latest_read_epoch,
1446 &["1", "connector", "sink", "name"],
1447 &["2", "connector", "sink", "name"],
1448 5,
1449 );
1450 for gauge_vec in [
1451 &metrics.iceberg_partition_num,
1452 &metrics.iceberg_position_delete_cache_num,
1453 &metrics.iceberg_rolling_unflushed_data_file,
1454 ] {
1455 assert_aggregation(
1456 gauge_vec,
1457 &["1", "sink", "name"],
1458 &["2", "sink", "name"],
1459 12,
1460 );
1461 }
1462 }
1463 }
1464}