atharvalade commented on code in PR #3103: URL: https://github.com/apache/iggy/pull/3103#discussion_r3431537849
########## core/connectors/sinks/s3_sink/src/formatter.rs: ########## @@ -0,0 +1,375 @@ +// 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::OutputFormat; +use chrono::{DateTime, Utc}; +use iggy_connector_sdk::{ + ConsumedMessage, Error, MessagesMetadata, Payload, TopicMetadata, owned_value_to_serde_json, +}; +use serde::Serialize; +use serde_json::Value; + +#[derive(Serialize)] +struct JsonMessage<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + offset: Option<u64>, + #[serde(skip_serializing_if = "Option::is_none")] + timestamp: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + stream: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + topic: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + partition_id: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + headers: Option<Value>, + payload: Value, +} + +pub(crate) fn format_message( + message: &ConsumedMessage, + topic_metadata: &TopicMetadata, + messages_metadata: &MessagesMetadata, + include_metadata: bool, + include_headers: bool, + format: OutputFormat, +) -> Result<Vec<u8>, Error> { + match format { + OutputFormat::JsonLines | OutputFormat::JsonArray => format_json_message( + message, + topic_metadata, + messages_metadata, + include_metadata, + include_headers, + ), + OutputFormat::Raw => format_raw_message(message), + } +} + +fn format_json_message( + message: &ConsumedMessage, + topic_metadata: &TopicMetadata, + messages_metadata: &MessagesMetadata, + include_metadata: bool, + include_headers: bool, +) -> Result<Vec<u8>, Error> { + let ts_str = if include_metadata { + Some(timestamp_to_rfc3339(message.timestamp)) + } else { + None + }; + let msg = JsonMessage { + offset: if include_metadata { + Some(message.offset) + } else { + None + }, + timestamp: ts_str.as_deref(), + stream: if include_metadata { + Some(&topic_metadata.stream) + } else { + None + }, + topic: if include_metadata { + Some(&topic_metadata.topic) + } else { + None + }, + partition_id: if include_metadata { + Some(messages_metadata.partition_id) + } else { + None + }, + headers: if include_headers { + message.headers.as_ref().map(serialize_headers) + } else { + None + }, + payload: payload_to_json_value(&message.payload), + }; + + serde_json::to_vec(&msg).map_err(|e| { + Error::CannotStoreData(format!( + "Failed to serialize message at offset {}: {e}", + message.offset + )) + }) +} + +fn format_raw_message(message: &ConsumedMessage) -> Result<Vec<u8>, Error> { + message.payload.try_to_bytes().map_err(|e| { + Error::CannotStoreData(format!( + "Failed to extract raw bytes at offset {}: {e}", + message.offset + )) + }) +} + +fn serialize_headers( + headers: &std::collections::BTreeMap<iggy_common::HeaderKey, iggy_common::HeaderValue>, +) -> Value { + use iggy_common::HeaderKind; + use serde_json::Map; + + let mut obj = Map::new(); + for (key, value) in headers { + let key_str = key.as_str().unwrap_or("").to_string(); + let json_value = match value.kind() { + HeaderKind::String => { + Value::String(String::from_utf8_lossy(&value.value()).into_owned()) + } + HeaderKind::Raw => Value::String(base64_encode(&value.value())), + HeaderKind::Bool => { + let b = !value.value().is_empty() && value.value()[0] != 0; + Value::Bool(b) + } + HeaderKind::Int8 | HeaderKind::Int16 | HeaderKind::Int32 | HeaderKind::Int64 => { + let s = value.to_string_value(); + s.parse::<i64>() + .map(|n| Value::Number(n.into())) + .unwrap_or(Value::String(s)) + } + HeaderKind::Uint8 | HeaderKind::Uint16 | HeaderKind::Uint32 | HeaderKind::Uint64 => { + let s = value.to_string_value(); + s.parse::<u64>() + .map(|n| Value::Number(n.into())) + .unwrap_or(Value::String(s)) + } + HeaderKind::Float32 | HeaderKind::Float64 => { + let s = value.to_string_value(); + s.parse::<f64>() + .ok() + .and_then(serde_json::Number::from_f64) + .map(Value::Number) + .unwrap_or(Value::String(s)) + } + _ => Value::String(value.to_string_value()), + }; + obj.insert(key_str, json_value); + } + Value::Object(obj) +} + +fn payload_to_json_value(payload: &Payload) -> Value { + match payload { + Payload::Json(value) => owned_value_to_serde_json(value), + Payload::Text(text) => Value::String(text.clone()), + Payload::Raw(bytes) => match serde_json::from_slice(bytes) { + Ok(v) => v, + Err(_) => Value::String(base64_encode(bytes)), + }, + Payload::Proto(text) => Value::String(text.clone()), + Payload::FlatBuffer(bytes) => Value::String(base64_encode(bytes)), + Payload::Avro(bytes) => Value::String(base64_encode(bytes)), + } +} + +fn base64_encode(bytes: &[u8]) -> String { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +fn timestamp_to_rfc3339(micros: u64) -> String { + let secs = (micros / 1_000_000) as i64; + let nanos = ((micros % 1_000_000) * 1_000) as u32; + DateTime::<Utc>::from_timestamp(secs, nanos) + .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) + .unwrap_or_else(|| "1970-01-01T00:00:00Z".to_string()) +} + +/// Finalize buffer entries into the output byte format. +/// For JsonArray: byte-concatenation (no re-parse). For JsonLines/Raw: newline-separated. +pub(crate) fn finalize_buffer<'a>( + entries: impl Iterator<Item = &'a [u8]>, + format: OutputFormat, +) -> Vec<u8> { + match format { Review Comment: good catch, split `Raw` into its own `finalize_buffer` arm that concatenates entries without any delimiter, added `finalize_raw_no_delimiter` test with embedded 0x0A bytes to prevent regression -- 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]
