hemantkrsh commented on code in PR #2891: URL: https://github.com/apache/iggy/pull/2891#discussion_r2910595733
########## core/connectors/sinks/clickhouse_sink/src/sink.rs: ########## @@ -0,0 +1,782 @@ +/* Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +use std::time::Duration; + +use crate::clickhouse_client::ClickHouseClient; +use crate::generic_inserter; +use crate::{ + ClickHouseSink, ClickHouseSinkConfig, InsertType, MessageRowWithMetadata, + MessageRowWithoutMetadata, +}; +use async_trait::async_trait; +use clickhouse::error::Error as ChError; +use iggy_connector_sdk::{ConsumedMessage, Error, MessagesMetadata, Payload, Sink, TopicMetadata}; +use simd_json::{OwnedValue, base::ValueAsObject}; +use tracing::{debug, error, info, warn}; + +#[async_trait] +impl Sink for ClickHouseSink { + async fn open(&mut self) -> Result<(), Error> { + let clickhouse_client = ClickHouseClient::init(self.config.clone()) + .map_err(|e| Error::InitError(e.to_string()))?; + self.client = Some(clickhouse_client); + Ok(()) + } + + async fn consume( + &self, + topic_metadata: &TopicMetadata, + messages_metadata: MessagesMetadata, + messages: Vec<ConsumedMessage>, + ) -> Result<(), Error> { + self.batch_insert(&messages, topic_metadata, &messages_metadata) + .await + } + + async fn close(&mut self) -> Result<(), Error> { + info!("Closing ClickHouse sink connector with ID: {}", self.id); + + let state = self.state.lock().await; + info!( + "ClickHouse sink ID: {} processed {} messages with {} batch attempt failures and with {} batch failures", + self.id, state.messages_processed, state.insert_batch_failed, state.insert_batch_failed + ); + Ok(()) + } +} + +impl ClickHouseSink { + pub fn new(id: u32, config: ClickHouseSinkConfig) -> Self { + let verbose = config.verbose_logging(); + ClickHouseSink { + id, + client: None, + config, + state: tokio::sync::Mutex::new(Default::default()), + verbose, + } + } + + async fn run_inserter( + &self, + messages: &[ConsumedMessage], + topic_metadata: &TopicMetadata, + messages_metadata: &MessagesMetadata, + ) -> clickhouse::error::Result<()> { + match self.config.insert_type { + InsertType::Json => { + let inserter = self + .client + .as_ref() + .ok_or_else(|| { + clickhouse::error::Error::Custom( + "ClickHouse client not initialized".to_string(), + ) + })? + .create_formatted_inserter(); + + generic_inserter::run_inserter(inserter, messages, |msg| { + self.prepare_json_data(msg, topic_metadata, messages_metadata) + }) + .await?; + } + InsertType::RowBinary => { + if self.config.include_metadata() { + let inserter = self + .client + .as_ref() + .ok_or_else(|| { + clickhouse::error::Error::Custom( + "ClickHouse client not initialized".to_string(), + ) + })? + .create_typed_inserter::<MessageRowWithMetadata>(&self.config.table); + + generic_inserter::run_inserter(inserter, messages, |msg| { + self.prepare_row_with_metadata(msg, topic_metadata, messages_metadata) + }) + .await?; + } else { + let inserter = self + .client + .as_ref() + .ok_or_else(|| { + clickhouse::error::Error::Custom( + "ClickHouse client not initialized".to_string(), + ) + })? + .create_typed_inserter::<MessageRowWithoutMetadata>(&self.config.table); + + generic_inserter::run_inserter(inserter, messages, |msg| { + self.prepare_row_without_metadata(msg) + }) + .await?; + } + } + } + + Ok(()) + } + + // create the batch and invoke try_insert + async fn batch_insert( + &self, + messages: &[ConsumedMessage], + topic_metadata: &TopicMetadata, + messages_metadata: &MessagesMetadata, + ) -> Result<(), Error> { + let batch_size = self.config.max_batch_size() as usize; + for chunk in messages.chunks(batch_size) { + self.try_insert(chunk, topic_metadata, messages_metadata) + .await?; + } + Ok(()) + } + + // try insert batch of data with retry + async fn try_insert( + &self, + messages: &[ConsumedMessage], + topic_metadata: &TopicMetadata, + messages_metadata: &MessagesMetadata, + ) -> Result<(), Error> { + let retry = self.config.retry(); + let max_retries = self.config.max_retry(); + let mut retry_count = 0; + let base_delay = Duration::from_millis(self.config.retry_base_delay()); + + loop { + match self + .run_inserter(messages, topic_metadata, messages_metadata) + .await + { + Ok(_) => { + let msg_count = messages.len(); + let table = &self.config.table; + if self.verbose { + info!( + "ClickHouse sink ID: {} processed {} messages to table '{}' (attempt {})", + self.id, + msg_count, + table, + retry_count + 1 + ); + } else { + debug!( + "ClickHouse sink ID: {} processed {} messages to table '{}' (attempt {})", + self.id, + msg_count, + table, + retry_count + 1 + ); + } + + let mut state = self.state.lock().await; + state.messages_processed += messages.len() as u64; + drop(state); + + return Ok(()); + } + //TODO: is_retryable check -- done + Err(ch_err) if retry && retry_count < max_retries && is_retryable(&ch_err) => { + let delay = base_delay * 2u32.pow(retry_count); Review Comment: Handled this by capping the `max_retries` to 10 and max delay to 15 minutes to avoid unbounded or unreasonably high delay between retries. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
