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


##########
core/connectors/sinks/meilisearch_sink/src/lib.rs:
##########
@@ -0,0 +1,1316 @@
+// 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 async_trait::async_trait;
+use base64::{Engine as _, engine::general_purpose};
+use iggy_common::IggyTimestamp;
+use iggy_connector_sdk::{
+    ConsumedMessage, Error, MessagesMetadata, Payload, Sink, TopicMetadata,
+    convert::owned_value_to_serde_json,
+    retry::{exponential_backoff, jitter, parse_duration},
+    sink_connector,
+};
+use meilisearch_sdk::{
+    client::Client,
+    errors::{
+        Error as MeilisearchSdkError, ErrorCode as MeilisearchErrorCode,
+        ErrorType as MeilisearchErrorType,
+    },
+    indexes::Index,
+    task_info::TaskInfo,
+    tasks::Task,
+};
+use secrecy::{ExposeSecret, SecretString};
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+use std::{cmp, future::Future, time::Duration};
+use tokio::{
+    sync::Mutex,
+    time::{Instant, sleep},
+};
+use tracing::{debug, error, info, warn};
+use url::Url;
+
+sink_connector!(MeilisearchSink);
+
+const DEFAULT_PRIMARY_KEY: &str = "iggy_id";
+const DEFAULT_CREATE_INDEX_IF_NOT_EXISTS: bool = true;
+const DEFAULT_INCLUDE_METADATA: bool = true;
+const DEFAULT_BATCH_SIZE: usize = 1000;
+const DEFAULT_TIMEOUT: &str = "30s";
+const DEFAULT_WAIT_FOR_TASKS: bool = true;
+const DEFAULT_TASK_TIMEOUT: &str = "30s";
+const DEFAULT_TASK_POLL_INTERVAL: &str = "100ms";
+const DEFAULT_RETRY_DELAY: &str = "500ms";
+const DEFAULT_MAX_RETRY_DELAY: &str = "5s";
+const DEFAULT_MAX_RETRIES: u32 = 3;
+const DEFAULT_MAX_OPEN_RETRIES: u32 = 5;
+const ENCODING_BASE64: &str = "base64";
+
+#[derive(Debug)]
+struct State {
+    invocations_count: usize,
+    documents_enqueued: usize,
+    documents_confirmed: usize,
+    errors_count: usize,
+}
+
+#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum MeilisearchDocumentAction {
+    #[default]
+    Replace,
+    Update,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct MeilisearchSinkConfig {
+    pub url: String,
+    pub index: String,
+    #[serde(serialize_with = 
"iggy_common::serde_secret::serialize_optional_secret")]
+    pub api_key: Option<SecretString>,
+    pub primary_key: Option<String>,
+    pub document_action: Option<MeilisearchDocumentAction>,
+    pub create_index_if_not_exists: Option<bool>,
+    pub include_metadata: Option<bool>,
+    pub batch_size: Option<usize>,
+    pub timeout: Option<String>,
+    pub wait_for_tasks: Option<bool>,
+    pub task_timeout: Option<String>,
+    pub task_poll_interval: Option<String>,
+    pub max_retries: Option<u32>,
+    pub retry_delay: Option<String>,
+    pub max_retry_delay: Option<String>,
+    pub max_open_retries: Option<u32>,
+}
+
+#[derive(Debug)]
+pub struct MeilisearchSink {
+    id: u32,
+    config: ResolvedMeilisearchSinkConfig,
+    client: Option<Client>,
+    state: Mutex<State>,
+}
+
+#[derive(Debug)]
+struct ResolvedMeilisearchSinkConfig {
+    url: String,
+    index: String,
+    api_key: Option<SecretString>,
+    primary_key: String,
+    document_action: MeilisearchDocumentAction,
+    create_index_if_not_exists: bool,
+    include_metadata: bool,
+    batch_size: usize,
+    timeout: Duration,
+    wait_for_tasks: bool,
+    task_timeout: Duration,
+    task_poll_interval: Duration,
+    max_retries: u32,
+    retry_delay: Duration,
+    max_retry_delay: Duration,
+    max_open_retries: u32,
+}
+
+impl From<MeilisearchSinkConfig> for ResolvedMeilisearchSinkConfig {
+    fn from(config: MeilisearchSinkConfig) -> Self {
+        let primary_key = config
+            .primary_key
+            .filter(|value| !value.trim().is_empty())
+            .unwrap_or_else(|| DEFAULT_PRIMARY_KEY.to_string());
+        let document_action = config.document_action.unwrap_or_default();
+        let create_index_if_not_exists = config
+            .create_index_if_not_exists
+            .unwrap_or(DEFAULT_CREATE_INDEX_IF_NOT_EXISTS);
+        let include_metadata = 
config.include_metadata.unwrap_or(DEFAULT_INCLUDE_METADATA);
+        let batch_size = 
config.batch_size.unwrap_or(DEFAULT_BATCH_SIZE).max(1);
+        let timeout = parse_duration(config.timeout.as_deref(), 
DEFAULT_TIMEOUT);
+        let wait_for_tasks = 
config.wait_for_tasks.unwrap_or(DEFAULT_WAIT_FOR_TASKS);
+        let task_timeout = parse_duration(config.task_timeout.as_deref(), 
DEFAULT_TASK_TIMEOUT);
+        let task_poll_interval = parse_duration(
+            config.task_poll_interval.as_deref(),
+            DEFAULT_TASK_POLL_INTERVAL,
+        );
+        let max_retries = config.max_retries.unwrap_or(DEFAULT_MAX_RETRIES);
+        let mut retry_delay = parse_duration(config.retry_delay.as_deref(), 
DEFAULT_RETRY_DELAY);
+        let mut max_retry_delay =
+            parse_duration(config.max_retry_delay.as_deref(), 
DEFAULT_MAX_RETRY_DELAY);
+        if retry_delay > max_retry_delay {
+            warn!(
+                "Meilisearch sink retry_delay ({:?}) exceeds max_retry_delay 
({:?}). Swapping values.",
+                retry_delay, max_retry_delay
+            );
+            std::mem::swap(&mut retry_delay, &mut max_retry_delay);
+        }
+        let max_open_retries = 
config.max_open_retries.unwrap_or(DEFAULT_MAX_OPEN_RETRIES);
+
+        Self {
+            url: config.url,
+            index: config.index,
+            api_key: config.api_key,
+            primary_key,
+            document_action,
+            create_index_if_not_exists,
+            include_metadata,
+            batch_size,
+            timeout,
+            wait_for_tasks,
+            task_timeout,
+            task_poll_interval,
+            max_retries,
+            retry_delay,
+            max_retry_delay,
+            max_open_retries,
+        }
+    }
+}
+
+impl MeilisearchSink {
+    pub fn new(id: u32, config: MeilisearchSinkConfig) -> Self {
+        Self {
+            id,
+            config: config.into(),
+            client: None,
+            state: Mutex::new(State {
+                invocations_count: 0,
+                documents_enqueued: 0,
+                documents_confirmed: 0,
+                errors_count: 0,
+            }),
+        }
+    }
+
+    fn create_client(&self) -> Result<Client, Error> {
+        let url = normalize_host(&self.config.url)?;
+        let api_key = self.config.api_key.as_ref().map(|key| 
key.expose_secret());
+        Client::new(url, api_key).map_err(|error| {
+            Error::Connection(format!("Failed to create Meilisearch client: 
{error}"))
+        })
+    }
+
+    async fn check_connectivity(&self, client: &Client) -> Result<(), Error> {
+        let mut retries = 0u32;
+
+        loop {
+            let result = tokio::time::timeout(self.config.timeout, 
client.health()).await;
+            match result {
+                Ok(Ok(health)) if health.status == "available" => return 
Ok(()),
+                Ok(Ok(health)) => {
+                    if retries >= self.config.max_open_retries {
+                        return Err(Error::Connection(format!(
+                            "Meilisearch health check returned status '{}'",
+                            health.status
+                        )));
+                    }
+                    retries += 1;
+                    let delay = jitter(exponential_backoff(
+                        self.config.retry_delay,
+                        retries,
+                        self.config.max_retry_delay,
+                    ));
+                    warn!(
+                        "Meilisearch health check returned status '{}' (retry 
{}/{}). Retrying in {:?}...",
+                        health.status, retries, self.config.max_open_retries, 
delay
+                    );
+                    sleep(delay).await;
+                }
+                Ok(Err(error)) => {
+                    let should_retry =
+                        retries < self.config.max_open_retries && 
is_transient_sdk_error(&error);
+                    if !should_retry {
+                        return Err(map_sdk_error(error));
+                    }
+                    retries += 1;
+                    let delay = jitter(exponential_backoff(
+                        self.config.retry_delay,
+                        retries,
+                        self.config.max_retry_delay,
+                    ));
+                    warn!(
+                        "Meilisearch health check failed (retry {}/{}): {}. 
Retrying in {:?}...",
+                        retries, self.config.max_open_retries, error, delay
+                    );
+                    sleep(delay).await;
+                }
+                Err(_) => {
+                    if retries >= self.config.max_open_retries {
+                        return Err(Error::HttpRequestFailed(format!(
+                            "Meilisearch health check timed out after {:?}",
+                            self.config.timeout
+                        )));
+                    }
+                    retries += 1;
+                    let delay = jitter(exponential_backoff(
+                        self.config.retry_delay,
+                        retries,
+                        self.config.max_retry_delay,
+                    ));
+                    warn!(
+                        "Meilisearch health check timed out after {:?} (retry 
{}/{}). Retrying in {:?}...",
+                        self.config.timeout, retries, 
self.config.max_open_retries, delay
+                    );
+                    sleep(delay).await;
+                }
+            }
+        }
+    }
+
+    async fn ensure_index_exists(&self, client: &Client) -> Result<(), Error> {
+        match self.get_index_if_exists(client).await? {
+            Some(index) => {
+                info!("Meilisearch index '{}' already exists", 
self.config.index);
+                if let Some(primary_key) = index.primary_key.as_deref()
+                    && primary_key != self.config.primary_key
+                {
+                    warn!(
+                        "Meilisearch index '{}' primary key '{}' differs from 
configured primary key '{}'",
+                        self.config.index, primary_key, self.config.primary_key
+                    );
+                } else if index.primary_key.is_none() {
+                    warn!(
+                        "Meilisearch index '{}' does not currently have a 
primary key. Configured primary key '{}' will be sent with document indexing 
requests.",
+                        self.config.index, self.config.primary_key
+                    );
+                }
+                Ok(())
+            }
+            None if self.config.create_index_if_not_exists => 
self.create_index(client).await,
+            None => Err(Error::InitError(format!(
+                "Meilisearch index '{}' does not exist and 
create_index_if_not_exists=false",
+                self.config.index
+            ))),
+        }
+    }
+
+    async fn get_index_if_exists(&self, client: &Client) -> 
Result<Option<Index>, Error> {
+        self.retry_sdk_open_operation("get index", || async {
+            match client.get_index(&self.config.index).await {
+                Ok(index) => Ok(Some(index)),
+                Err(error) if is_index_not_found(&error) => Ok(None),
+                Err(error) => Err(error),
+            }
+        })
+        .await
+    }
+
+    async fn create_index(&self, client: &Client) -> Result<(), Error> {
+        info!(
+            "Creating Meilisearch index '{}' with primary key '{}'",
+            self.config.index, self.config.primary_key
+        );
+
+        let task = self
+            .retry_sdk_open_operation("create index", || {
+                client.create_index(&self.config.index, 
Some(&self.config.primary_key))
+            })
+            .await?;
+        self.wait_for_index_creation_task(client, task).await?;
+
+        info!("Created Meilisearch index '{}'", self.config.index);
+        Ok(())
+    }
+
+    fn prepare_document(
+        &self,
+        topic_metadata: &TopicMetadata,
+        messages_metadata: &MessagesMetadata,
+        message: ConsumedMessage,
+    ) -> Result<Value, Error> {
+        let ConsumedMessage {
+            id: message_id,
+            offset,
+            checksum,
+            timestamp,
+            origin_timestamp,
+            headers,
+            payload,
+        } = message;
+
+        let mut document = match payload {
+            Payload::Json(value) => {
+                
Self::document_from_json_value(owned_value_to_serde_json(&value))
+            }
+            Payload::Raw(bytes) => {
+                let mut bytes_copy = bytes.clone();
+                match simd_json::from_slice::<simd_json::OwnedValue>(&mut 
bytes_copy) {
+                    Ok(value) => 
Self::document_from_json_value(owned_value_to_serde_json(&value)),
+                    Err(_) => Map::from_iter([
+                        (
+                            "data".to_string(),
+                            
Value::String(general_purpose::STANDARD.encode(&bytes)),
+                        ),
+                        ("data_type".to_string(), 
Value::String("raw".to_string())),
+                        (
+                            "data_encoding".to_string(),
+                            Value::String(ENCODING_BASE64.to_string()),
+                        ),
+                    ]),
+                }
+            }
+            Payload::Text(text) => Map::from_iter([
+                ("text".to_string(), Value::String(text)),
+                ("data_type".to_string(), Value::String("text".to_string())),
+            ]),
+            _ => {
+                return Err(Error::InvalidRecordValue(format!(
+                    "Unsupported payload format for Meilisearch sink: {}",
+                    messages_metadata.schema
+                )));
+            }
+        };
+
+        let mut generated_id = None;
+        if !document.contains_key(self.config.primary_key.as_str()) {
+            let value = generated_document_id_from_parts(
+                topic_metadata,
+                messages_metadata,
+                offset,
+                message_id,
+            )?;
+            document.insert(
+                self.config.primary_key.clone(),
+                Value::String(value.clone()),
+            );
+            generated_id = Some(value);
+        }
+
+        if self.config.include_metadata {
+            if self.config.primary_key != DEFAULT_PRIMARY_KEY
+                && !document.contains_key(DEFAULT_PRIMARY_KEY)
+            {
+                let id = match &generated_id {
+                    Some(id) => id.clone(),
+                    None => generated_document_id_from_parts(
+                        topic_metadata,
+                        messages_metadata,
+                        offset,
+                        message_id,
+                    )?,
+                };
+                document.insert(DEFAULT_PRIMARY_KEY.to_string(), 
Value::String(id));
+            }
+            insert_metadata_field(
+                &mut document,
+                "iggy_message_id",
+                Value::String(message_id.to_string()),
+            );
+            insert_metadata_field(&mut document, "iggy_offset", 
Value::from(offset));

Review Comment:
   lib.rs:411,427,428,432 emit offset/checksum/timestamp as raw JSON numbers; 
Meilisearch/JS store as f64 → values >2^53 corrupt at rest (checksum spans full 
u64). message_id is correctly stringified (:409),**fix:** perf warns 
stringifying in the loop adds allocs. Fix: stringify checksum only (widest 
range, used for integrity), document offset/timestamp. 



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