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


##########
core/connectors/sources/meilisearch_source/src/lib.rs:
##########
@@ -0,0 +1,898 @@
+// 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 iggy_connector_sdk::{
+    ConnectorState, Error, ProducedMessage, ProducedMessages, Schema, Source,
+    retry::{exponential_backoff, jitter, parse_duration},
+    source_connector,
+};
+use meilisearch_sdk::{
+    client::Client,
+    errors::{
+        Error as MeilisearchSdkError, ErrorCode as MeilisearchErrorCode,
+        ErrorType as MeilisearchErrorType,
+    },
+};
+use secrecy::{ExposeSecret, SecretString};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use std::{future::Future, time::Duration};
+use tokio::{sync::Mutex, time::sleep};
+use tracing::{info, warn};
+use url::Url;
+
+source_connector!(MeilisearchSource);
+
+const CONNECTOR_NAME: &str = "Meilisearch source";
+const DEFAULT_BATCH_SIZE: usize = 100;
+const DEFAULT_POLLING_INTERVAL: &str = "5s";
+const DEFAULT_INCLUDE_METADATA: bool = false;
+const DEFAULT_TIMEOUT: &str = "30s";
+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 PRIMARY_KEY_SORT_DIRECTION: &str = "asc";
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct MeilisearchSourceConfig {
+    pub url: String,
+    pub index: String,
+    #[serde(serialize_with = 
"iggy_common::serde_secret::serialize_optional_secret")]
+    pub api_key: Option<SecretString>,
+    pub query: Option<String>,
+    pub filter: Option<Value>,
+    pub batch_size: Option<usize>,
+    pub polling_interval: Option<String>,
+    pub include_metadata: Option<bool>,
+    pub timeout: 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 MeilisearchSource {
+    id: u32,
+    config: ResolvedMeilisearchSourceConfig,
+    client: Option<Client>,
+    primary_key: Option<String>,
+    primary_key_sort: Option<String>,
+    filter_expression: Option<String>,
+    state: Mutex<State>,
+}
+
+#[derive(Debug)]
+struct ResolvedMeilisearchSourceConfig {
+    url: String,
+    index: String,
+    api_key: Option<SecretString>,
+    query: String,
+    filter: Option<Value>,
+    batch_size: usize,
+    polling_interval: Duration,
+    include_metadata: bool,
+    timeout: Duration,
+    max_retries: u32,
+    retry_delay: Duration,
+    max_retry_delay: Duration,
+    max_open_retries: u32,
+}
+
+impl From<MeilisearchSourceConfig> for ResolvedMeilisearchSourceConfig {
+    fn from(config: MeilisearchSourceConfig) -> Self {
+        let batch_size = 
config.batch_size.unwrap_or(DEFAULT_BATCH_SIZE).max(1);
+        let polling_interval =
+            parse_duration(config.polling_interval.as_deref(), 
DEFAULT_POLLING_INTERVAL);
+        let include_metadata = 
config.include_metadata.unwrap_or(DEFAULT_INCLUDE_METADATA);
+        let timeout = parse_duration(config.timeout.as_deref(), 
DEFAULT_TIMEOUT);
+        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,
+            query: config.query.unwrap_or_default(),
+            filter: config.filter,
+            batch_size,
+            polling_interval,
+            include_metadata,
+            timeout,
+            max_retries,
+            retry_delay,
+            max_retry_delay,
+            max_open_retries,
+        }
+    }
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct State {
+    last_primary_key: Option<Value>,
+    documents_produced: usize,
+    poll_count: usize,
+}
+
+impl MeilisearchSource {
+    pub fn new(id: u32, config: MeilisearchSourceConfig, state: 
Option<ConnectorState>) -> Self {
+        let restored_state = state
+            .and_then(|state| state.deserialize::<State>(CONNECTOR_NAME, id))
+            .inspect(|state| {
+                info!(
+                    "Restored state for {CONNECTOR_NAME} connector with ID: 
{id}. \
+                     Last primary key: {:?}, documents produced: {}, poll 
count: {}",
+                    state.last_primary_key, state.documents_produced, 
state.poll_count
+                );
+            });
+
+        Self {
+            id,
+            config: config.into(),
+            client: None,
+            primary_key: None,
+            primary_key_sort: None,
+            filter_expression: None,
+            state: Mutex::new(restored_state.unwrap_or(State {
+                last_primary_key: None,
+                documents_produced: 0,
+                poll_count: 0,
+            })),
+        }
+    }
+
+    fn serialize_state(&self, state: &State) -> Option<ConnectorState> {
+        ConnectorState::serialize(state, CONNECTOR_NAME, self.id)
+    }
+
+    fn create_client(&self) -> Result<Client, Error> {
+        let host = normalize_host(&self.config.url)?;
+        let api_key = self
+            .config
+            .api_key
+            .as_ref()
+            .map(|key| key.expose_secret().to_string());
+
+        Client::new(host, 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 get_primary_key(&self, client: &Client) -> Result<String, Error> {
+        let primary_key = self
+            .retry_sdk_open_operation("get primary key", || async {
+                let mut index = client.get_index(&self.config.index).await?;
+                index
+                    .get_primary_key()
+                    .await
+                    .map(|primary_key| primary_key.map(str::to_string))
+            })
+            .await?;
+
+        primary_key.ok_or_else(|| {
+            Error::InvalidConfigValue(format!(
+                "Meilisearch index '{}' must define a primary key for stable 
source polling",
+                self.config.index
+            ))
+        })
+    }
+
+    async fn search_documents(
+        &self,
+        client: &Client,
+    ) -> Result<(Vec<ProducedMessage>, bool), Error> {
+        let last_primary_key = {
+            let state = self.state.lock().await;
+            state.last_primary_key.clone()
+        };
+        let primary_key = self.primary_key.as_deref().ok_or_else(|| {
+            Error::Connection("Meilisearch primary key is not 
initialized".to_string())
+        })?;
+        let sort = self.primary_key_sort.as_deref().ok_or_else(|| {
+            Error::Connection("Meilisearch primary key sort is not 
initialized".to_string())
+        })?;
+        let cursor_filter = cursor_filter_expression(primary_key, 
last_primary_key.as_ref())?;
+        let combined_filter =
+            combine_filter_expressions(self.filter_expression.as_deref(), 
cursor_filter);
+        let sort_refs = [sort];
+        let index = client.index(&self.config.index);
+        let mut query = index.search();
+        query
+            .with_query(&self.config.query)
+            .with_limit(self.config.batch_size)
+            .with_sort(&sort_refs);
+
+        if let Some(filter) = &combined_filter {
+            query.with_filter(filter);
+        }
+
+        let results = self
+            .retry_sdk_operation("search documents", || {
+                let query = query.clone();
+                async move { query.execute::<Value>().await }
+            })
+            .await?;
+        let documents: Vec<Value> = results.hits.into_iter().map(|hit| 
hit.result).collect();
+        let primary_keys = document_primary_keys(&documents, primary_key)?;
+        let last_document_primary_key = primary_keys.into_iter().last();
+        let messages = self.documents_to_messages(documents)?;
+        let state_changed = last_document_primary_key.is_some();
+
+        let mut state = self.state.lock().await;
+        if let Some(primary_key) = last_document_primary_key {
+            state.last_primary_key = Some(primary_key);
+        }
+        state.documents_produced += messages.len();
+        state.poll_count += 1;
+
+        Ok((messages, state_changed))
+    }
+
+    fn documents_to_messages(&self, documents: Vec<Value>) -> 
Result<Vec<ProducedMessage>, Error> {
+        documents
+            .into_iter()
+            .map(|document| {
+                let payload = if self.config.include_metadata {
+                    json!({
+                        "document": document,
+                        "meilisearch": {
+                            "index": self.config.index,
+                            "primary_key": self.primary_key.as_deref(),
+                        }
+                    })
+                } else {
+                    document
+                };
+
+                serde_json::to_vec(&payload)
+                    .map(|payload| ProducedMessage {
+                        id: None,
+                        checksum: None,
+                        timestamp: None,
+                        origin_timestamp: None,
+                        headers: None,
+                        payload,
+                    })
+                    .map_err(|error| {
+                        Error::Serialization(format!(
+                            "Failed to serialize Meilisearch document: {error}"
+                        ))
+                    })
+            })
+            .collect()
+    }
+
+    async fn retry_sdk_operation<T, Fut, Op>(
+        &self,
+        operation: &str,
+        operation_fn: Op,
+    ) -> Result<T, Error>
+    where
+        Op: FnMut() -> Fut,
+        Fut: Future<Output = Result<T, MeilisearchSdkError>>,
+    {
+        self.retry_sdk_operation_with_attempts(operation, 
self.config.max_retries, operation_fn)
+            .await
+    }
+
+    async fn retry_sdk_open_operation<T, Fut, Op>(
+        &self,
+        operation: &str,
+        operation_fn: Op,
+    ) -> Result<T, Error>
+    where
+        Op: FnMut() -> Fut,
+        Fut: Future<Output = Result<T, MeilisearchSdkError>>,
+    {
+        self.retry_sdk_operation_with_attempts(
+            operation,
+            self.config.max_open_retries,
+            operation_fn,
+        )
+        .await
+    }
+
+    async fn retry_sdk_operation_with_attempts<T, Fut, Op>(
+        &self,
+        operation: &str,
+        max_retries: u32,
+        mut operation_fn: Op,
+    ) -> Result<T, Error>
+    where
+        Op: FnMut() -> Fut,
+        Fut: Future<Output = Result<T, MeilisearchSdkError>>,
+    {
+        let mut retries = 0u32;
+
+        loop {
+            let result = tokio::time::timeout(self.config.timeout, 
operation_fn()).await;
+            match result {
+                Ok(Ok(value)) => return Ok(value),
+                Ok(Err(error)) => {
+                    if retries >= max_retries || 
!is_transient_sdk_error(&error) {
+                        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 {operation} failed (retry 
{retries}/{max_retries}): {error}. Retrying in {delay:?}..."
+                    );
+                    sleep(delay).await;
+                }
+                Err(_) => {
+                    if retries >= max_retries {
+                        return Err(Error::HttpRequestFailed(format!(
+                            "Meilisearch {operation} 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 {operation} timed out after {:?} (retry 
{retries}/{max_retries}). Retrying in {delay:?}...",
+                        self.config.timeout
+                    );
+                    sleep(delay).await;
+                }
+            }
+        }
+    }
+}
+
+#[async_trait]
+impl Source for MeilisearchSource {
+    async fn open(&mut self) -> Result<(), Error> {
+        let sanitized_url = sanitize_url_for_logging(&self.config.url);
+        info!(
+            "Opening Meilisearch source connector with ID: {} for URL: {}, 
index: {}",
+            self.id, sanitized_url, self.config.index
+        );
+
+        let filter_expression = 
filter_expression(self.config.filter.as_ref())?;
+        let client = self.create_client()?;
+        self.check_connectivity(&client).await?;
+        let primary_key = self.get_primary_key(&client).await?;
+        info!(
+            "Meilisearch source connector with ID: {} requires integer primary 
key values for cursor pagination. Index: {}, primary key: {}",
+            self.id, self.config.index, primary_key
+        );
+        self.primary_key_sort = 
Some(format!("{primary_key}:{PRIMARY_KEY_SORT_DIRECTION}"));
+        self.filter_expression = filter_expression;
+        self.primary_key = Some(primary_key);
+        self.client = Some(client);
+
+        info!(
+            "Successfully opened Meilisearch source connector with ID: {}",
+            self.id
+        );
+        Ok(())
+    }
+
+    async fn poll(&self) -> Result<ProducedMessages, Error> {
+        sleep(self.config.polling_interval).await;
+        let client = self
+            .client
+            .as_ref()
+            .ok_or_else(|| Error::Connection("Meilisearch client not 
initialized".to_string()))?;
+        let (messages, state_changed) = self.search_documents(client).await?;
+        let persisted_state = if state_changed {
+            let state = self.state.lock().await;
+            self.serialize_state(&state)
+        } else {
+            None
+        };
+
+        Ok(ProducedMessages {
+            schema: Schema::Json,
+            messages,
+            state: persisted_state,
+        })
+    }
+
+    async fn close(&mut self) -> Result<(), Error> {
+        {
+            let state = self.state.lock().await;
+            info!(
+                "Meilisearch source connector with ID: {} is closing. Stats: 
{} documents produced, {} polls executed",
+                self.id, state.documents_produced, state.poll_count
+            );
+        }
+
+        self.client = None;
+        info!(
+            "Meilisearch source connector with ID: {} is closed.",
+            self.id
+        );
+        Ok(())
+    }
+}
+
+fn normalize_host(host: &str) -> Result<String, Error> {
+    let trimmed = host.trim();
+    if trimmed.is_empty() {
+        return Err(Error::Connection(
+            "Invalid Meilisearch URL: host cannot be empty".to_string(),
+        ));
+    }
+
+    let with_scheme = if trimmed.starts_with("http://";) || 
trimmed.starts_with("https://";) {
+        trimmed.to_string()
+    } else {
+        format!("http://{trimmed}";)
+    };
+
+    let mut url = Url::parse(&with_scheme)
+        .map_err(|error| Error::Connection(format!("Invalid Meilisearch URL: 
{error}")))?;
+    if url.host_str().is_none() {
+        return Err(Error::Connection(
+            "Invalid Meilisearch URL: host cannot be empty".to_string(),
+        ));
+    }
+    if !matches!(url.scheme(), "http" | "https") {
+        return Err(Error::Connection(format!(
+            "Invalid Meilisearch URL scheme '{}': expected http or https",
+            url.scheme()
+        )));
+    }
+    if !matches!(url.path(), "" | "/") || url.query().is_some() || 
url.fragment().is_some() {
+        return Err(Error::Connection(
+            "Invalid Meilisearch URL: path, query, and fragment components are 
not supported"
+                .to_string(),
+        ));
+    }
+
+    url.set_path("");
+    url.set_query(None);
+    url.set_fragment(None);
+    let mut normalized = url.to_string();
+    while normalized.ends_with('/') {
+        normalized.pop();
+    }
+    Ok(normalized)
+}
+
+fn sanitize_url_for_logging(host: &str) -> String {
+    let Ok(normalized) = normalize_host(host) else {
+        return "<invalid-url>".to_string();
+    };
+    let Some((scheme, rest)) = normalized.split_once("://") else {
+        return normalized;
+    };
+    let authority_end = rest.find('/').unwrap_or(rest.len());
+    let (authority, path) = rest.split_at(authority_end);
+    if let Some((_, host)) = authority.rsplit_once('@') {
+        format!("{scheme}://<redacted>@{host}{path}")
+    } else {
+        normalized
+    }
+}
+
+fn filter_array_expression(filters: &[Value], nested: bool) -> 
Result<Option<String>, Error> {
+    let separator = if nested { " OR " } else { " AND " };
+    let mut expressions = Vec::with_capacity(filters.len());
+
+    for filter in filters {
+        match filter {
+            Value::String(filter) if !filter.is_empty() => 
expressions.push(filter.clone()),
+            Value::Array(filters) => {
+                if let Some(filter) = filter_array_expression(filters, true)? {
+                    expressions.push(format!("({filter})"));
+                }
+            }
+            _ => {
+                return Err(Error::InvalidConfigValue(
+                    "Meilisearch filter arrays must contain only strings or 
nested arrays"
+                        .to_string(),
+                ));
+            }
+        }
+    }
+
+    if expressions.is_empty() {
+        Ok(None)
+    } else {
+        Ok(Some(expressions.join(separator)))
+    }
+}
+
+fn filter_expression(filter: Option<&Value>) -> Result<Option<String>, Error> {
+    let Some(filter) = filter.filter(|value| !value.is_null()) else {
+        return Ok(None);
+    };
+
+    match filter {
+        Value::String(filter) if !filter.is_empty() => 
Ok(Some(filter.clone())),
+        Value::Array(filters) => filter_array_expression(filters, false),
+        _ => Err(Error::InvalidConfigValue(
+            "Meilisearch filter must be a string or an array of 
strings/arrays".to_string(),
+        )),
+    }
+}
+
+fn combine_filter_expressions(
+    user_filter: Option<&str>,
+    cursor_filter: Option<String>,
+) -> Option<String> {
+    match (user_filter, cursor_filter) {
+        (Some(user_filter), Some(cursor_filter)) => {
+            Some(format!("({user_filter}) AND ({cursor_filter})"))
+        }
+        (Some(user_filter), None) => Some(user_filter.to_string()),
+        (None, Some(cursor_filter)) => Some(cursor_filter),
+        (None, None) => None,
+    }
+}
+
+fn cursor_filter_expression(
+    primary_key: &str,
+    last_primary_key: Option<&Value>,
+) -> Result<Option<String>, Error> {
+    last_primary_key
+        .map(|value| {
+            primary_key_filter_literal(value).map(|literal| 
format!("{primary_key} > {literal}"))
+        })
+        .transpose()
+}
+
+fn primary_key_filter_literal(value: &Value) -> Result<String, Error> {
+    match value {
+        Value::Number(number) if number.is_i64() || number.is_u64() => 
serde_json::to_string(value)
+            .map_err(|error| {
+                Error::Serialization(format!(
+                    "Failed to serialize Meilisearch primary key: {error}"
+                ))
+            }),
+        Value::Number(_) => Err(Error::InvalidConfigValue(
+            "Meilisearch source primary key values must be integers for cursor 
pagination"
+                .to_string(),
+        )),
+        _ => Err(Error::InvalidConfigValue(
+            "Meilisearch source primary key values must be numbers for cursor 
pagination"
+                .to_string(),
+        )),
+    }
+}
+
+fn document_primary_key(document: &Value, primary_key: &str) -> Result<Value, 
Error> {
+    let value = document.get(primary_key).ok_or_else(|| {
+        Error::InvalidConfigValue(format!(
+            "Meilisearch document is missing primary key '{primary_key}'"
+        ))
+    })?;
+    primary_key_filter_literal(value)?;
+    Ok(value.clone())
+}
+
+fn document_primary_keys(documents: &[Value], primary_key: &str) -> 
Result<Vec<Value>, Error> {

Review Comment:
   lib.rs:607-611 + lib.rs:418 — bad-PK doc in mid-batch permanently stalls 
connector  document_primary_keys short-circuits on first 
Err(InvalidConfigValue). poll() returns that error. Runtime stops connector 
(permanent error type). Cursor unchanged. Restart re-fetches same batch, same 
error.  Stuck loop with no recovery. Fix: skip bad-PK docs with a warn log and 
advance cursor to last good integer PK seen, OR return good prefix up to bad 
doc.



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