lnc-client 0.2.8

LANCE client library - Rust client for the LANCE streaming platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
//! Connection Management and Resilience
//!
//! Provides connection pooling, automatic reconnection, and resilience features
//! for LANCE client connections.
//!
//! # Features
//!
//! - **Connection Pool**: Manage multiple connections to a LANCE server
//! - **Auto-Reconnect**: Automatically reconnect on connection failures
//! - **Health Checking**: Periodic health checks with ping/pong
//! - **Backoff**: Exponential backoff for reconnection attempts
//! - **Circuit Breaker**: Prevent cascading failures
//!
//! # Example
//!
//! ```rust,no_run
//! use lnc_client::{ConnectionPool, ConnectionPoolConfig};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let pool = ConnectionPool::new(
//!         "127.0.0.1:1992",
//!         ConnectionPoolConfig::new()
//!             .with_max_connections(10)
//!             .with_health_check_interval(30),
//!     ).await?;
//!
//!     // Get a connection from the pool
//!     let mut conn = pool.get().await?;
//!     
//!     // Use the connection
//!     conn.ping().await?;
//!     
//!     // Connection is returned to pool when dropped
//!     Ok(())
//! }
//! ```

use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};

use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};

use crate::client::{ClientConfig, LanceClient};
use crate::error::{ClientError, Result};
use crate::tls::TlsClientConfig;

/// Configuration knobs for the LANCE client connection pool, mirroring the
/// resilience patterns documented in Architecture ยงยง14 and 20.
#[derive(Debug, Clone)]
pub struct ConnectionPoolConfig {
    /// Maximum number of connections in the pool
    pub max_connections: usize,
    /// Minimum number of idle connections to maintain
    pub min_idle: usize,
    /// Connection timeout
    pub connect_timeout: Duration,
    /// Maximum time to wait for a connection from the pool
    pub acquire_timeout: Duration,
    /// Health check interval (0 = disabled)
    pub health_check_interval: Duration,
    /// Maximum connection lifetime (0 = unlimited)
    pub max_lifetime: Duration,
    /// Idle timeout before closing a connection
    pub idle_timeout: Duration,
    /// Enable automatic reconnection
    pub auto_reconnect: bool,
    /// Maximum reconnection attempts (0 = unlimited)
    pub max_reconnect_attempts: u32,
    /// Base delay for exponential backoff
    pub reconnect_base_delay: Duration,
    /// Maximum delay for exponential backoff
    pub reconnect_max_delay: Duration,
    /// TLS configuration (None = plain TCP)
    pub tls_config: Option<TlsClientConfig>,
}

impl Default for ConnectionPoolConfig {
    fn default() -> Self {
        Self {
            max_connections: 10,
            min_idle: 1,
            connect_timeout: Duration::from_secs(30),
            acquire_timeout: Duration::from_secs(30),
            health_check_interval: Duration::from_secs(30),
            max_lifetime: Duration::from_secs(3600), // 1 hour
            idle_timeout: Duration::from_secs(300),  // 5 minutes
            auto_reconnect: true,
            max_reconnect_attempts: 5,
            reconnect_base_delay: Duration::from_millis(100),
            reconnect_max_delay: Duration::from_secs(30),
            tls_config: None,
        }
    }
}

impl ConnectionPoolConfig {
    /// Create a new connection pool configuration with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum connections
    pub fn with_max_connections(mut self, n: usize) -> Self {
        self.max_connections = n;
        self
    }

    /// Set minimum idle connections
    pub fn with_min_idle(mut self, n: usize) -> Self {
        self.min_idle = n;
        self
    }

    /// Set connection timeout
    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Set acquire timeout
    pub fn with_acquire_timeout(mut self, timeout: Duration) -> Self {
        self.acquire_timeout = timeout;
        self
    }

    /// Set health check interval (seconds)
    pub fn with_health_check_interval(mut self, secs: u64) -> Self {
        self.health_check_interval = Duration::from_secs(secs);
        self
    }

    /// Set maximum connection lifetime
    pub fn with_max_lifetime(mut self, lifetime: Duration) -> Self {
        self.max_lifetime = lifetime;
        self
    }

    /// Set idle timeout
    pub fn with_idle_timeout(mut self, timeout: Duration) -> Self {
        self.idle_timeout = timeout;
        self
    }

    /// Enable or disable auto-reconnect
    pub fn with_auto_reconnect(mut self, enabled: bool) -> Self {
        self.auto_reconnect = enabled;
        self
    }

    /// Set maximum reconnection attempts
    pub fn with_max_reconnect_attempts(mut self, attempts: u32) -> Self {
        self.max_reconnect_attempts = attempts;
        self
    }

    /// Set TLS configuration for encrypted connections
    pub fn with_tls(mut self, tls_config: TlsClientConfig) -> Self {
        self.tls_config = Some(tls_config);
        self
    }
}

/// Snapshot of connection-pool statistics exposed for observability and sized
/// to match Architecture ยง27's metrics guidance.
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    /// Total connections created
    pub connections_created: u64,
    /// Total connections closed
    pub connections_closed: u64,
    /// Current active connections (in use)
    pub active_connections: u64,
    /// Current idle connections (available)
    pub idle_connections: u64,
    /// Total acquire attempts
    pub acquire_attempts: u64,
    /// Successful acquires
    pub acquire_successes: u64,
    /// Failed acquires (timeout, error)
    pub acquire_failures: u64,
    /// Health check failures
    pub health_check_failures: u64,
    /// Reconnection attempts
    pub reconnect_attempts: u64,
}

/// Internal pool metrics using atomics (not exported outside the crate) so we
/// can keep Architecture ยง27 counters non-blocking.
#[derive(Debug, Default)]
struct PoolMetrics {
    connections_created: AtomicU64,
    connections_closed: AtomicU64,
    active_connections: AtomicU64,
    idle_connections: AtomicU64,
    acquire_attempts: AtomicU64,
    acquire_successes: AtomicU64,
    acquire_failures: AtomicU64,
    health_check_failures: AtomicU64,
    reconnect_attempts: AtomicU64,
}

impl PoolMetrics {
    fn snapshot(&self) -> PoolStats {
        PoolStats {
            connections_created: self.connections_created.load(Ordering::Relaxed),
            connections_closed: self.connections_closed.load(Ordering::Relaxed),
            active_connections: self.active_connections.load(Ordering::Relaxed),
            idle_connections: self.idle_connections.load(Ordering::Relaxed),
            acquire_attempts: self.acquire_attempts.load(Ordering::Relaxed),
            acquire_successes: self.acquire_successes.load(Ordering::Relaxed),
            acquire_failures: self.acquire_failures.load(Ordering::Relaxed),
            health_check_failures: self.health_check_failures.load(Ordering::Relaxed),
            reconnect_attempts: self.reconnect_attempts.load(Ordering::Relaxed),
        }
    }
}

/// Internal tracked connection paired with lifecycle metadata so we can enforce
/// Architecture ยง14 lifetime/idle policies.
struct PooledConnection {
    client: LanceClient,
    created_at: Instant,
    last_used: Instant,
}

impl PooledConnection {
    fn new(client: LanceClient) -> Self {
        let now = Instant::now();
        Self {
            client,
            created_at: now,
            last_used: now,
        }
    }

    fn is_expired(&self, max_lifetime: Duration) -> bool {
        if max_lifetime.is_zero() {
            return false;
        }
        self.created_at.elapsed() > max_lifetime
    }

    fn is_idle_too_long(&self, idle_timeout: Duration) -> bool {
        if idle_timeout.is_zero() {
            return false;
        }
        self.last_used.elapsed() > idle_timeout
    }
}

/// Connection pool for managing LANCE client connections, ensuring we reuse
/// TCP/TLS sessions per Architecture ยง14 instead of spawning new ones per
/// request. The pool keeps pre-warmed connections, enforces max/idle caps, and
/// wires up background health checks so ingestion/consumer threads avoid
/// blocking on connect storms.
pub struct ConnectionPool {
    addr: String,
    config: ConnectionPoolConfig,
    connections: Arc<Mutex<VecDeque<PooledConnection>>>,
    semaphore: Arc<Semaphore>,
    metrics: Arc<PoolMetrics>,
    running: Arc<AtomicBool>,
}

impl ConnectionPool {
    /// Creates a new connection pool bound to the provided address in keeping
    /// with Architecture ยง14's pinning and reuse strategy.
    ///
    /// # Arguments
    /// * `addr` - Target endpoint (`"host:port"`) shared by pooled clients.
    /// * `config` - Pool configuration describing capacity, timeouts, and TLS.
    ///
    /// # Returns
    /// * `Result<Self>` - Ready-to-use pool with `min_idle` connections opened
    ///   and a health-check task running (if enabled).
    ///
    /// # Errors
    /// Propagates connection failures when seeding initial idle clients.
    pub async fn new(addr: &str, config: ConnectionPoolConfig) -> Result<Self> {
        let pool = Self {
            addr: addr.to_string(),
            config: config.clone(),
            connections: Arc::new(Mutex::new(VecDeque::new())),
            semaphore: Arc::new(Semaphore::new(config.max_connections)),
            metrics: Arc::new(PoolMetrics::default()),
            running: Arc::new(AtomicBool::new(true)),
        };

        // Pre-populate with minimum idle connections
        for _ in 0..config.min_idle {
            if let Ok(conn) = pool.create_connection().await {
                let mut connections = pool.connections.lock().await;
                connections.push_back(conn);
                pool.metrics
                    .idle_connections
                    .fetch_add(1, Ordering::Relaxed);
            }
        }

        // Start health check task if enabled
        if !config.health_check_interval.is_zero() {
            let pool_clone = ConnectionPool {
                addr: pool.addr.clone(),
                config: pool.config.clone(),
                connections: pool.connections.clone(),
                semaphore: pool.semaphore.clone(),
                metrics: pool.metrics.clone(),
                running: pool.running.clone(),
            };
            tokio::spawn(async move {
                pool_clone.health_check_task().await;
            });
        }

        Ok(pool)
    }

    /// Acquires a pooled connection, respecting the configured acquire timeout
    /// and returning the RAII guard used throughout the client APIs.
    ///
    /// # Returns
    /// * `Result<PooledClient>` - Guard wrapping the loaned connection.
    ///
    /// # Errors
    /// * [`ClientError::Timeout`] if acquisition exceeds `acquire_timeout`.
    /// * [`ClientError::ConnectionClosed`] if the semaphore is closed.
    pub async fn get(&self) -> Result<PooledClient> {
        self.metrics
            .acquire_attempts
            .fetch_add(1, Ordering::Relaxed);

        // Acquire permit with timeout
        let permit = tokio::time::timeout(
            self.config.acquire_timeout,
            self.semaphore.clone().acquire_owned(),
        )
        .await
        .map_err(|_| {
            self.metrics
                .acquire_failures
                .fetch_add(1, Ordering::Relaxed);
            ClientError::Timeout
        })?
        .map_err(|_| {
            self.metrics
                .acquire_failures
                .fetch_add(1, Ordering::Relaxed);
            ClientError::ConnectionClosed
        })?;

        // Try to get an existing connection
        let conn = {
            let mut connections = self.connections.lock().await;
            loop {
                match connections.pop_front() {
                    Some(conn) => {
                        self.metrics
                            .idle_connections
                            .fetch_sub(1, Ordering::Relaxed);

                        // Check if connection is still valid
                        if conn.is_expired(self.config.max_lifetime)
                            || conn.is_idle_too_long(self.config.idle_timeout)
                        {
                            self.metrics
                                .connections_closed
                                .fetch_add(1, Ordering::Relaxed);
                            continue;
                        }
                        break Some(conn);
                    },
                    None => break None,
                }
            }
        };

        let conn = match conn {
            Some(mut c) => {
                c.last_used = Instant::now();
                c
            },
            None => {
                // Create a new connection
                self.create_connection().await?
            },
        };

        self.metrics
            .active_connections
            .fetch_add(1, Ordering::Relaxed);
        self.metrics
            .acquire_successes
            .fetch_add(1, Ordering::Relaxed);

        Ok(PooledClient {
            conn: Some(conn),
            pool: self.connections.clone(),
            metrics: self.metrics.clone(),
            permit: Some(permit),
            config: self.config.clone(),
        })
    }

    /// Creates a brand-new `LanceClient` based on the pool's configuration.
    ///
    /// # Returns
    /// * `Result<PooledConnection>` - Fresh connection wrapped with lifecycle
    ///   metadata for expiry/idle enforcement.
    ///
    /// # Errors
    /// Propagates underlying `LanceClient::connect`/`connect_tls` failures.
    async fn create_connection(&self) -> Result<PooledConnection> {
        let mut client_config = ClientConfig::new(&self.addr);
        client_config.connect_timeout = self.config.connect_timeout;

        let client = match &self.config.tls_config {
            Some(tls_config) => LanceClient::connect_tls(client_config, tls_config.clone()).await?,
            None => LanceClient::connect(client_config).await?,
        };
        self.metrics
            .connections_created
            .fetch_add(1, Ordering::Relaxed);

        Ok(PooledConnection::new(client))
    }

    /// Get pool statistics
    pub fn stats(&self) -> PoolStats {
        self.metrics.snapshot()
    }

    /// Gracefully shuts down the pool, clearing idle connections and marking
    /// future `get` calls as invalid per Architecture ยง14 teardown guidance.
    pub async fn close(&self) {
        self.running.store(false, Ordering::Relaxed);

        let mut connections = self.connections.lock().await;
        let count = connections.len() as u64;
        connections.clear();
        self.metrics
            .connections_closed
            .fetch_add(count, Ordering::Relaxed);
        self.metrics.idle_connections.store(0, Ordering::Relaxed);
    }

    /// Health check task
    async fn health_check_task(&self) {
        let mut interval = tokio::time::interval(self.config.health_check_interval);

        while self.running.load(Ordering::Relaxed) {
            interval.tick().await;

            // Get all connections for health check
            let mut to_check = {
                let mut connections = self.connections.lock().await;
                std::mem::take(&mut *connections)
            };

            let mut healthy = VecDeque::new();
            let _initial_count = to_check.len();

            for mut conn in to_check.drain(..) {
                // Check expiry
                if conn.is_expired(self.config.max_lifetime) {
                    self.metrics
                        .connections_closed
                        .fetch_add(1, Ordering::Relaxed);
                    continue;
                }

                // Ping to check health
                match conn.client.ping().await {
                    Ok(_) => {
                        conn.last_used = Instant::now();
                        healthy.push_back(conn);
                    },
                    Err(_) => {
                        self.metrics
                            .health_check_failures
                            .fetch_add(1, Ordering::Relaxed);
                        self.metrics
                            .connections_closed
                            .fetch_add(1, Ordering::Relaxed);
                    },
                }
            }

            // Return healthy connections
            {
                let mut connections = self.connections.lock().await;
                connections.extend(healthy);
                self.metrics
                    .idle_connections
                    .store(connections.len() as u64, Ordering::Relaxed);
            }
        }
    }
}

/// RAII guard that returns the connection to the pool on drop, keeping the
/// Architecture ยง14 resource caps accurate.
pub struct PooledClient {
    conn: Option<PooledConnection>,
    pool: Arc<Mutex<VecDeque<PooledConnection>>>,
    metrics: Arc<PoolMetrics>,
    #[allow(dead_code)]
    permit: Option<OwnedSemaphorePermit>,
    #[allow(dead_code)]
    config: ConnectionPoolConfig,
}

impl PooledClient {
    /// Get a reference to the underlying client
    pub fn client(&mut self) -> Result<&mut LanceClient> {
        match self.conn.as_mut() {
            Some(conn) => Ok(&mut conn.client),
            None => Err(ClientError::ConnectionClosed),
        }
    }

    /// Ping the server
    pub async fn ping(&mut self) -> Result<Duration> {
        if let Some(ref mut conn) = self.conn {
            conn.client.ping().await
        } else {
            Err(ClientError::ConnectionClosed)
        }
    }

    /// Mark the connection as unhealthy (don't return to pool)
    pub fn mark_unhealthy(&mut self) {
        self.conn = None;
        self.metrics
            .connections_closed
            .fetch_add(1, Ordering::Relaxed);
    }
}

impl Drop for PooledClient {
    fn drop(&mut self) {
        if let Some(mut conn) = self.conn.take() {
            conn.last_used = Instant::now();

            // Return to pool
            let pool = self.pool.clone();
            let metrics = self.metrics.clone();

            tokio::spawn(async move {
                let mut connections = pool.lock().await;
                connections.push_back(conn);
                metrics.active_connections.fetch_sub(1, Ordering::Relaxed);
                metrics.idle_connections.fetch_add(1, Ordering::Relaxed);
            });
        } else {
            self.metrics
                .active_connections
                .fetch_sub(1, Ordering::Relaxed);
        }

        // Permit is released when dropped
    }
}

/// Reconnecting client wrapper offering automatic reconnection and leader
/// redirection support per Architecture ยง21.
pub struct ReconnectingClient {
    addr: String,
    config: ClientConfig,
    tls_config: Option<TlsClientConfig>,
    client: Option<LanceClient>,
    reconnect_attempts: u32,
    max_attempts: u32,
    base_delay: Duration,
    max_delay: Duration,
    /// Current leader address (for redirection)
    leader_addr: Option<SocketAddr>,
    /// Whether to follow leader redirects
    follow_leader: bool,
}

impl ReconnectingClient {
    /// Create a new reconnecting client
    ///
    /// The address can be either an IP:port (e.g., "127.0.0.1:1992") or
    /// a hostname:port (e.g., "lance.example.com:1992").
    pub async fn connect(addr: &str) -> Result<Self> {
        let config = ClientConfig::new(addr);
        let client = LanceClient::connect(config.clone()).await?;

        Ok(Self {
            addr: addr.to_string(),
            config,
            tls_config: None,
            client: Some(client),
            reconnect_attempts: 0,
            max_attempts: 5,
            base_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            leader_addr: None,
            follow_leader: true,
        })
    }

    /// Wrap an existing LanceClient with auto-reconnect support.
    ///
    /// The `addr` is used for DNS re-resolution on reconnect (important for
    /// load-balanced endpoints). By default, retries are unlimited.
    pub fn from_existing(client: LanceClient, addr: &str) -> Self {
        let config = client.config().clone();
        Self {
            addr: addr.to_string(),
            config,
            tls_config: None,
            client: Some(client),
            reconnect_attempts: 0,
            max_attempts: 0, // unlimited by default
            base_delay: Duration::from_millis(500),
            max_delay: Duration::from_secs(30),
            leader_addr: None,
            follow_leader: true,
        }
    }

    /// Create a new reconnecting client with TLS
    ///
    /// The address can be either an IP:port (e.g., "127.0.0.1:1992") or
    /// a hostname:port (e.g., "lance.example.com:1992").
    pub async fn connect_tls(addr: &str, tls_config: TlsClientConfig) -> Result<Self> {
        let config = ClientConfig::new(addr);
        let client = LanceClient::connect_tls(config.clone(), tls_config.clone()).await?;

        Ok(Self {
            addr: addr.to_string(),
            config,
            tls_config: Some(tls_config),
            client: Some(client),
            reconnect_attempts: 0,
            max_attempts: 5,
            base_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            leader_addr: None,
            follow_leader: true,
        })
    }

    /// Set maximum reconnection attempts (0 = unlimited)
    pub fn with_max_attempts(mut self, attempts: u32) -> Self {
        self.max_attempts = attempts;
        self
    }

    /// Configure for unlimited reconnection attempts (never give up)
    pub fn with_unlimited_retries(mut self) -> Self {
        self.max_attempts = 0;
        self
    }

    /// Set base delay for exponential backoff
    pub fn with_base_delay(mut self, delay: Duration) -> Self {
        self.base_delay = delay;
        self
    }

    /// Set maximum delay for exponential backoff
    pub fn with_max_delay(mut self, delay: Duration) -> Self {
        self.max_delay = delay;
        self
    }

    /// Enable or disable automatic leader following
    pub fn with_follow_leader(mut self, follow: bool) -> Self {
        self.follow_leader = follow;
        self
    }

    /// Get the original connection address
    pub fn original_addr(&self) -> &str {
        &self.addr
    }

    /// Get the current leader address if known
    pub fn leader_addr(&self) -> Option<SocketAddr> {
        self.leader_addr
    }

    /// Update the known leader address (called when redirect received)
    pub fn set_leader_addr(&mut self, addr: SocketAddr) {
        self.leader_addr = Some(addr);
        if self.follow_leader {
            // Update config to connect to leader on next reconnect
            self.config.addr = addr.to_string();
        }
    }

    /// Get total reconnection attempts made
    pub fn reconnect_attempts(&self) -> u32 {
        self.reconnect_attempts
    }

    /// Get a reference to the underlying client, reconnecting if needed
    pub async fn client(&mut self) -> Result<&mut LanceClient> {
        if self.client.is_none() {
            self.reconnect().await?;
        }
        self.client.as_mut().ok_or(ClientError::ConnectionClosed)
    }

    /// Attempt to reconnect with exponential backoff and DNS re-resolution.
    /// On success, resets the reconnect attempt counter.
    pub async fn reconnect(&mut self) -> Result<()> {
        let mut attempts = 0;

        loop {
            attempts += 1;
            self.reconnect_attempts += 1;

            // Re-resolve DNS by connecting with the original address.
            // This is critical for LB environments where DNS round-robin
            // may route us to a different (healthy) node.
            let mut config = self.config.clone();
            config.addr = self.addr.clone();

            let result = match &self.tls_config {
                Some(tls) => LanceClient::connect_tls(config, tls.clone()).await,
                None => LanceClient::connect(config).await,
            };

            match result {
                Ok(client) => {
                    self.client = Some(client);
                    return Ok(());
                },
                Err(e) => {
                    if self.max_attempts > 0 && attempts >= self.max_attempts {
                        return Err(e);
                    }

                    // Calculate backoff delay
                    let delay = self.base_delay * 2u32.saturating_pow(attempts - 1);
                    let delay = delay.min(self.max_delay);

                    tokio::time::sleep(delay).await;
                },
            }
        }
    }

    /// Execute an operation with automatic reconnection on failure.
    /// Retries on all retryable errors (connection failures, FORWARD_FAILED,
    /// timeouts, backpressure, NOT_LEADER) with exponential backoff.
    pub async fn execute<F, T>(&mut self, op: F) -> Result<T>
    where
        F: Fn(
            &mut LanceClient,
        )
            -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T>> + Send + '_>>,
    {
        let mut attempts = 0u32;
        loop {
            let client = self.client().await?;

            match op(client).await {
                Ok(result) => return Ok(result),
                Err(e) if e.is_retryable() => {
                    attempts += 1;
                    if self.max_attempts > 0 && attempts >= self.max_attempts {
                        return Err(e);
                    }
                    // Mark connection as failed so next client() call reconnects
                    self.client = None;
                    // Backoff before retry
                    let delay = self.base_delay * 2u32.saturating_pow(attempts.saturating_sub(1));
                    let delay = delay.min(self.max_delay);
                    tokio::time::sleep(delay).await;
                },
                Err(e) => return Err(e),
            }
        }
    }

    /// Mark connection as failed
    pub fn mark_failed(&mut self) {
        self.client = None;
    }
}

/// Cluster-aware client with automatic node discovery. It discovers nodes and
/// maintains healthy connections for read availability per Architecture ยง21.
pub struct ClusterClient {
    /// Known cluster nodes
    nodes: Vec<SocketAddr>,
    /// Primary node for this client (for connection affinity, not write routing)
    primary: Option<SocketAddr>,
    /// Client configuration
    config: ClientConfig,
    /// TLS configuration
    tls_config: Option<TlsClientConfig>,
    /// Active client connection
    client: Option<LanceClient>,
    /// Last successful discovery time
    last_discovery: Option<Instant>,
    /// Discovery refresh interval
    discovery_interval: Duration,
}

impl ClusterClient {
    /// Creates a cluster client using the provided seed nodes, aligning with
    /// Architecture ยง21's discovery process.
    ///
    /// # Arguments
    /// * `seed_addrs` - List of seed endpoints (`"host:port"`) used to fetch
    ///   the cluster topology.
    ///
    /// # Returns
    /// * `Result<Self>` - Initialized client after a successful discovery
    ///   round-trip.
    ///
    /// # Errors
    /// * [`ClientError::ProtocolError`] when no seed nodes resolve.
    /// * Propagates underlying connect/discovery errors when all nodes fail.
    pub async fn connect(seed_addrs: &[&str]) -> Result<Self> {
        let nodes: Vec<SocketAddr> = seed_addrs.iter().filter_map(|s| s.parse().ok()).collect();

        if nodes.is_empty() {
            return Err(ClientError::ProtocolError(
                "No valid seed addresses".to_string(),
            ));
        }

        let config = ClientConfig::new(nodes[0].to_string());
        let mut cluster = Self {
            nodes,
            primary: None,
            config,
            tls_config: None,
            client: None,
            last_discovery: None,
            discovery_interval: Duration::from_secs(60),
        };

        cluster.discover_cluster().await?;
        Ok(cluster)
    }

    /// Creates a TLS-enabled cluster client using the provided seed nodes so we
    /// can satisfy Architecture ยง14's transport security guidance.
    ///
    /// # Arguments
    /// * `seed_addrs` - List of seed endpoints for discovery.
    /// * `tls_config` - Certificates and trust roots forwarded to
    ///   `LanceClient`.
    ///
    /// # Returns
    /// * `Result<Self>` - Initialized TLS client once discovery succeeds.
    ///
    /// # Errors
    /// Mirrors [`ClusterClient::connect`], plus TLS handshake failures.
    pub async fn connect_tls(seed_addrs: &[&str], tls_config: TlsClientConfig) -> Result<Self> {
        let nodes: Vec<SocketAddr> = seed_addrs.iter().filter_map(|s| s.parse().ok()).collect();

        if nodes.is_empty() {
            return Err(ClientError::ProtocolError(
                "No valid seed addresses".to_string(),
            ));
        }

        let config = ClientConfig::new(nodes[0].to_string()).with_tls(tls_config.clone());
        let mut cluster = Self {
            nodes,
            primary: None,
            config,
            tls_config: Some(tls_config),
            client: None,
            last_discovery: None,
            discovery_interval: Duration::from_secs(60),
        };

        cluster.discover_cluster().await?;
        Ok(cluster)
    }

    /// Set the discovery refresh interval
    pub fn with_discovery_interval(mut self, interval: Duration) -> Self {
        self.discovery_interval = interval;
        self
    }

    /// Discover cluster topology from any available node
    async fn discover_cluster(&mut self) -> Result<()> {
        for &node in &self.nodes.clone() {
            let mut config = self.config.clone();
            config.addr = node.to_string();

            match LanceClient::connect(config).await {
                Ok(mut client) => {
                    match client.get_cluster_status().await {
                        Ok(status) => {
                            self.primary = status.leader_id.map(|id| {
                                // Try to find node in peer_states or use first node
                                status
                                    .peer_states
                                    .get(&id)
                                    .and_then(|s| s.parse().ok())
                                    .unwrap_or(node)
                            });
                            self.last_discovery = Some(Instant::now());

                            // Connect to primary if found
                            if let Some(primary_addr) = self.primary {
                                self.config.addr = primary_addr.to_string();
                                self.client =
                                    Some(LanceClient::connect(self.config.clone()).await?);
                            } else {
                                self.client = Some(client);
                            }
                            return Ok(());
                        },
                        Err(_) => {
                            // Single-node mode or cluster not available
                            self.client = Some(client);
                            self.primary = Some(node);
                            self.last_discovery = Some(Instant::now());
                            return Ok(());
                        },
                    }
                },
                Err(_) => continue,
            }
        }

        Err(ClientError::ConnectionFailed(std::io::Error::new(
            std::io::ErrorKind::NotConnected,
            "Could not connect to any cluster node",
        )))
    }

    /// Get a client connection, refreshing discovery if needed
    pub async fn client(&mut self) -> Result<&mut LanceClient> {
        // Check if discovery refresh is needed
        let needs_refresh = self
            .last_discovery
            .map(|t| t.elapsed() > self.discovery_interval)
            .unwrap_or(true);

        if needs_refresh || self.client.is_none() {
            self.discover_cluster().await?;
        }

        self.client.as_mut().ok_or(ClientError::ConnectionClosed)
    }

    /// Get the current primary node address
    pub fn primary(&self) -> Option<SocketAddr> {
        self.primary
    }

    /// Get all known cluster nodes
    pub fn nodes(&self) -> &[SocketAddr] {
        &self.nodes
    }

    /// Get the TLS configuration if set
    pub fn tls_config(&self) -> Option<&TlsClientConfig> {
        self.tls_config.as_ref()
    }

    /// Check if TLS is enabled
    pub fn is_tls_enabled(&self) -> bool {
        self.tls_config.is_some()
    }

    /// Force a cluster discovery refresh
    pub async fn refresh(&mut self) -> Result<()> {
        self.discover_cluster().await
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_pool_config_defaults() {
        let config = ConnectionPoolConfig::new();

        assert_eq!(config.max_connections, 10);
        assert_eq!(config.min_idle, 1);
        assert!(config.auto_reconnect);
    }

    #[test]
    fn test_pool_config_builder() {
        let config = ConnectionPoolConfig::new()
            .with_max_connections(20)
            .with_min_idle(5)
            .with_health_check_interval(60)
            .with_auto_reconnect(false);

        assert_eq!(config.max_connections, 20);
        assert_eq!(config.min_idle, 5);
        assert_eq!(config.health_check_interval, Duration::from_secs(60));
        assert!(!config.auto_reconnect);
    }

    #[test]
    fn test_pool_stats_default() {
        let stats = PoolStats::default();

        assert_eq!(stats.connections_created, 0);
        assert_eq!(stats.active_connections, 0);
    }

    #[test]
    fn test_pooled_connection_expiry() {
        use std::thread::sleep;

        // Can't easily test without actual connection, just test the logic
        let max_lifetime = Duration::from_millis(10);
        let created_at = Instant::now();

        sleep(Duration::from_millis(20));

        assert!(created_at.elapsed() > max_lifetime);
    }

    #[test]
    fn test_reconnecting_client_leader_addr() {
        // Test leader address tracking (without actual connection)
        let addr: SocketAddr = "127.0.0.1:1992".parse().unwrap();
        let leader: SocketAddr = "127.0.0.1:1993".parse().unwrap();

        // Simulate leader address update logic
        let follow_leader = true;
        let mut config_addr = addr;

        // Set leader - simulates set_leader_addr behavior
        let leader_addr: Option<SocketAddr> = Some(leader);
        if follow_leader {
            config_addr = leader;
        }

        assert_eq!(leader_addr, Some(leader));
        assert_eq!(config_addr, leader);
    }

    #[test]
    fn test_connection_pool_config_auto_reconnect() {
        let config = ConnectionPoolConfig::new()
            .with_auto_reconnect(true)
            .with_max_reconnect_attempts(10);

        assert!(config.auto_reconnect);
        assert_eq!(config.max_reconnect_attempts, 10);
    }
}