atharvalade commented on code in PR #3103:
URL: https://github.com/apache/iggy/pull/3103#discussion_r3431544660


##########
core/connectors/sinks/s3_sink/src/lib.rs:
##########
@@ -0,0 +1,478 @@
+// 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::fmt;
+use std::str::FromStr;
+use std::sync::Arc;
+
+use iggy_connector_sdk::{Error, sink_connector};
+use secrecy::SecretString;
+use serde::{Deserialize, Serialize};
+
+mod buffer;
+mod client;
+mod formatter;
+mod path;
+mod sink;
+
+sink_connector!(S3Sink);
+
+const DEFAULT_MAX_ATTEMPTS: u32 = 3;
+const DEFAULT_RETRY_DELAY: &str = "1s";
+const DEFAULT_MAX_FILE_SIZE: &str = "8MiB";
+const DEFAULT_PATH_TEMPLATE: &str = "{stream}/{topic}/{date}/{hour}";
+const DEFAULT_OUTPUT_FORMAT: &str = "json_lines";
+const MAX_S3_SINGLE_PUT_SIZE: u64 = 5 * 1024 * 1024 * 1024; // 5 GiB
+
+#[derive(Clone, Serialize, Deserialize)]
+pub struct S3SinkConfig {
+    pub bucket: String,
+    pub region: String,
+    #[serde(default)]
+    pub prefix: Option<String>,
+    #[serde(default)]
+    pub endpoint: Option<String>,
+    #[serde(
+        default,
+        serialize_with = "iggy_common::serde_secret::serialize_optional_secret"
+    )]
+    pub access_key_id: Option<SecretString>,
+    #[serde(
+        default,
+        serialize_with = "iggy_common::serde_secret::serialize_optional_secret"
+    )]
+    pub secret_access_key: Option<SecretString>,
+    #[serde(default = "default_path_template")]
+    pub path_template: String,
+    #[serde(default = "default_file_rotation")]
+    pub file_rotation: FileRotation,
+    #[serde(default = "default_max_file_size")]
+    pub max_file_size: String,
+    #[serde(default)]
+    pub max_messages_per_file: Option<u64>,
+    #[serde(default = "default_output_format")]
+    pub output_format: String,
+    #[serde(default = "default_true")]
+    pub include_metadata: bool,
+    #[serde(default)]
+    pub include_headers: bool,
+    #[serde(default, alias = "max_retries")]
+    pub max_attempts: Option<u32>,
+    #[serde(default)]
+    pub retry_delay: Option<String>,
+    #[serde(default)]
+    pub path_style: Option<bool>,
+}
+
+impl fmt::Debug for S3SinkConfig {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("S3SinkConfig")
+            .field("bucket", &self.bucket)
+            .field("region", &self.region)
+            .field("prefix", &self.prefix)
+            .field("endpoint", &self.endpoint)
+            .field("access_key_id", &"[REDACTED]")
+            .field("secret_access_key", &"[REDACTED]")
+            .field("path_template", &self.path_template)
+            .field("file_rotation", &self.file_rotation)
+            .field("max_file_size", &self.max_file_size)
+            .field("max_messages_per_file", &self.max_messages_per_file)
+            .field("output_format", &self.output_format)
+            .field("include_metadata", &self.include_metadata)
+            .field("include_headers", &self.include_headers)
+            .field("max_attempts", &self.max_attempts)
+            .field("retry_delay", &self.retry_delay)
+            .field("path_style", &self.path_style)
+            .finish()
+    }
+}
+
+fn default_path_template() -> String {
+    DEFAULT_PATH_TEMPLATE.to_string()
+}
+
+fn default_file_rotation() -> FileRotation {
+    FileRotation::Size
+}
+
+fn default_max_file_size() -> String {
+    DEFAULT_MAX_FILE_SIZE.to_string()
+}
+
+fn default_output_format() -> String {
+    DEFAULT_OUTPUT_FORMAT.to_string()
+}
+
+fn default_true() -> bool {
+    true
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FileRotation {
+    Size,
+    Messages,
+}
+
+impl fmt::Display for FileRotation {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            FileRotation::Size => write!(f, "size"),
+            FileRotation::Messages => write!(f, "messages"),
+        }
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum OutputFormat {
+    JsonLines,
+    JsonArray,
+    Raw,
+}
+
+impl TryFrom<&str> for OutputFormat {
+    type Error = Error;
+
+    fn try_from(s: &str) -> Result<Self, Self::Error> {
+        match s.to_lowercase().as_str() {
+            "json_lines" | "jsonl" | "jsonlines" => 
Ok(OutputFormat::JsonLines),
+            "json_array" => Ok(OutputFormat::JsonArray),
+            "raw" => Ok(OutputFormat::Raw),
+            other => Err(Error::InvalidConfigValue(format!(
+                "Unknown output format: '{other}'. Expected: json_lines, 
json_array, or raw"
+            ))),
+        }
+    }
+}
+
+impl OutputFormat {
+    pub fn file_extension(&self) -> &'static str {
+        match self {
+            OutputFormat::JsonLines => "jsonl",
+            OutputFormat::JsonArray => "json",
+            OutputFormat::Raw => "bin",
+        }
+    }
+}
+
+pub struct S3Sink {
+    id: u32,
+    config: S3SinkConfig,
+    bucket: Option<Box<s3::Bucket>>,
+    buffers: DashMap<BufferKey, Arc<tokio::sync::Mutex<buffer::FileBuffer>>>,
+    max_file_size_bytes: u64,
+    max_messages: u64,
+    output_format: OutputFormat,
+    state: tokio::sync::Mutex<SinkState>,
+    retry_delay: std::time::Duration,
+}
+
+impl fmt::Debug for S3Sink {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("S3Sink")
+            .field("id", &self.id)
+            .field("config", &self.config)
+            .field("bucket", &self.bucket.as_ref().map(|b| &b.name))
+            .field("buffers_count", &self.buffers.len())
+            .field("max_file_size_bytes", &self.max_file_size_bytes)
+            .field("max_messages", &self.max_messages)
+            .field("output_format", &self.output_format)
+            .field("retry_delay", &self.retry_delay)
+            .finish()
+    }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub(crate) struct BufferKey {
+    pub stream: String,
+    pub topic: String,
+    pub partition_id: u32,
+}
+
+#[derive(Debug)]
+struct SinkState {
+    messages_received: u64,
+    messages_uploaded: u64,
+    messages_lost: u64,
+}
+
+impl S3Sink {
+    pub fn new(id: u32, config: S3SinkConfig) -> Self {
+        S3Sink {
+            id,
+            config,
+            bucket: None,
+            buffers: DashMap::new(),
+            max_file_size_bytes: 0,
+            max_messages: u64::MAX,
+            output_format: OutputFormat::JsonLines,
+            state: tokio::sync::Mutex::new(SinkState {
+                messages_received: 0,
+                messages_uploaded: 0,
+                messages_lost: 0,
+            }),
+            retry_delay: std::time::Duration::from_secs(1),
+        }
+    }
+
+    pub fn validate_and_parse_config(&mut self) -> Result<(), Error> {
+        if self.config.bucket.is_empty() {
+            return Err(Error::InvalidConfigValue(
+                "bucket must not be empty".to_owned(),
+            ));
+        }
+        if self.config.region.is_empty() {
+            return Err(Error::InvalidConfigValue(
+                "region must not be empty".to_owned(),
+            ));
+        }
+        if self.config.path_template.is_empty() {
+            return Err(Error::InvalidConfigValue(
+                "path_template must not be empty".to_owned(),
+            ));
+        }
+
+        self.output_format = 
OutputFormat::try_from(self.config.output_format.as_str())?;
+        self.max_file_size_bytes = 
parse_file_size(&self.config.max_file_size)?;
+
+        if self.max_file_size_bytes == 0 {
+            return Err(Error::InvalidConfigValue(
+                "max_file_size must be greater than 0".to_owned(),
+            ));
+        }
+        if self.max_file_size_bytes > MAX_S3_SINGLE_PUT_SIZE {
+            return Err(Error::InvalidConfigValue(format!(
+                "max_file_size ({}) exceeds S3 single PutObject limit of 5 
GiB",
+                self.config.max_file_size
+            )));
+        }
+
+        let delay_str = self
+            .config
+            .retry_delay
+            .as_deref()
+            .unwrap_or(DEFAULT_RETRY_DELAY);
+        self.retry_delay = humantime::Duration::from_str(delay_str)
+            .map(|d| d.into())
+            .map_err(|e| {
+                Error::InvalidConfigValue(format!("Invalid retry_delay 
'{delay_str}': {e}"))
+            })?;
+
+        if self.config.file_rotation == FileRotation::Messages {
+            match self.config.max_messages_per_file {
+                None => {
+                    return Err(Error::InvalidConfigValue(
+                        "file_rotation is 'messages' but max_messages_per_file 
is not configured"
+                            .to_owned(),
+                    ));
+                }
+                Some(0) => {
+                    return Err(Error::InvalidConfigValue(
+                        "max_messages_per_file must be greater than 
0".to_owned(),
+                    ));
+                }
+                Some(n) => {
+                    self.max_messages = n;
+                }
+            }
+        } else if let Some(n) = self.config.max_messages_per_file {
+            if n == 0 {
+                return Err(Error::InvalidConfigValue(
+                    "max_messages_per_file must be greater than 0".to_owned(),
+                ));
+            }
+            self.max_messages = n;
+        }
+
+        Ok(())
+    }
+

Review Comment:
   Added doc comment on the field clarifying "total attempts" semantics: 
max_attempts = 3 means 1 initial try + 2 retries, and the `max_retries` alias 
follows the same meaning



##########
core/connectors/sinks/s3_sink/src/sink.rs:
##########
@@ -0,0 +1,657 @@
+// 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 crate::buffer::FileBuffer;
+use crate::formatter;
+use crate::path::{PathContext, render_s3_key};
+use crate::{BufferKey, S3Sink};
+use async_trait::async_trait;
+use iggy_connector_sdk::retry::{exponential_backoff, jitter};
+use iggy_connector_sdk::{ConsumedMessage, Error, MessagesMetadata, Sink, 
TopicMetadata};
+use std::sync::Arc;
+use std::time::Duration;
+use tracing::{debug, error, info, warn};
+
+const MAX_BACKOFF: Duration = Duration::from_secs(60);
+
+struct FlushPayload {
+    data: Vec<u8>,
+    s3_key: String,
+    msg_count: u64,
+    first_offset: u64,
+    last_offset: u64,
+}
+
+#[async_trait]
+impl Sink for S3Sink {
+    async fn open(&mut self) -> Result<(), Error> {
+        info!("Opening S3 sink connector with ID: {}", self.id);
+
+        self.validate_and_parse_config()?;
+
+        let bucket = crate::client::create_bucket(&self.config).await?;
+
+        crate::client::verify_bucket(&bucket).await?;
+
+        info!(
+            "S3 sink ID: {} connected to bucket '{}' in region '{}'",
+            self.id, self.config.bucket, self.config.region
+        );
+
+        self.bucket = Some(bucket);
+
+        info!(
+            "S3 sink ID: {} opened. format={}, rotation={}, max_file_size={}, 
template='{}'",
+            self.id,
+            self.config.output_format,
+            self.config.file_rotation,
+            self.config.max_file_size,
+            self.config.path_template,
+        );
+
+        Ok(())
+    }
+
+    async fn consume(
+        &self,
+        topic_metadata: &TopicMetadata,
+        messages_metadata: MessagesMetadata,
+        messages: Vec<ConsumedMessage>,
+    ) -> Result<(), Error> {
+        let bucket = self
+            .bucket
+            .as_ref()
+            .ok_or_else(|| Error::InitError("S3 client not 
initialized".to_string()))?;
+
+        let key = BufferKey {
+            stream: topic_metadata.stream.clone(),
+            topic: topic_metadata.topic.clone(),
+            partition_id: messages_metadata.partition_id,
+        };
+
+        let batch_size = messages.len() as u64;
+
+        {
+            let mut state = self.state.lock().await;
+            state.messages_received += batch_size;
+        }
+
+        let buffer_arc = self
+            .buffers
+            .entry(key.clone())
+            .or_insert_with(|| 
Arc::new(tokio::sync::Mutex::new(FileBuffer::new())))
+            .clone();
+
+        let mut processed = 0u64;
+        let result = self
+            .process_messages_inner(
+                bucket,
+                &key,
+                &buffer_arc,
+                topic_metadata,
+                &messages_metadata,
+                &messages,
+                &mut processed,
+            )
+            .await;
+
+        if let Err(ref e) = result {
+            let lost = batch_size - processed;
+            if lost > 0 {
+                let mut state = self.state.lock().await;
+                state.messages_lost += lost;
+                error!(
+                    "S3 sink ID: {} lost {lost} messages from batch of 
{batch_size} for {}/{}/{}: {e}",
+                    self.id,
+                    topic_metadata.stream,
+                    topic_metadata.topic,
+                    messages_metadata.partition_id,
+                );
+            }
+        }
+
+        debug!(
+            "S3 sink ID: {} buffered {} messages for {}/{}/{}",
+            self.id,
+            batch_size,
+            topic_metadata.stream,
+            topic_metadata.topic,
+            messages_metadata.partition_id,
+        );
+
+        result
+    }
+
+    async fn close(&mut self) -> Result<(), Error> {
+        info!("Closing S3 sink connector with ID: {}", self.id);
+
+        if let Some(bucket) = &self.bucket {
+            for entry in self.buffers.iter() {
+                let key = entry.key().clone();
+                let buffer_arc = entry.value().clone();
+                let flush_payload = {
+                    let mut buffer = buffer_arc.lock().await;
+                    if buffer.is_empty() {
+                        None
+                    } else {
+                        Some(self.extract_flush_payload(&key, &mut buffer))
+                    }
+                };
+                if let Some(Ok(payload)) = flush_payload {
+                    if let Err(e) = self.do_upload(bucket, payload).await {
+                        error!(
+                            "S3 sink ID: {} failed to flush on close for 
{}/{}/{}: {e}",
+                            self.id, key.stream, key.topic, key.partition_id
+                        );
+                    }
+                } else if let Some(Err(e)) = flush_payload {
+                    error!(
+                        "S3 sink ID: {} failed to prepare flush on close for 
{}/{}/{}: {e}",
+                        self.id, key.stream, key.topic, key.partition_id
+                    );
+                }
+            }
+        } else {
+            let pending: u64 = self
+                .buffers
+                .iter()
+                .map(|e| e.value().try_lock().map(|b| 
b.message_count()).unwrap_or(0))
+                .sum();
+            if pending > 0 {
+                warn!(
+                    "S3 sink ID: {} closing without S3 client — {pending} 
buffered messages will be lost",
+                    self.id,
+                );
+            }
+        }
+
+        let state = self.state.lock().await;
+        info!(
+            "S3 sink ID: {} closed. received={}, uploaded={}, lost={}",
+            self.id, state.messages_received, state.messages_uploaded, 
state.messages_lost,
+        );
+
+        Ok(())
+    }
+}
+
+impl S3Sink {
+    #[allow(clippy::too_many_arguments)]
+    async fn process_messages_inner(
+        &self,
+        bucket: &s3::Bucket,
+        key: &BufferKey,
+        buffer_arc: &Arc<tokio::sync::Mutex<FileBuffer>>,
+        topic_metadata: &TopicMetadata,
+        messages_metadata: &MessagesMetadata,
+        messages: &[ConsumedMessage],
+        processed: &mut u64,
+    ) -> Result<(), Error> {
+        for message in messages {
+            let formatted = formatter::format_message(
+                message,
+                topic_metadata,
+                messages_metadata,
+                self.config.include_metadata,
+                self.config.include_headers,
+                self.output_format,
+            )?;
+
+            let flush_payload = {
+                let mut buffer = buffer_arc.lock().await;
+                buffer.append(&formatted, message.offset, message.timestamp);
+
+                if buffer.should_rotate(
+                    self.config.file_rotation,
+                    self.max_file_size_bytes,
+                    self.max_messages,
+                ) {
+                    Some(self.extract_flush_payload(key, &mut buffer)?)
+                } else {
+                    None
+                }
+            };
+
+            if let Some(payload) = flush_payload {
+                self.do_upload(bucket, payload).await?;
+            }
+
+            *processed += 1;
+        }
+        Ok(())
+    }
+
+    fn extract_flush_payload(
+        &self,
+        key: &BufferKey,
+        buffer: &mut FileBuffer,
+    ) -> Result<FlushPayload, Error> {
+        let data = formatter::finalize_buffer(buffer.entries(), 
self.output_format);
+
+        let ctx = PathContext {
+            stream: &key.stream,
+            topic: &key.topic,
+            partition_id: key.partition_id,
+            first_timestamp_micros: buffer.first_timestamp_micros(),
+        };
+
+        let s3_key = render_s3_key(
+            self.config.prefix.as_deref(),
+            &self.config.path_template,
+            &ctx,
+            buffer.first_offset(),
+            buffer.last_offset(),
+            self.output_format,
+        )?;
+
+        let msg_count = buffer.message_count();
+        let first_offset = buffer.first_offset();
+        let last_offset = buffer.last_offset();
+
+        buffer.reset();
+
+        Ok(FlushPayload {
+            data,
+            s3_key,
+            msg_count,
+            first_offset,
+            last_offset,
+        })
+    }
+
+    async fn do_upload(&self, bucket: &s3::Bucket, payload: FlushPayload) -> 
Result<(), Error> {
+        match self
+            .upload_with_retry(bucket, &payload.s3_key, &payload.data)
+            .await
+        {
+            Ok(()) => {
+                debug!(
+                    "S3 sink ID: {} uploaded {} ({} messages, {} bytes)",
+                    self.id,
+                    payload.s3_key,
+                    payload.msg_count,
+                    payload.data.len(),
+                );
+                let mut state = self.state.lock().await;
+                state.messages_uploaded += payload.msg_count;
+                Ok(())
+            }
+            Err(e) => {
+                error!(
+                    "S3 sink ID: {} failed to upload {} ({} messages, offsets 
{}-{} lost): {e}",
+                    self.id,
+                    payload.s3_key,
+                    payload.msg_count,
+                    payload.first_offset,
+                    payload.last_offset,
+                );
+                let mut state = self.state.lock().await;
+                state.messages_lost += payload.msg_count;
+
+                self.write_lost_marker(
+                    bucket,
+                    &payload.s3_key,
+                    payload.first_offset,
+                    payload.last_offset,
+                    payload.msg_count,
+                    &e,
+                )
+                .await;
+
+                Err(e)
+            }
+        }
+    }
+
+    async fn write_lost_marker(
+        &self,
+        bucket: &s3::Bucket,
+        s3_key: &str,
+        first_offset: u64,
+        last_offset: u64,
+        msg_count: u64,
+        error: &Error,
+    ) {
+        let marker_key = format!("{s3_key}.lost");
+        let body = format!(
+            "offset_range: {first_offset}-{last_offset}\nmessage_count: 
{msg_count}\nerror: {error}\n"
+        );
+        if let Err(e) = self
+            .upload_with_retry(bucket, &marker_key, body.as_bytes())
+            .await
+        {
+            warn!(
+                "S3 sink ID: {} failed to write .lost marker at {} after 
retries: {e}",
+                self.id, marker_key
+            );
+        }
+    }
+
+    async fn upload_with_retry(
+        &self,
+        bucket: &s3::Bucket,
+        s3_key: &str,
+        data: &[u8],
+    ) -> Result<(), Error> {
+        let max_attempts = self.max_attempts();
+        let base_delay = self.retry_delay;
+        let mut attempt = 0u32;
+
+        loop {
+            match bucket.put_object(s3_key, data).await {
+                Ok(response) => {
+                    let status = response.status_code();
+                    if (200..300).contains(&status) {
+                        return Ok(());
+                    }
+
+                    if !is_retriable_status(status) {
+                        return Err(Error::CannotStoreData(format!(
+                            "S3 PutObject returned non-retriable status 
{status} for key '{s3_key}'"
+                        )));
+                    }
+
+                    attempt += 1;
+                    if attempt >= max_attempts {
+                        return Err(Error::CannotStoreData(format!(
+                            "S3 PutObject returned status {status} after 
{max_attempts} attempts for key '{s3_key}'"
+                        )));
+                    }
+                    warn!(
+                        "S3 sink ID: {} PutObject status {status} (attempt 
{attempt}/{max_attempts}). Retrying...",
+                        self.id
+                    );
+                }
+                Err(e) => {
+                    attempt += 1;
+                    if attempt >= max_attempts {
+                        return Err(Error::CannotStoreData(format!(
+                            "S3 PutObject failed after {max_attempts} attempts 
for key '{s3_key}': {e}"
+                        )));
+                    }
+                    warn!(
+                        "S3 sink ID: {} PutObject error (attempt 
{attempt}/{max_attempts}): {e}. Retrying...",
+                        self.id
+                    );
+                }
+            }

Review Comment:
   Extracted let `retry_index` = attempt - 1 with a comment explaining 
`exponential_backoff` expects a 0-based index



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