mattp5657 commented on code in PR #4123: URL: https://github.com/apache/iggy/pull/4123#discussion_r4010497339
########## 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(); + let options = self.config.options.clone(); + let operator = Operator::via_iter(service, options).map_err(|error| { + Error::InitError(format!( + "Failed to create OpenDAL service '{service}': {error}" + )) + })?; + + if !operator.info().capability().write { + return Err(Error::InvalidConfigValue(format!( + "OpenDAL service '{service}' does not support writes" + ))); + } + + operator.check().await.map_err(|error| { + Error::InitError(format!( + "OpenDAL service '{service}' connectivity check failed: {error}" + )) + })?; + + info!( + "Opened {CONNECTOR_NAME} connector ID: {}, service: {service}, root: {}", + self.id, + operator.info().root() + ); + self.operator = Some(operator); + Ok(()) + } + + async fn consume( Review Comment: Should these be batched instead of one `operator.write()` per message? `s3_sink` batches and flushes a combined object per batch, this sink issues a separate write per message, so at the default `batch_length = 100` that's 100 S3 PUTs instead of 1. Worth aligning with `s3_sink`'s approach for cost/throughput at scale? ########## 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>, Review Comment: Credentials (S3 access keys, etc.) flow through `options: BTreeMap<String, String>` instead of `SecretString`, diverging from this codebase's own stated convention for credential-bearing config. A hand-rolled `Debug` impl redacts values in one specific logging path but gives no type-level guarantee anywhere else. ########## core/connectors/sinks/opendal_sink/src/path.rs: ########## @@ -0,0 +1,123 @@ +// 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 chrono::{DateTime, Utc}; +use iggy_connector_sdk::{Error, Schema}; + +pub(crate) struct PathContext<'a> { + pub(crate) stream: &'a str, + pub(crate) topic: &'a str, + pub(crate) partition_id: u32, + pub(crate) first_timestamp_micros: u64, +} + +pub(crate) fn object_path( + path_prefix: &str, + path_template: &str, + context: &PathContext<'_>, + offset: u64, + schema: Schema, +) -> Result<String, Error> { + let rendered = render_template(path_template, context)?; + let extension = match schema { + Schema::Json => "json", + Schema::Raw => "bin", + Schema::Text => "txt", + Schema::Proto => "proto", + Schema::FlatBuffer => "flatbuffer", + Schema::Avro => "avro", + }; + + // Partition ID is always embedded in the filename to prevent cross-partition + // key collisions because partitions have independent offset spaces starting at + // 0. + let filename = format!("{:05}-{:020}.{}", context.partition_id, offset, extension); + + if path_prefix.is_empty() { + Ok(format!("{rendered}/{filename}")) + } else { + Ok(format!("{path_prefix}/{rendered}/{filename}")) + } +} + +fn render_template(template: &str, context: &PathContext<'_>) -> Result<String, Error> { + let timestamp = timestamp_to_datetime(context.first_timestamp_micros)?; + let date = timestamp.format("%Y-%m-%d").to_string(); + let hour = timestamp.format("%H").to_string(); + let timestamp_millis = (context.first_timestamp_micros / 1_000).to_string(); + + Ok(template + .replace("{stream}", &sanitize_path_segment(context.stream)) + .replace("{topic}", &sanitize_path_segment(context.topic)) + .replace("{partition}", &context.partition_id.to_string()) + .replace("{date}", &date) + .replace("{hour}", &hour) + .replace("{timestamp}", ×tamp_millis)) +} + +fn sanitize_path_segment(segment: &str) -> String { + segment + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() + || character == '.' + || character == '_' + || character == '-' + { + character + } else { + '_' + } + }) + .collect() +} + +fn timestamp_to_datetime(micros: u64) -> Result<DateTime<Utc>, Error> { + let seconds = (micros / 1_000_000) as i64; + let nanoseconds = ((micros % 1_000_000) * 1_000) as u32; + DateTime::<Utc>::from_timestamp(seconds, nanoseconds).ok_or_else(|| { + Error::CannotStoreData(format!( Review Comment: Should an out-of-range timestamp return `Error::InvalidRecordValue` instead of `Error::CannotStoreData`? -- 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]
