slbotbm commented on code in PR #3404:
URL: https://github.com/apache/iggy/pull/3404#discussion_r3396480225


##########
core/connectors/sources/meilisearch_source/src/lib.rs:
##########
@@ -0,0 +1,444 @@
+// 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, 
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::{str::FromStr, time::Duration};
+use tokio::{sync::Mutex, time::sleep};
+use tracing::info;
+
+source_connector!(MeilisearchSource);
+
+const CONNECTOR_NAME: &str = "Meilisearch source";
+const DEFAULT_BATCH_SIZE: usize = 100;
+const DEFAULT_POLLING_INTERVAL: &str = "5s";
+
+#[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 sort: Option<Vec<String>>,
+    pub batch_size: Option<usize>,
+    pub polling_interval: Option<String>,
+    pub timeout: Option<String>,
+    pub include_metadata: Option<bool>,
+}
+
+#[derive(Debug)]
+pub struct MeilisearchSource {
+    id: u32,
+    config: MeilisearchSourceConfig,
+    client: Option<Client>,
+    batch_size: usize,
+    polling_interval: Duration,
+    include_metadata: bool,
+    state: Mutex<State>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct State {
+    next_offset: usize,
+    documents_produced: usize,
+    poll_count: usize,
+}
+
+impl MeilisearchSource {
+    pub fn new(id: u32, config: MeilisearchSourceConfig, state: 
Option<ConnectorState>) -> 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(false);
+        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}. \
+                     Next offset: {}, documents produced: {}, poll count: {}",
+                    state.next_offset, state.documents_produced, 
state.poll_count
+                );
+            });
+
+        Self {
+            id,
+            config,
+            client: None,
+            batch_size,
+            polling_interval,
+            include_metadata,
+            state: Mutex::new(restored_state.unwrap_or(State {
+                next_offset: 0,
+                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 = client.health().await.map_err(map_sdk_error)?;
+        if health.status == "available" {
+            return Ok(());
+        }
+
+        Err(Error::Connection(format!(
+            "Meilisearch health check returned status '{}'",
+            health.status
+        )))
+    }
+
+    async fn search_documents(&self, client: &Client) -> 
Result<Vec<ProducedMessage>, Error> {
+        let offset = {
+            let state = self.state.lock().await;
+            state.next_offset
+        };
+        let filter_expression = self.filter_expression()?;
+        let sort_refs = self.sort_refs();
+        let index = client.index(&self.config.index);
+        let mut query = index.search();
+        query
+            .with_query(self.config.query.as_deref().unwrap_or_default())
+            .with_offset(offset)
+            .with_limit(self.batch_size);

Review Comment:
   This code saves `next_offset` and advances it by `messages.len()` next time 
a poll happens. This is only stable if the result set is immutable between 
polls. Inserting / deleting documents at offsets already polled will lead to 
re-ordering of documents, and thus to silent skips or re-delivery of documents 
on the connector's side.



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