ryerraguntla commented on code in PR #2886:
URL: https://github.com/apache/iggy/pull/2886#discussion_r3409814899


##########
core/connectors/sinks/clickhouse_sink/src/client.rs:
##########
@@ -0,0 +1,449 @@
+// 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.
+
+//! Thin `reqwest`-based HTTP client for the ClickHouse HTTP interface.
+//!
+//! ClickHouse exposes its HTTP API at `http://host:port/`. Queries are sent
+//! either as a URL query parameter (`?query=...`) or in the request body.
+//! Authentication uses the `X-ClickHouse-User` and `X-ClickHouse-Key` headers.
+//!
+//! Insert format:
+//!   POST /?database={db}&query=INSERT+INTO+{table}+FORMAT+{fmt}
+//!   Body: row data in the chosen format
+
+use crate::schema::{Column, parse_type};
+use bytes::Bytes;
+use iggy_connector_sdk::Error;
+use rand::RngExt;
+use reqwest::StatusCode;
+use reqwest::header::{CONTENT_TYPE, HeaderMap, HeaderValue};
+use serde::Deserialize;
+use std::time::Duration;
+use tracing::{debug, error, info, warn};
+
+const USER_HEADER: &str = "X-ClickHouse-User";
+const KEY_HEADER: &str = "X-ClickHouse-Key";
+
+/// Thin wrapper around `reqwest::Client` pre-configured for a ClickHouse
+/// endpoint.
+#[derive(Debug)]
+pub(crate) struct ClickHouseClient {
+    inner: reqwest::Client,
+    base_url: String,
+    database: String,
+    table: String,
+    format_name: String,
+    insert_url: String,
+    insert_query: String,
+}
+
+impl ClickHouseClient {
+    /// Build a new client.
+    pub fn new(
+        base_url: String,
+        database: String,
+        table: String,
+        format_name: String,
+        username: &str,
+        password: &str,
+        timeout: Duration,
+    ) -> Result<Self, Error> {
+        let mut auth_headers = HeaderMap::new();
+        auth_headers.insert(
+            USER_HEADER,
+            HeaderValue::from_str(username)
+                .map_err(|e| Error::InitError(format!("Invalid username header 
value: {e}")))?,
+        );
+        auth_headers.insert(
+            KEY_HEADER,
+            HeaderValue::from_str(password)
+                .map_err(|e| Error::InitError(format!("Invalid password header 
value: {e}")))?,
+        );
+
+        let inner = reqwest::Client::builder()
+            .timeout(timeout)
+            .default_headers(auth_headers)
+            .build()
+            .map_err(|e| Error::InitError(format!("Failed to build HTTP 
client: {e}")))?;
+
+        let insert_url = format!(
+            "{}/?database={}&date_time_input_format=best_effort",
+            base_url,
+            urlencoded(&database),
+        );
+        let insert_query = format!(
+            "INSERT INTO `{}`.`{}` FORMAT {}",
+            escape_backtick(&database),
+            escape_backtick(&table),
+            format_name,
+        );
+
+        Ok(ClickHouseClient {
+            inner,
+            base_url,
+            database,
+            table,
+            format_name,
+            insert_url,
+            insert_query,
+        })
+    }
+
+    /// Send `SELECT 1` to verify the server is reachable.
+    pub async fn ping(&self) -> Result<(), Error> {
+        let url = format!("{}/ping", self.base_url);
+        let response = self
+            .inner
+            .get(&url)
+            .send()
+            .await
+            .map_err(|e| Error::InitError(format!("Ping failed: {e}")))?;
+
+        if response.status().is_success() {
+            Ok(())
+        } else {
+            let status = response.status();
+            let body = response.text().await.unwrap_or_default();
+            error!("ClickHouse ping returned HTTP {status}: {body}");
+            Err(Error::InitError(format!(
+                "ClickHouse ping returned HTTP {status}: {body}"
+            )))
+        }
+    }
+
+    /// Fetch the column definitions for the configured table.
+    /// Returns columns ordered by their position in the table definition.
+    pub async fn fetch_schema(&self) -> Result<Vec<Column>, Error> {
+        let query = format!(
+            "SELECT name, type, default_kind FROM system.columns \
+             WHERE database = '{}' AND table = '{}' \
+             ORDER BY position \
+             FORMAT JSONEachRow",
+            escape_single_quote(&self.database),
+            escape_single_quote(&self.table),
+        );
+
+        let body = self.run_query(&query).await?;
+        let mut columns = Vec::new();
+
+        for line in body.lines() {
+            let line = line.trim();
+            if line.is_empty() {
+                continue;
+            }
+            let row: SchemaRow = serde_json::from_str(line).map_err(|e| {
+                error!("Failed to parse schema row '{line}': {e}");
+                Error::InitError(format!("Schema parse error: {e}"))
+            })?;
+
+            let ch_type = parse_type(&row.r#type)?;
+            let has_default = matches!(
+                row.default_kind.as_deref(),
+                Some("DEFAULT") | Some("MATERIALIZED") | Some("ALIAS")
+            );
+            columns.push(Column {
+                name: row.name,
+                ch_type,
+                has_default,
+            });
+        }
+
+        if columns.is_empty() {
+            error!(
+                "Table '{}' not found or has no columns in database '{}'",
+                self.table, self.database
+            );
+            return Err(Error::InitError(format!(
+                "Table '{}' not found in database '{}'",
+                self.table, self.database
+            )));
+        }
+
+        info!(
+            "Fetched schema for table '{}': {} columns",
+            self.table,
+            columns.len()
+        );
+        Ok(columns)
+    }
+
+    /// Insert `body` into `table` using the given ClickHouse FORMAT string.
+    ///
+    /// Retries up to `max_retries` times on transient errors (network errors,
+    /// HTTP 429, HTTP 5xx). Does not retry on HTTP 4xx (data errors).
+    ///
+    /// # At-least-once semantics
+    ///
+    /// Each retry resends the identical body with no 
`insert_deduplication_token`.
+    /// If the server committed the batch but the response was lost, the retry
+    /// produces duplicate rows. Callers must tolerate this or handle
+    /// deduplication at read time. See the README for details.
+    // TODO: accept `Bytes` instead of `Vec<u8>` so callers can build into a
+    // `BytesMut`, freeze it zero-copy, and reuse a thread-local buffer across
+    // batches. `insert` is `pub(crate)` so the change is fully contained.
+    pub async fn insert(
+        &self,
+        body: Vec<u8>,
+        max_retries: u32,
+        retry_delay: Duration,
+    ) -> Result<(), Error> {
+        if body.is_empty() {
+            debug!("insert called with empty body — skipping");
+            return Ok(());
+        }
+
+        let body = Bytes::from(body);
+        let mut attempts = 0u32;
+        loop {
+            let result = self
+                .inner
+                .post(&self.insert_url)
+                .header(CONTENT_TYPE, "application/octet-stream")
+                .query(&[("query", &self.insert_query)])
+                .body(body.clone())
+                .send()
+                .await;
+
+            match result {
+                Ok(response) => {
+                    let status = response.status();
+                    if status.is_success() {
+                        debug!(
+                            "Inserted {} bytes into {}.{} FORMAT {}",
+                            body.len(),
+                            self.database,
+                            self.table,
+                            self.format_name
+                        );
+                        return Ok(());
+                    }
+
+                    let body_text = response.text().await.unwrap_or_default();
+
+                    if is_retryable_status(status) {
+                        attempts += 1;
+                        if attempts >= max_retries {
+                            error!(
+                                "Insert failed after {attempts} attempts (HTTP 
{status}): {body_text}"
+                            );

Review Comment:
   client.rs:243-256 (insert) — Error::CannotStoreData used for BOTH retryable 
(429/5xx/network) and non-retryable 4xx. Other connectors 
doris_sink/influxdb_sink use Error::PermanentHttpError for 4xx, per SDK doc "so 
circuit breakers are not tripped by bad data" (sdk/src/lib.rs:420-425). 
     Fix: 4xx branch → Error::PermanentHttpError.



-- 
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]

Reply via email to