ryerraguntla commented on code in PR #3497: URL: https://github.com/apache/iggy/pull/3497#discussion_r3456171832
########## core/connectors/sinks/meilisearch_sink/src/lib.rs: ########## @@ -0,0 +1,1196 @@ +// 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 mut retries = 0u32; + + loop { + let health = self + .retry_sdk_open_operation("health check", || client.health()) + .await?; + if health.status == "available" { + return Ok(()); + } + + 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; + } + } + + 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(mut bytes) => { + match simd_json::from_slice::<simd_json::OwnedValue>(&mut bytes) { + 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)); + insert_metadata_field( + &mut document, + "iggy_stream", + Value::from(topic_metadata.stream.as_str()), + ); + insert_metadata_field( + &mut document, + "iggy_topic", + Value::from(topic_metadata.topic.as_str()), + ); + insert_metadata_field( + &mut document, + "iggy_partition", + Value::from(messages_metadata.partition_id), + ); + insert_metadata_field(&mut document, "iggy_checksum", Value::from(checksum)); + insert_metadata_field(&mut document, "iggy_timestamp", Value::from(timestamp)); + insert_metadata_field( + &mut document, + "iggy_origin_timestamp", + Value::from(origin_timestamp), + ); + insert_metadata_field( + &mut document, + "iggy_ingested_at", + Value::from(IggyTimestamp::now().as_millis() as i64), + ); + if let Some(headers) = &headers + && let Ok(headers_value) = serde_json::to_value(headers) + { + insert_metadata_field(&mut document, "iggy_headers", headers_value); + } + } + + Ok(Value::Object(document)) + } + + fn document_from_json_value(value: Value) -> Map<String, Value> { + match value { + Value::Object(object) => object, + other => { + let mut object = Map::new(); + object.insert("value".to_string(), other); + object + } + } + } + + async fn index_documents( + &self, + client: &Client, + documents: Vec<Value>, + ) -> Result<usize, PartialIndexError> { + let mut accepted = 0usize; + for chunk in documents.chunks(self.config.batch_size) { + match self.index_document_chunk(client, chunk).await { + Ok(indexed) => accepted += indexed, + Err(partial_error) => { + return Err(PartialIndexError { + accepted: accepted + partial_error.accepted, + failed: partial_error.failed, + error: partial_error.error, + }); + } + } + } + Ok(accepted) + } + + async fn index_document_chunk( + &self, + client: &Client, + documents: &[Value], + ) -> Result<usize, PartialIndexError> { + if documents.is_empty() { + return Ok(0); + } + + let index = client.index(&self.config.index); + let task = match self.config.document_action { + MeilisearchDocumentAction::Replace => { + self.retry_sdk_operation("add or replace documents", || { + index.add_or_replace(documents, Some(&self.config.primary_key)) + }) + .await + } + MeilisearchDocumentAction::Update => { + self.retry_sdk_operation("add or update documents", || { + index.add_or_update(documents, Some(&self.config.primary_key)) + }) + .await + } + } + .map_err(|error| PartialIndexError { + accepted: 0, + failed: documents.len(), + error, + })?; + self.wait_for_task(client, task) Review Comment: task-wait failure returns PartialIndexError { accepted: documents.len(), failed: 0 }; consume() at line 765 increments documents_enqueued by those "accepted" and returns Err; runtime retries; with document_action=update, all previously-submitted docs get a second partial update applied. **Fix:** swap to accepted: 0, failed: documents.len() on task-wait failure. -- 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]
