You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by ba...@apache.org on 2025/08/02 13:36:49 UTC

(iggy) 01/02: del

This is an automated email from the ASF dual-hosted git repository.

bashirbekov pushed a commit to branch draft-sans-new
in repository https://gitbox.apache.org/repos/asf/iggy.git

commit f603c2d85760ec5d1ff6bd4476bde126092aa9d6
Author: haze518 <as...@gmail.com>
AuthorDate: Tue Jul 29 14:04:23 2025 +0600

    del
---
 Cargo.lock                          |  15 ++
 core/common/src/error/iggy_error.rs |   8 +
 core/sdk/Cargo.toml                 |   3 +
 core/sdk/src/connection/mod.rs      | 443 ++++++++++++++++++++++++++++++++++++
 core/sdk/src/lib.rs                 |   2 +
 core/sdk/src/protocol/mod.rs        | 225 ++++++++++++++++++
 6 files changed, 696 insertions(+)

diff --git a/Cargo.lock b/Cargo.lock
index 4db7dd24..6abbab02 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1508,6 +1508,12 @@ dependencies = [
  "static_assertions",
 ]
 
+[[package]]
+name = "compat"
+version = "0.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1993b0854368a452b0011692f128362d9b42dbe17e009b1b4dd10e91ede39c27"
+
 [[package]]
 name = "concurrent-queue"
 version = "2.5.0"
@@ -2454,6 +2460,12 @@ dependencies = [
  "ext-trait",
 ]
 
+[[package]]
+name = "f"
+version = "0.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39c9599da4f7bbd19df30c2a4df53a809d86397f489a3352c30ba8cbc58f5ff8"
+
 [[package]]
 name = "fast-async-mutex"
 version = "0.6.7"
@@ -3796,7 +3808,9 @@ dependencies = [
  "async-trait",
  "bon",
  "bytes",
+ "compat",
  "dashmap",
+ "f",
  "flume",
  "futures",
  "futures-util",
@@ -3812,6 +3826,7 @@ dependencies = [
  "serde",
  "tokio",
  "tokio-rustls",
+ "tokio-util",
  "tracing",
  "trait-variant",
  "webpki-roots 1.0.2",
diff --git a/core/common/src/error/iggy_error.rs b/core/common/src/error/iggy_error.rs
index cc8a284b..1cb45921 100644
--- a/core/common/src/error/iggy_error.rs
+++ b/core/common/src/error/iggy_error.rs
@@ -459,6 +459,14 @@ pub enum IggyError {
     CannotReadIndexPosition = 10011,
     #[error("Cannot read index timestamp")]
     CannotReadIndexTimestamp = 10012,
+    #[error("Send queue is full")]
+    SendQueueFull = 10050,
+    #[error("Too many pending requests")]
+    TooManyPendingRequests = 10051,
+    #[error("IO Error")]
+    IoError = 10052,
+    #[error("Max number of retry has exceeded")]
+    MaxRetriesExceeded = 10053,
 }
 
 impl IggyError {
diff --git a/core/sdk/Cargo.toml b/core/sdk/Cargo.toml
index c6b26729..47554f6d 100644
--- a/core/sdk/Cargo.toml
+++ b/core/sdk/Cargo.toml
@@ -40,7 +40,9 @@ async-dropper = { workspace = true }
 async-trait = { workspace = true }
 bon = { workspace = true }
 bytes = { workspace = true }
+compat = "0.0.0"
 dashmap = { workspace = true }
+f = "0.0.0"
 # Can be removed if the feature above gets removed.
 #fast-async-mutex = { version = "0.6.7", optional = true }
 flume = { workspace = true }
@@ -57,6 +59,7 @@ rustls = { workspace = true }
 serde = { workspace = true }
 tokio = { workspace = true }
 tokio-rustls = { workspace = true }
+tokio-util.workspace = true
 tracing = { workspace = true }
 trait-variant = { workspace = true }
 webpki-roots = { workspace = true }
diff --git a/core/sdk/src/connection/mod.rs b/core/sdk/src/connection/mod.rs
new file mode 100644
index 00000000..801f0387
--- /dev/null
+++ b/core/sdk/src/connection/mod.rs
@@ -0,0 +1,443 @@
+use std::{collections::{HashMap, VecDeque}, fmt::Debug, io, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll, Waker}, time::Duration};
+
+use async_broadcast::{broadcast, Receiver, Sender};
+use async_trait::async_trait;
+use bytes::{Buf, Bytes, BytesMut};
+use futures::{future::poll_fn, AsyncRead, AsyncWrite};
+use iggy_binary_protocol::{BinaryClient, BinaryTransport, Client};
+use iggy_common::{ClientState, Command, DiagnosticEvent, IggyDuration, IggyError, TcpClientConfig};
+use tokio::{net::TcpStream, sync::Mutex as TokioMutex, time::{sleep, Sleep}};
+use tracing::{debug, error, info, trace, warn};
+use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
+
+use crate::protocol::{Order, ProtocolCore, ProtocolCoreConfig, Response, TxBuf};
+
+#[derive(Debug, Clone)]
+pub struct ConnectionStats {
+    pub bytes_sent: u64,
+    pub bytes_received: u64,
+    pub pending_sends: usize,
+    pub pending_receives: usize,
+}
+
+pub trait AsyncIO: AsyncWrite + AsyncRead + Unpin{}
+impl<T: AsyncRead + AsyncWrite + Unpin> AsyncIO for T {}
+
+pub trait Runtime: Send + Sync + Debug {
+    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>);
+}
+
+#[derive(Debug)]
+pub struct TokioRuntime {}
+
+impl Runtime for TokioRuntime {
+    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
+        tokio::spawn(future);
+    }
+}
+
+#[derive(Debug)]
+struct SendState {
+    request_id: u64,
+    encoded: BytesMut,
+    offset: usize,
+}
+
+#[derive(Debug)]
+pub struct ConnectionState {
+    core: ProtocolCore,
+    pub recv_waiters: HashMap<u64, Waker>,
+    ready_responses: HashMap<u64, Result<Bytes, IggyError>>,
+    driver: Option<Waker>,
+    error: Option<IggyError>,
+    pending_orders: VecDeque<Order>,
+}
+
+
+
+struct ConnectionDriver<S> {
+    state: Arc<Mutex<ConnectionState>>,
+    socket: Pin<Box<S>>,
+    current_send: Option<TxBuf>,
+    send_offset: usize,
+    recv_buffer: BytesMut,
+    wait_timer: Option<Pin<Box<Sleep>>>,
+}
+
+impl<S: AsyncIO + Send> ConnectionDriver<S> {
+    fn new(state: Arc<Mutex<ConnectionState>>, socket: S) -> Self {
+        Self {
+            state,
+            socket: Box::pin(socket),
+            current_send: None,
+            send_offset: 0,
+            recv_buffer: BytesMut::with_capacity(4096),
+            wait_timer: None,
+        }
+    }
+}
+
+impl<S: AsyncIO + Send> Future for ConnectionDriver<S> {
+    type Output = Result<(), io::Error>;
+    
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut work_done = false;
+        let mut recv_scratch = vec![0u8; 4096];
+
+        loop {
+            if let Some(timer) = &mut self.wait_timer {
+                match timer.as_mut().poll(cx) {
+                    Poll::Ready(()) => {
+                        self.wait_timer = None;
+                        work_done = true;
+                    }
+                    Poll::Pending => {
+                        if !work_done {
+                            return Poll::Pending;
+                        }
+                        todo!("some work")
+                    }
+                }
+            }
+
+            let order = {
+                let mut state = self.state.lock().unwrap();
+                state.driver = Some(cx.waker().clone());
+
+                // Get next order from queue or poll core
+                state.pending_orders.pop_front()
+                    .unwrap_or_else(|| state.core.poll())
+            };
+
+            match order {
+                Order::Connect => {
+                    error!("Connect order in driver - should be handled by transport");
+                }
+                Order::Wait(duration) => {
+                    self.wait_timer = Some(Box::pin(sleep(duration.get_duration())));
+                    work_done = true;
+                    continue;
+                }
+                Order::Transmit(tx_buf) => {
+                    self.current_send = Some(tx_buf);
+                    self.send_offset = 0;
+                    work_done = true;
+                }
+                Order::Authenticate { .. } => {
+                    continue;
+                }
+                Order::Noop => {}
+                Order::Error(e) => {
+                    return Poll::Ready(Err(io::Error::new(
+                        io::ErrorKind::Other,
+                        format!("Core error: {:?}", e)
+                    )));
+                }
+            }
+
+            if let Some(send) = self.current_send.take() {
+                let remaining = &send.data[self.send_offset..];
+                if !remaining.is_empty() {
+                    match self.socket.as_mut().poll_write(cx, remaining) {
+                        Poll::Ready(Ok(n)) => {
+                            self.send_offset += n;
+                            work_done = true;
+                            
+                            if self.send_offset >= send.data.len() {                                
+                                let mut state = self.state.lock().unwrap();
+                                let next_order = state.core.poll();
+                                if !matches!(next_order, Order::Noop) {
+                                    state.pending_orders.push_back(next_order);
+                                }
+                            } else {
+                                self.current_send = Some(send);
+                            }
+                        }
+                        Poll::Ready(Err(e)) => {
+                            let mut state = self.state.lock().unwrap();
+                            state.core.on_disconnected();
+                            state.error = Some(IggyError::IoError);
+                            return Poll::Ready(Err(e));
+                        }
+                        Poll::Pending => {
+                            self.current_send = Some(send);
+                        }
+                    }
+                }
+            }
+
+            match self.socket.as_mut().poll_read(cx, &mut recv_scratch) {
+                Poll::Ready(Ok(0)) => {
+                    let mut state = self.state.lock().unwrap();
+                    state.core.on_disconnected();
+                    return Poll::Ready(Err(io::Error::new(
+                        io::ErrorKind::UnexpectedEof,
+                        "connection closed"
+                    )));
+                }
+                Poll::Ready(Ok(n)) => {
+                    work_done = true;
+
+                    self.recv_buffer.extend_from_slice(&recv_scratch[..n]);
+
+                    while self.recv_buffer.len() >= 8 {
+                        let status = u32::from_le_bytes(
+                            self.recv_buffer[0..4].try_into().unwrap()
+                        );
+                        let length = u32::from_le_bytes(
+                            self.recv_buffer[4..8].try_into().unwrap()
+                        );
+                        
+                        let total = 8 + length as usize;
+                        if self.recv_buffer.len() < total {
+                            break;
+                        }
+                        
+                        self.recv_buffer.advance(8);
+                        let payload = if length > 0 {
+                            let data = self.recv_buffer.split_to(length as usize);
+                            Bytes::from(data)
+                        } else {
+                            Bytes::new()
+                        };
+                        
+                        let mut state = self.state.lock().unwrap();
+                        if let Some(request_id) = state.core.on_response(status, &payload) {
+                            let result = if status == 0 {
+                                Ok(payload)
+                            } else {
+                                Err(IggyError::from_code(status))
+                            };
+                            
+                            state.ready_responses.insert(request_id, result);
+                            
+                            if let Some(waker) = state.recv_waiters.remove(&request_id) {
+                                waker.wake();
+                            }
+                        }
+                        
+                        let next_order = state.core.poll();
+                        if !matches!(next_order, Order::Noop) {
+                            state.pending_orders.push_back(next_order);
+                        }
+                    }
+                }
+                Poll::Ready(Err(e)) => {
+                    let mut state = self.state.lock().unwrap();
+                    state.core.on_disconnected();
+                    state.error = Some(IggyError::IoError);
+                    return Poll::Ready(Err(e));
+                }
+                Poll::Pending => {}
+            }
+            
+            if !work_done {
+                let mut state = self.state.lock().unwrap();
+                state.driver = Some(cx.waker().clone());
+                return Poll::Pending;
+            }
+
+            work_done = false;
+        }    
+    }
+}
+
+#[derive(Debug)]
+pub struct TokioTcpTransport {
+    state: Arc<Mutex<ConnectionState>>,
+    runtime: Arc<dyn Runtime>,
+    config: Arc<TcpClientConfig>,
+    socket_handle: Option<tokio::task::JoinHandle<()>>,
+}
+
+impl TokioTcpTransport {
+    fn new(config: Arc<TcpClientConfig>, runtime: Arc<dyn Runtime>) -> Self {
+        let core_config = ProtocolCoreConfig {
+            max_retries: config.reconnection.max_retries,
+            reestablish_after: config.reconnection.reestablish_after,
+            auto_login: config.auto_login.clone(),
+        };
+        
+        let state = Arc::new(Mutex::new(ConnectionState {
+            core: ProtocolCore::new(core_config),
+            recv_waiters: HashMap::new(),
+            ready_responses: HashMap::new(),
+            driver: None,
+            error: None,
+            pending_orders: VecDeque::new(),
+        }));
+        
+        Self {
+            state,
+            runtime,
+            config,
+            socket_handle: None,
+        }
+    }
+
+    async fn run(&mut self) {
+        loop {
+            let order = {
+                let mut state = self.state.lock().unwrap();
+                state.core.poll()
+            };
+            
+            match order {
+                Order::Connect => {
+                    match TcpStream::connect(&self.config.server_address).await {
+                        Ok(socket) => {
+                            info!("Connected to {}", self.config.server_address);
+                            
+                            {
+                                let mut state = self.state.lock().unwrap();
+                                state.core.on_connected();
+                            }
+                            let compat_socket = socket.compat();
+                            let driver = ConnectionDriver::new(self.state.clone(), compat_socket);
+                            let handle = tokio::spawn(async move {
+                                if let Err(e) = driver.await {
+                                    error!("Driver error: {}", e);
+                                }
+                            });
+                            
+                            self.socket_handle = Some(handle);
+                        }
+                        Err(e) => {
+                            error!("Connection failed: {}", e);
+                            let mut state = self.state.lock().unwrap();
+                            state.core.on_disconnected();
+                        }
+                    }
+                }
+                
+                Order::Wait(duration) => {
+                    sleep(duration.get_duration()).await;
+                }
+                
+                _ => {
+                    sleep(Duration::from_millis(10)).await;
+                }
+            }
+        }
+    }
+}
+
+#[derive(Debug)]
+pub struct TcpClient {
+    transport: Arc<TokioMutex<Option<TokioTcpTransport>>>,
+    state: Arc<Mutex<ConnectionState>>,
+    config: Arc<TcpClientConfig>,
+    events: (Sender<DiagnosticEvent>, Receiver<DiagnosticEvent>),
+    runtime: Arc<dyn Runtime>,
+}
+
+impl TcpClient {
+    pub fn create(config: Arc<TcpClientConfig>) -> Result<Self, IggyError> {
+        let runtime = Arc::new(TokioRuntime{});
+        let transport = TokioTcpTransport::new(config.clone(), runtime.clone());
+        let state = transport.state.clone();
+
+        let (tx, rx) = broadcast(1000);
+
+        Ok(Self {
+            transport: Arc::new(TokioMutex::new(Some(transport))),
+            state,
+            config,
+            events: (tx, rx),
+            runtime,
+        })
+    }
+    
+    async fn send_raw(&self, code: u32, payload: Bytes) -> Result<Bytes, IggyError> {
+        let request_id = {
+            let mut state = self.state.lock().unwrap();
+            let id = state.core.send(code, payload)?;
+            
+            if let Some(waker) = state.driver.take() {
+                waker.wake();
+            }
+            
+            id
+        };
+        
+        poll_fn(move |cx| {
+            let mut state = self.state.lock().unwrap();
+            
+            if let Some(ref error) = state.error {
+                return Poll::Ready(Err(error.clone()));
+            }
+            
+            if let Some(result) = state.ready_responses.remove(&request_id) {
+                return Poll::Ready(result);
+            }
+            
+            state.recv_waiters.entry(request_id)
+                .or_insert_with(|| cx.waker().clone());
+            
+            Poll::Pending
+        }).await
+    }
+}
+
+#[async_trait]
+impl Client for TcpClient {
+    async fn connect(&self) -> Result<(), IggyError> {
+        let transport = self.transport.clone();
+        tokio::spawn(async move {
+            let mut transport = transport.lock().await;
+            if let Some(transport) = transport.as_mut() {
+                transport.run().await;
+            }
+        });
+        Ok(())
+    }
+    
+    async fn disconnect(&self) -> Result<(), IggyError> {
+        let mut state = self.state.lock().unwrap();
+        state.core.on_disconnected();
+        Ok(())
+    }
+    
+    async fn shutdown(&self) -> Result<(), IggyError> {
+        let mut state = self.state.lock().unwrap();
+        state.core.shutdown();
+        Ok(())
+    }
+    
+    async fn subscribe_events(&self) -> Receiver<DiagnosticEvent> {
+        self.events.1.clone()
+    }
+}
+
+#[async_trait]
+impl BinaryTransport for TcpClient {
+    async fn get_state(&self) -> ClientState {
+        let state = self.state.lock().unwrap();
+        state.core.state()
+    }
+
+    async fn set_state(&self, _state: ClientState) {
+        // State is managed by core, this is for compatibility
+    }
+    
+    async fn publish_event(&self, event: DiagnosticEvent) {
+        if let Err(error) = self.events.0.broadcast(event).await {
+            error!("Failed to send a TCP diagnostic event: {error}");
+        }
+    }
+
+    async fn send_with_response<T: Command>(&self, command: &T) -> Result<Bytes, IggyError> {
+        command.validate()?;
+        self.send_raw_with_response(command.code(), command.to_bytes()).await
+    }
+    
+    async fn send_raw_with_response(&self, code: u32, payload: Bytes) -> Result<Bytes, IggyError> {
+        self.send_raw(code, payload).await
+    }
+    
+    fn get_heartbeat_interval(&self) -> IggyDuration {
+        self.config.heartbeat_interval
+    }
+}
+
+impl BinaryClient for TcpClient {}
diff --git a/core/sdk/src/lib.rs b/core/sdk/src/lib.rs
index c315fd5e..99eb68c8 100644
--- a/core/sdk/src/lib.rs
+++ b/core/sdk/src/lib.rs
@@ -26,3 +26,5 @@ pub mod prelude;
 pub mod quic;
 pub mod stream_builder;
 pub mod tcp;
+pub mod protocol;
+pub mod connection;
\ No newline at end of file
diff --git a/core/sdk/src/protocol/mod.rs b/core/sdk/src/protocol/mod.rs
new file mode 100644
index 00000000..93292b30
--- /dev/null
+++ b/core/sdk/src/protocol/mod.rs
@@ -0,0 +1,225 @@
+use std::{
+    collections::VecDeque, sync::Arc, time::{Duration, Instant}
+};
+
+use bytes::{Buf, BufMut, Bytes, BytesMut};
+use iggy_common::{AutoLogin, ClientState, Credentials, IggyDuration, IggyError};
+use tracing::{debug, info, warn};
+
+const RESPONSE_HEADER_SIZE: usize = 8;
+
+#[derive(Debug)]
+pub struct ProtocolCoreConfig {
+    pub auto_login: AutoLogin,
+    pub reestablish_after: IggyDuration,
+    pub max_retries: Option<u32>,
+}
+
+#[derive(Debug)]
+pub enum Order {
+    Connect,
+    Wait(IggyDuration),
+    Transmit(TxBuf),
+    Authenticate { username: String, password: String },
+    Noop,
+    Error(IggyError),
+}
+
+#[derive(Debug, Clone)]
+pub struct TxBuf {
+    pub data: Bytes,
+    pub request_id: u64,
+}
+
+#[derive(Debug)]
+pub struct Response {
+    pub status: u32,
+    pub payload: Bytes,
+}
+
+#[derive(Debug)]
+pub struct ProtocolCore {
+    state: ClientState,
+    config: ProtocolCoreConfig,
+    last_connect_attempt: Option<Instant>,
+    retry_count: u32,
+    next_request_id: u64,
+    pending_sends: VecDeque<(u32, Bytes, u64)>,
+    sent_order: VecDeque<u64>,
+    auth_pending: bool,
+    auth_request_id: Option<u64>,
+}
+
+impl ProtocolCore {
+    pub fn new(config: ProtocolCoreConfig) -> Self {
+        Self {
+            state: ClientState::Disconnected,
+            config,
+            last_connect_attempt: None,
+            retry_count: 0,
+            next_request_id: 1,
+            pending_sends: VecDeque::new(),
+            sent_order: VecDeque::new(),
+            auth_pending: false,
+            auth_request_id: None,
+        }
+    }
+
+    pub fn state(&self) -> ClientState {
+        self.state
+    }
+
+    pub fn poll(&mut self) -> Order {
+        match self.state {
+            ClientState::Disconnected => self.handle_disconnected(),
+            ClientState::Connecting => Order::Noop,
+            ClientState::Connected => self.handle_connected(),
+            ClientState::Authenticating => Order::Noop,
+            ClientState::Authenticated => self.poll_transmit(),
+            ClientState::Shutdown => Order::Noop,
+        }
+    }
+
+    fn handle_disconnected(&mut self) -> Order {
+        if let Some(last_attempt) = self.last_connect_attempt {
+            let elapsed = last_attempt.elapsed().as_micros() as u64;
+            let interval = self.config.reestablish_after.as_micros();
+
+            if elapsed < interval {
+                let remaining = IggyDuration::from(interval - elapsed);
+                return Order::Wait(remaining);
+            }
+        }
+
+        if let Some(max_retries) = self.config.max_retries {
+            if self.retry_count >= max_retries {
+                return Order::Error(IggyError::MaxRetriesExceeded);
+            }
+        }
+
+        self.retry_count += 1;
+        self.last_connect_attempt = Some(Instant::now());
+        self.state = ClientState::Connecting;
+
+        debug!("Initiating connection (attempt {})", self.retry_count);
+        Order::Connect
+    }
+
+    fn handle_connected(&mut self) -> Order {
+        match &self.config.auto_login {
+            AutoLogin::Disabled => {
+                info!("Automatic sign-in is disabled.");
+                self.state = ClientState::Authenticated;
+            }
+            AutoLogin::Enabled(credentials) => {
+                if !self.auth_pending {
+                    self.state = ClientState::Authenticating;
+                    self.auth_pending = true;
+
+                    match credentials {
+                        Credentials::UsernamePassword(username, password) => {
+                            let auth_payload = encode_auth(&username, &password);
+                            let auth_id = self.queue_send(0x0A, auth_payload);
+                            self.auth_request_id = Some(auth_id);
+
+                            return self.poll_transmit();
+                        }
+                        _ => {
+                            todo!("add PersonalAccessToken")
+                        }
+                    }
+
+                }
+            }
+        }
+
+        self.poll_transmit()
+    }
+
+    fn poll_transmit(&mut self) -> Order {
+        if let Some((code, payload, request_id)) = self.pending_sends.pop_front() {
+            let mut buf = BytesMut::new();
+            let total_len = (payload.len() + 4) as u32;
+            buf.put_u32_le(total_len);
+            buf.put_u32_le(code);
+            buf.put_slice(&payload);
+
+            self.sent_order.push_back(request_id);
+
+            Order::Transmit(TxBuf {
+                data: buf.freeze(),
+                request_id,
+            })
+        } else {
+            Order::Noop
+        }
+    }
+
+    pub fn send(&mut self, code: u32, payload: Bytes) -> Result<u64, IggyError> {
+        match self.state {
+            ClientState::Shutdown => Err(IggyError::ClientShutdown),
+            ClientState::Disconnected | ClientState::Connecting => Err(IggyError::NotConnected),
+            ClientState::Connected | ClientState::Authenticating => {
+                Ok(self.queue_send(code, payload))
+            }
+            ClientState::Authenticated => Ok(self.queue_send(code, payload)),
+        }
+    }
+
+    fn queue_send(&mut self, code: u32, payload: Bytes) -> u64 {
+        let request_id = self.next_request_id;
+        self.next_request_id += 1;
+        self.pending_sends.push_back((code, payload, request_id));
+        request_id
+    }
+
+    pub fn on_connected(&mut self) {
+        debug!("Transport connected");
+        self.state = ClientState::Connected;
+        self.retry_count = 0;
+    }
+
+    pub fn on_disconnected(&mut self) {
+        debug!("Transport disconnected");
+        self.state = ClientState::Disconnected;
+        self.auth_pending = false;
+        self.auth_request_id = None;
+        self.sent_order.clear();
+    }
+
+    pub fn on_response(&mut self, status: u32, _payload: &Bytes) -> Option<u64> {
+        let request_id = self.sent_order.pop_front()?;
+
+        if Some(request_id) == self.auth_request_id {
+            if status == 0 {
+                self.on_authenticated();
+            } else {
+                warn!("Authentication failed with status: {}", status);
+                self.state = ClientState::Connected;
+                self.auth_pending = false;
+            }
+            self.auth_request_id = None;
+        }
+
+        Some(request_id)
+    }
+
+    fn on_authenticated(&mut self) {
+        debug!("Authentication successful");
+        self.state = ClientState::Authenticated;
+        self.auth_pending = false;
+    }
+
+    pub fn shutdown(&mut self) {
+        self.state = ClientState::Shutdown;
+    }
+}
+
+fn encode_auth(username: &str, password: &str) -> Bytes {
+    let mut buf = BytesMut::new();
+    buf.put_u32_le(username.len() as u32);
+    buf.put_slice(username.as_bytes());
+    buf.put_u32_le(password.len() as u32);
+    buf.put_slice(password.as_bytes());
+    buf.freeze()
+}