leekeiabstraction commented on code in PR #216:
URL: https://github.com/apache/fluss-rust/pull/216#discussion_r2749397934


##########
crates/fluss/src/client/lookup/lookup_client.rs:
##########
@@ -0,0 +1,203 @@
+// 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.
+
+//! Lookup client that batches multiple lookups together for improved 
throughput.
+//!
+//! This client achieves parity with the Java client by:
+//! - Queuing lookup operations instead of sending them immediately
+//! - Batching multiple lookups to the same server/bucket
+//! - Running a background sender task to process batches
+
+use super::{LookupQuery, LookupQueue};
+use crate::client::lookup::lookup_sender::LookupSender;
+use crate::client::metadata::Metadata;
+use crate::config::Config;
+use crate::error::{Error, Result};
+use crate::metadata::{TableBucket, TablePath};
+use log::{debug, error};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::Duration;
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+
+/// A client that lookups values from the server with batching support.
+///
+/// The lookup client uses a queue and background sender to batch multiple
+/// lookup operations together, reducing network round trips and improving
+/// throughput.
+///
+/// # Example
+///
+/// ```ignore
+/// let lookup_client = LookupClient::new(config, metadata);
+/// let result = lookup_client.lookup(table_path, table_bucket, 
key_bytes).await?;
+/// ```
+pub struct LookupClient {
+    /// Channel to send lookup requests to the queue
+    lookup_tx: mpsc::Sender<LookupQuery>,
+    /// Handle to the sender task
+    sender_handle: Option<JoinHandle<()>>,
+    /// Shutdown signal sender
+    shutdown_tx: mpsc::Sender<()>,
+    /// Whether the client is closed
+    closed: AtomicBool,
+}
+
+impl LookupClient {
+    /// Creates a new lookup client.
+    pub fn new(config: &Config, metadata: Arc<Metadata>) -> Self {
+        // Extract configuration values
+        let queue_size = config.lookup_queue_size;
+        let max_batch_size = config.lookup_max_batch_size;
+        let batch_timeout_ms = config.lookup_batch_timeout_ms;
+        let max_inflight = config.lookup_max_inflight_requests;
+        let max_retries = config.lookup_max_retries;
+
+        // Create queue and channels
+        let (queue, lookup_tx, re_enqueue_tx) =
+            LookupQueue::new(queue_size, max_batch_size, batch_timeout_ms);
+
+        // Create sender
+        let mut sender =
+            LookupSender::new(metadata, queue, re_enqueue_tx, max_inflight, 
max_retries);
+
+        // Create shutdown channel
+        let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);
+
+        // Spawn sender task
+        let sender_handle = tokio::spawn(async move {
+            tokio::select! {
+                _ = sender.run() => {
+                    debug!("Lookup sender completed");
+                }
+                _ = shutdown_rx.recv() => {
+                    debug!("Lookup sender received shutdown signal");
+                    sender.initiate_close();
+                }
+            }
+        });
+
+        Self {
+            lookup_tx,
+            sender_handle: Some(sender_handle),
+            shutdown_tx,
+            closed: AtomicBool::new(false),
+        }
+    }
+
+    /// Looks up a value by its primary key.
+    ///
+    /// This method queues the lookup operation and returns a future that will
+    /// complete when the server responds. Multiple lookups may be batched 
together
+    /// for improved throughput.
+    ///
+    /// # Arguments
+    /// * `table_path` - The table path
+    /// * `table_bucket` - The table bucket
+    /// * `key_bytes` - The encoded primary key bytes
+    ///
+    /// # Returns
+    /// * `Ok(Some(bytes))` - The value bytes if found
+    /// * `Ok(None)` - If the key was not found
+    /// * `Err(Error)` - If the lookup fails
+    pub async fn lookup(
+        &self,
+        table_path: TablePath,
+        table_bucket: TableBucket,
+        key_bytes: Vec<u8>,

Review Comment:
   Use `bytes::Bytes` for this to remove an unnecessary copy (`to_vec`) in 
`Lookuper.lookup()`.



##########
crates/fluss/src/client/lookup/lookup_sender.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.
+
+//! Lookup sender that processes batched lookup requests.
+//!
+//! The sender runs as a background task, draining lookups from the queue,
+//! grouping them by destination server, and sending batched requests.
+
+use super::{LookupQuery, LookupQueue};
+use crate::client::metadata::Metadata;
+use crate::error::{Error, FlussError, Result};
+use crate::metadata::TableBucket;
+use crate::proto::LookupResponse;
+use crate::rpc::message::LookupRequest;
+use log::{debug, error, warn};
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::Duration;
+use tokio::sync::{Semaphore, mpsc};
+
+/// Lookup sender that batches and sends lookup requests.
+pub struct LookupSender {
+    /// Metadata for leader lookup
+    metadata: Arc<Metadata>,
+    /// The lookup queue to drain from
+    queue: LookupQueue,
+    /// Channel to re-enqueue failed lookups
+    re_enqueue_tx: mpsc::UnboundedSender<LookupQuery>,
+    /// Semaphore to limit in-flight requests
+    inflight_semaphore: Arc<Semaphore>,
+    /// Maximum number of retries
+    max_retries: i32,
+    /// Whether the sender is running
+    running: AtomicBool,
+    /// Whether to force close (abandon pending lookups)
+    force_close: AtomicBool,
+}
+
+/// A batch of lookups going to the same table bucket.
+struct LookupBatch {
+    table_bucket: TableBucket,
+    lookups: Vec<LookupQuery>,
+    keys: Vec<Vec<u8>>,
+}
+
+impl LookupBatch {
+    fn new(table_bucket: TableBucket) -> Self {
+        Self {
+            table_bucket,
+            lookups: Vec::new(),
+            keys: Vec::new(),
+        }
+    }
+
+    fn add_lookup(&mut self, lookup: LookupQuery) {
+        self.keys.push(lookup.key().to_vec());
+        self.lookups.push(lookup);
+    }
+
+    fn complete(&mut self, values: Vec<Option<Vec<u8>>>) {
+        if values.len() != self.lookups.len() {
+            let err_msg = format!(
+                "The number of return values ({}) does not match the number of 
lookups ({})",
+                values.len(),
+                self.lookups.len()
+            );
+            for lookup in &mut self.lookups {
+                lookup.complete(Err(Error::UnexpectedError {
+                    message: err_msg.clone(),
+                    source: None,
+                }));
+            }
+            return;
+        }
+
+        for (lookup, value) in self.lookups.iter_mut().zip(values.into_iter()) 
{
+            lookup.complete(Ok(value));
+        }
+    }
+
+    fn complete_exceptionally(&mut self, error_msg: &str) {
+        for lookup in &mut self.lookups {
+            lookup.complete(Err(Error::UnexpectedError {
+                message: error_msg.to_string(),
+                source: None,
+            }));
+        }
+    }
+}
+
+impl LookupSender {
+    /// Creates a new lookup sender.
+    pub fn new(
+        metadata: Arc<Metadata>,
+        queue: LookupQueue,
+        re_enqueue_tx: mpsc::UnboundedSender<LookupQuery>,
+        max_inflight_requests: usize,
+        max_retries: i32,
+    ) -> Self {
+        Self {
+            metadata,
+            queue,
+            re_enqueue_tx,
+            inflight_semaphore: 
Arc::new(Semaphore::new(max_inflight_requests)),
+            max_retries,
+            running: AtomicBool::new(true),
+            force_close: AtomicBool::new(false),
+        }
+    }
+
+    /// Runs the sender loop.
+    pub async fn run(&mut self) {
+        debug!("Starting Fluss lookup sender");
+
+        while self.running.load(Ordering::Acquire) {
+            if let Err(e) = self.run_once(false).await {
+                error!("Error in lookup sender: {}", e);
+            }
+        }
+
+        debug!("Beginning shutdown of lookup sender, sending remaining 
lookups");
+
+        // Process remaining lookups during shutdown
+        if !self.force_close.load(Ordering::Acquire) && 
self.queue.has_undrained() {
+            if let Err(e) = self.run_once(true).await {
+                error!("Error during lookup sender shutdown: {}", e);
+            }
+        }
+
+        debug!("Lookup sender shutdown complete");
+    }
+
+    /// Runs a single iteration of the sender loop.
+    async fn run_once(&mut self, drain_all: bool) -> Result<()> {
+        let lookups = if drain_all {
+            self.queue.drain_all()
+        } else {
+            self.queue.drain().await
+        };
+
+        self.send_lookups(lookups).await
+    }
+
+    /// Groups and sends lookups to appropriate servers.
+    async fn send_lookups(&self, lookups: Vec<LookupQuery>) -> Result<()> {

Review Comment:
   Yeah, we can leave this.



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