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


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

Review Comment:
   check_connectivity fails immediately on non-"available" health  
retry_sdk_open_operation only retries transient SDK errors. If Meilisearch 
returns 200 OK with {"status":"unknown"} (during startup), the retry loop never 
fires; check_connectivity returns Err(Connection(...))  immediately. open() 
fails on a transient condition. Meilisearch can transiently return 
non-available status during index loading. **Fix:** add inner retry loop around 
the status check up to max_open_retries,  mirroring the sink pattern.



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