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


##########
core/connectors/sinks/meilisearch_sink/src/lib.rs:
##########
@@ -0,0 +1,1154 @@
+// 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 retry_delay = parse_duration(config.retry_delay.as_deref(), 
DEFAULT_RETRY_DELAY);
+        let max_retry_delay =
+            parse_duration(config.max_retry_delay.as_deref(), 
DEFAULT_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 health = self
+            .retry_sdk_open_operation("health check", || client.health())
+            .await?;
+        if health.status == "available" {
+            return Ok(());
+        }
+
+        Err(Error::Connection(format!(
+            "Meilisearch health check returned status '{}'",
+            health.status
+        )))
+    }
+
+    async fn ensure_index_exists(&self, client: &Client) -> Result<(), Error> {
+        match self.get_index_if_exists(client).await? {
+            Some(_) => {
+                info!("Meilisearch index '{}' already exists", 
self.config.index);
+                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();

Review Comment:
   let mut bytes_copy = bytes.clone() for Payload::Raw is unnecessary. 
ConsumedMessage is moved into prepare_document(), so bytes is already owned. 
simd_json requires &mut [u8]. **Fix**: let 
     Payload::Raw(mut bytes) = payload, pass &mut bytes directly, use bytes for 
base64 fallback. Eliminates full payload clone per raw message.



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