ryankert01 commented on code in PR #4123:
URL: https://github.com/apache/iggy/pull/4123#discussion_r3999065219


##########
core/connectors/sinks/opendal_sink/src/lib.rs:
##########
@@ -0,0 +1,413 @@
+// 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::{
+    collections::BTreeMap,
+    fmt,
+    sync::atomic::{AtomicU64, Ordering},
+    time::Duration,
+};
+
+use async_trait::async_trait;
+use iggy_connector_sdk::{
+    ConsumedMessage, Error, MessagesMetadata, Sink, TopicMetadata,
+    retry::{RetryPolicy, parse_duration, retry_async},
+    sink_connector,
+};
+use opendal::{Buffer, Operator};
+use serde::Deserialize;
+use tracing::{debug, error, info};
+
+use crate::path::{PathContext, object_path};
+
+mod path;
+
+sink_connector!(OpenDalSink);
+
+const CONNECTOR_NAME: &str = "OpenDAL sink";
+const DEFAULT_PATH_TEMPLATE: &str = "{stream}/{topic}/{date}/{hour}";
+const DEFAULT_MAX_ATTEMPTS: u32 = 3;
+const DEFAULT_RETRY_DELAY: &str = "1s";
+const MAX_BACKOFF: Duration = Duration::from_secs(60);
+
+#[derive(Clone, Deserialize)]
+pub struct OpenDalSinkConfig {
+    pub service: String,
+    #[serde(default)]
+    pub path_prefix: Option<String>,
+    #[serde(default = "default_path_template")]
+    pub path_template: String,
+    #[serde(default)]
+    pub options: BTreeMap<String, String>,
+    #[serde(default)]
+    pub max_attempts: Option<u32>,
+    #[serde(default)]
+    pub retry_delay: Option<String>,
+    #[serde(default)]
+    pub verbose_logging: Option<bool>,
+}
+
+impl fmt::Debug for OpenDalSinkConfig {
+    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+        formatter
+            .debug_struct("OpenDalSinkConfig")
+            .field("service", &self.service)
+            .field("path_prefix", &self.path_prefix)
+            .field("path_template", &self.path_template)
+            .field("option_keys", &self.options.keys().collect::<Vec<_>>())
+            .field("max_attempts", &self.max_attempts)
+            .field("retry_delay", &self.retry_delay)
+            .field("verbose_logging", &self.verbose_logging)
+            .finish()
+    }
+}
+
+#[derive(Debug)]
+pub struct OpenDalSink {
+    id: u32,
+    config: OpenDalSinkConfig,
+    path_prefix: String,
+    retry_policy: RetryPolicy,
+    verbose: bool,
+    operator: Option<Operator>,
+    messages_processed: AtomicU64,
+    write_errors: AtomicU64,
+}
+
+impl OpenDalSink {
+    pub fn new(id: u32, config: OpenDalSinkConfig) -> Self {
+        let max_attempts = config.max_attempts.unwrap_or(DEFAULT_MAX_ATTEMPTS);
+
+        let retry_delay = parse_duration(config.retry_delay.as_deref(), 
DEFAULT_RETRY_DELAY);
+
+        let path_prefix = config
+            .path_prefix
+            .as_deref()
+            .unwrap_or_default()
+            .trim_matches('/')
+            .to_string();
+        let verbose = config.verbose_logging.unwrap_or(false);
+
+        Self {
+            id,
+            config,
+            path_prefix,
+            retry_policy: RetryPolicy {
+                max_attempts,
+                base_delay: retry_delay,
+                max_delay: MAX_BACKOFF,
+            },
+            verbose,
+            operator: None,
+            messages_processed: AtomicU64::new(0),
+            write_errors: AtomicU64::new(0),
+        }
+    }
+
+    async fn write_message(
+        &self,
+        operator: &Operator,
+        topic_metadata: &TopicMetadata,
+        messages_metadata: &MessagesMetadata,
+        message: ConsumedMessage,
+        retry_context: &str,
+    ) -> Result<(), Error> {
+        let context = PathContext {
+            stream: &topic_metadata.stream,
+            topic: &topic_metadata.topic,
+            partition_id: messages_metadata.partition_id,
+            first_timestamp_micros: message.timestamp,
+        };
+        let path = object_path(
+            &self.path_prefix,
+            &self.config.path_template,
+            &context,
+            message.offset,
+            messages_metadata.schema,
+        )?;
+        let payload = message.payload.try_into_vec()?;
+        let buffer = Buffer::from(payload);
+
+        retry_async(
+            self.retry_policy,
+            retry_context,
+            opendal::Error::is_temporary,
+            || operator.write(&path, buffer.clone()),
+        )
+        .await
+        .map_err(|failure| {
+            Error::CannotStoreData(format!(
+                "Failed to write OpenDAL object '{path}' after {} attempt(s): 
{}",
+                failure.attempts, failure.error
+            ))
+        })?;
+
+        Ok(())
+    }
+}
+
+#[async_trait]
+impl Sink for OpenDalSink {
+    async fn open(&mut self) -> Result<(), Error> {
+        let service = self.config.service.trim();
+        if service.is_empty() {
+            return Err(Error::InvalidConfigValue(
+                "OpenDAL service cannot be empty".to_string(),
+            ));
+        }
+        if self.config.path_template.is_empty() {
+            return Err(Error::InvalidConfigValue(
+                "OpenDAL path_template cannot be empty".to_string(),
+            ));
+        }
+
+        opendal::init_default_registry();

Review Comment:
   `install_default` calles `init_default_registry()` then install transport, 
so s3 would not fail. Maybe consider to add a test against minio container.
   ```suggestion
           opendal::install_default();
   ```



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