clickhouse-connection-pool 0.1.3

A connection pooling library for ClickHouse in Rust, built on top of deadpool.
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
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use clickhouse::Client;
use deadpool::managed::{Manager, Metrics, Object, PoolError, RecycleError};
use thiserror::Error;
use tokio::task;
use tokio::time::timeout;

use crate::config::{ClickhouseConfig, DatalakeConfig};
use crate::metrics::{Kind, MetricConfig, Registry, SharedRegistrar};

#[derive(Debug, Error)]
pub enum ClickhouseError {
    #[error("Clickhouse client error: {0}")]
    Client(#[from] clickhouse::error::Error),

    #[error("Connection validation failed: {0}")]
    Validation(String),

    #[error("Connection timed out")]
    Timeout,

    #[error("Pool error: {0}")]
    Pool(String),

    #[error("Shutdown in progress")]
    ShuttingDown,
}

impl From<tokio::time::error::Elapsed> for ClickhouseError {
    fn from(_: tokio::time::error::Elapsed) -> Self {
        Self::Timeout
    }
}

impl<T: std::fmt::Display> From<PoolError<T>> for ClickhouseError {
    fn from(value: PoolError<T>) -> Self {
        Self::Pool(value.to_string())
    }
}

#[derive(Debug, Clone)]
pub struct PoolMetrics {
    pub size: usize,
    pub available: usize,
    pub in_use: usize,
    pub max_size: usize,
    pub min_size: usize,
    pub waiters: usize,
}

pub struct ClickhouseConnection {
    client: Client,
    last_used: Instant,
    id: u64,
    query_count: AtomicU64,
    created_at: Instant,
}

impl ClickhouseConnection {
    pub fn new(client: Client, id: u64) -> Self {
        Self {
            client,
            last_used: Instant::now(),
            id,
            query_count: AtomicU64::new(0),
            created_at: Instant::now(),
        }
    }

    pub fn id(&self) -> u64 {
        self.id
    }

    pub fn age(&self) -> Duration {
        self.created_at.elapsed()
    }

    pub fn idle_time(&self) -> Duration {
        self.last_used.elapsed()
    }

    pub fn query_count(&self) -> u64 {
        self.query_count.load(Ordering::Relaxed)
    }

    pub async fn health_check(&self) -> Result<(), ClickhouseError> {
        match self.client.query("SELECT 1").execute().await {
            Ok(_) => Ok(()),
            Err(e) => Err(ClickhouseError::Client(e)),
        }
    }
}

impl Deref for ClickhouseConnection {
    type Target = Client;

    fn deref(&self) -> &Self::Target {
        &self.client
    }
}

impl DerefMut for ClickhouseConnection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.client
    }
}

impl fmt::Debug for ClickhouseConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClickhouseConnection")
            .field("id", &self.id)
            .field("created_at", &self.created_at)
            .field("query_count", &self.query_count)
            .field("last_used", &self.last_used)
            .finish()
    }
}

pub fn get_query_type(query: &str) -> &'static str {
    let query = query.trim_start().to_uppercase();

    if query.starts_with("SELECT") {
        "select"
    } else if query.starts_with("INSERT") {
        "insert"
    } else if query.starts_with("CREATE") {
        "create"
    } else if query.starts_with("ALTER") {
        "alter"
    } else if query.starts_with("DROP") {
        "drop"
    } else {
        "other"
    }
}

#[derive(Debug)]
pub struct ClickhouseConnectionManager {
    config: Arc<ClickhouseConfig>,
    next_connection_id: AtomicU64,
    is_shutting_down: Arc<AtomicBool>,
    metrics: Option<SharedRegistrar>,
}

impl ClickhouseConnectionManager {
    pub fn new(config: Arc<ClickhouseConfig>, metrics: Option<SharedRegistrar>) -> Self {
        Self {
            config,
            next_connection_id: AtomicU64::new(1),
            is_shutting_down: Arc::new(AtomicBool::new(false)),
            metrics,
        }
    }

    pub fn initiate_shutdown(&self) {
        self.is_shutting_down.store(true, Ordering::SeqCst);
        log::info!("Clickhouse connection manager shutdown in progress");
    }

    pub fn create_client(&self) -> Result<Client, ClickhouseError> {
        let url = self.config.authenticated_connection_url();

        let client = Client::default()
            .with_url(url)
            .with_user(&self.config.username)
            .with_password(&self.config.password)
            .with_option("async_insert", "1")
            .with_option("wait_for_async_insert", "1");

        Ok(client)
    }
}

impl Manager for ClickhouseConnectionManager {
    type Type = ClickhouseConnection;
    type Error = ClickhouseError;

    async fn create(&self) -> Result<Self::Type, Self::Error> {
        if self.is_shutting_down.load(Ordering::SeqCst) {
            return Err(ClickhouseError::ShuttingDown);
        }

        let connection_id = self.next_connection_id.fetch_add(1, Ordering::SeqCst);

        let start = Instant::now();

        let config = &self.config.clone();
        log::debug!(
            "Creating new Clickhouse connection [id: {}] to: {}:{}",
            connection_id,
            config.host,
            config.port
        );

        let client = self.create_client()?;

        let validation_timeout = Duration::from_secs(config.connect_timeout_seconds);

        let validation = match timeout(validation_timeout, client.query("SELECT 1").execute()).await
        {
            Ok(Ok(_)) => Ok(()),
            Ok(Err(e)) => Err(ClickhouseError::Client(e)),
            Err(_) => Err(ClickhouseError::Timeout),
        };

        let duration = start.elapsed();
        if let Some(metrics) = &self.metrics {
            metrics.set_gauge_vec_mut(
                "clickhouse_connection_creation_second",
                &["create"],
                duration.as_secs_f64(),
            );
        }

        match validation {
            Ok(()) => {
                log::debug!(
                    "Connection established: [id: {}] in {:?}",
                    connection_id,
                    duration
                );

                if let Some(metrics) = &self.metrics {
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connections_created_total",
                        &["success"],
                    );
                }

                Ok(ClickhouseConnection::new(client, connection_id))
            }
            Err(e) => {
                log::error!(
                    "Failed to validate ClickHouse connection (id: {}): {}",
                    connection_id,
                    e
                );

                if let Some(metrics) = &self.metrics {
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connections_created_total",
                        &["failure"],
                    );
                }

                Err(e)
            }
        }
    }

    async fn recycle(
        &self,
        conn: &mut Self::Type,
        _: &Metrics,
    ) -> Result<(), RecycleError<Self::Error>> {
        if self.is_shutting_down.load(Ordering::SeqCst) {
            return Err(RecycleError::Message("Shutting down".into()));
        }

        log::debug!("Testing health of connection: [id: {}]", conn.id());

        let validation_timeout = Duration::from_secs(self.config.connect_timeout_seconds);

        match timeout(validation_timeout, conn.query("SELECT 1").execute()).await {
            Ok(Ok(_)) => {
                log::debug!("Connection [id: {}] health check passed", conn.id());

                if let Some(metrics) = &self.metrics {
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connections_health_checks_total",
                        &["success"],
                    );
                }

                Ok(())
            }
            Ok(Err(e)) => {
                log::warn!("Connection [id: {}] health check failed: {}", conn.id(), e);

                if let Some(metrics) = &self.metrics {
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connections_health_checks_total",
                        &["failure"],
                    );
                }

                Err(RecycleError::Message(
                    format!("Health check failed: {}", e).into(),
                ))
            }
            Err(_) => {
                log::warn!(
                    "Connection [id: {}] health check timed out after: {:?}",
                    conn.id(),
                    validation_timeout
                );

                if let Some(metrics) = &self.metrics {
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connections_health_checks_total",
                        &["timeout"],
                    );
                }

                Err(RecycleError::Message("Health check timed out".into()))
            }
        }
    }
}

pub type Pool = deadpool::managed::Pool<ClickhouseConnectionManager>;
pub type PooledConnection = Object<ClickhouseConnectionManager>;

pub struct ClickhouseConnectionPool {
    pool: Pool,
    config: Arc<DatalakeConfig>,
    metrics: Option<SharedRegistrar>,
    is_initialized: AtomicBool,
}

impl ClickhouseConnectionPool {
    pub fn new(config: Arc<DatalakeConfig>, metrics: Option<SharedRegistrar>) -> Self {
        if let Some(metrics_ref) = &metrics {
            Self::register_metrics(metrics_ref);
        }

        let initial_size = config.clickhouse.max_connections as usize;

        let manager = ClickhouseConnectionManager::new(config.clickhouse.clone(), metrics.clone());

        let pool = deadpool::managed::Pool::<ClickhouseConnectionManager>::builder(manager)
            .max_size(initial_size)
            .build()
            .expect("Failed to build connection pool");

        Self {
            pool,
            config,
            metrics,
            is_initialized: AtomicBool::new(false),
        }
    }

    pub async fn initialize(&self) -> Result<(), ClickhouseError> {
        if self.is_initialized.load(Ordering::SeqCst) {
            return Ok(());
        }

        log::info!("Initializing Clickhouse connection pool");

        let warmup_count = self.config.clickhouse.max_connections as usize;

        let mut warmup_handles = Vec::with_capacity(warmup_count);

        for i in 0..warmup_count {
            let pool = self.pool.clone();

            let handle = task::spawn(async move {
                match pool.get().await {
                    Ok(conn) => match conn.health_check().await {
                        Ok(_) => {
                            log::debug!("Warm-up connection {} initialized successfully", i);
                            Ok(())
                        }
                        Err(e) => {
                            log::error!("Warm-up connection {} health check failed: {}", i, e);
                            Err(e)
                        }
                    },
                    Err(e) => {
                        log::error!("Failed to get warm-up connection {}: {}", i, e);
                        Err(ClickhouseError::Pool(e.to_string()))
                    }
                }
            });
            warmup_handles.push(handle);
        }

        let mut warmup_success_count = 0;
        for (i, handle) in warmup_handles.into_iter().enumerate() {
            match handle.await {
                Ok(Ok(_)) => {
                    warmup_success_count += 1;
                }
                Ok(Err(e)) => {
                    log::warn!("Warm-up connection {} failed: {}", i, e);
                }
                Err(e) => {
                    log::error!("Warm-up task {} panicked: {}", i, e);
                }
            }
        }

        log::info!(
            "Connection pool warm-up complete: {}/{} successful",
            warmup_success_count,
            warmup_count
        );

        self.is_initialized.store(true, Ordering::SeqCst);

        if let Some(metrics) = &self.metrics {
            let status = self.pool.status();
            metrics.set_int_gauge_vec_mut(
                "clickhouse_pool_connections",
                &["available"],
                status.available as i64,
            );
            metrics.set_int_gauge_vec_mut(
                "clickhouse_pool_connections",
                &["size"],
                status.size as i64,
            );
        }

        Ok(())
    }

    pub async fn get_connection(&self) -> Result<PooledConnection, ClickhouseError> {
        if !self.is_initialized.load(Ordering::SeqCst) {
            log::warn!("Attempting to get connection from uninitialized pool");
        }

        let start = Instant::now();

        let timeout_duration = Duration::from_secs(self.config.clickhouse.connect_timeout_seconds);

        match tokio::time::timeout(timeout_duration, self.pool.get()).await {
            Ok(Ok(conn)) => {
                let duration = start.elapsed();

                if let Some(metrics) = &self.metrics {
                    metrics.set_gauge_vec_mut(
                        "clickhouse_connection_acquisition_seconds",
                        &["success"],
                        duration.as_secs_f64(),
                    );
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connection_acquisition_total",
                        &["success"],
                    );
                }

                log::debug!("Connection acquired in {:?}", duration);
                Ok(conn)
            }
            Ok(Err(e)) => {
                if let Some(metrics) = &self.metrics {
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connection_acquisition_total",
                        &["failure"],
                    );
                }

                log::warn!("Failed to get connection from pool: {}", e);
                Err(ClickhouseError::Pool(e.to_string()))
            }
            Err(_) => {
                if let Some(metrics) = &self.metrics {
                    metrics.inc_int_counter_vec_mut(
                        "clickhouse_connection_acquisition_total",
                        &["timeout"],
                    );
                }

                log::warn!(
                    "Timed out waiting for connection after {:?}",
                    timeout_duration
                );
                Err(ClickhouseError::Timeout)
            }
        }
    }

    pub async fn shutdown(&self) -> Result<(), ClickhouseError> {
        log::info!("Initiating graceful shutdown of ClickHouse connection pool");

        let pool_manager = self.pool.manager();
        pool_manager.initiate_shutdown();

        let status = self.pool.status();
        log::info!(
            "Connection pool status before shutdown: size={}, available={}, in_use={}",
            status.size,
            status.available,
            status.size - status.available
        );

        let drain_timeout = Duration::from_secs(30);
        let drain_start = Instant::now();

        loop {
            let status = self.pool.status();
            let in_use = status.size - status.available;

            if in_use == 0 {
                log::info!("All connections returned to pool, proceeding with shutdown");
                break;
            }

            if drain_start.elapsed() > drain_timeout {
                log::warn!(
                    "Shutdown drain timeout exceeded, {} connections still in use",
                    in_use
                );

                break;
            }

            log::info!("Waiting for {} connections to be returned to pool", in_use);
            tokio::time::sleep(Duration::from_secs(1)).await;
        }

        // Close all connections
        self.pool.close();
        log::info!("All connections closed");

        log::info!("ClickHouse connection pool shutdown complete");

        Ok(())
    }

    fn register_metrics(metrics: &SharedRegistrar) {
        let metric_configs = [
            // Connection
            MetricConfig {
                kind: Kind::IntCounterVec,
                name: "clickhouse_connections_created_total",
                help: "Total no. of connections created",
                label_names: &["status"],
            },
            MetricConfig {
                kind: Kind::IntGaugeVec,
                name: "clickhouse_pool_connections",
                help: "Current no. of connections in the pool",
                label_names: &["state"],
            },
            MetricConfig {
                kind: Kind::IntCounterVec,
                name: "clickhouse_connetion_health_checks_total",
                help: "Total no. of connection health checks",
                label_names: &["status"],
            },
            MetricConfig {
                kind: Kind::GaugeVec,
                name: "clickhouse_connection_creation_seconds",
                help: "Time taken to create connections",
                label_names: &["operation"],
            },
            // Queries
            MetricConfig {
                kind: Kind::IntCounterVec,
                name: "clickhouse_queries_total",
                help: "Total no. of queries executed",
                label_names: &["type"],
            },
            MetricConfig {
                kind: Kind::IntCounterVec,
                name: "clickhouse_query_errors_total",
                help: "Total no. of query errors",
                label_names: &["type"],
            },
            MetricConfig {
                kind: Kind::GaugeVec,
                name: "clickhouse_query_duration_seconds",
                help: "Query execution time in seconds",
                label_names: &["type"],
            },
            // Batch queries
            MetricConfig {
                kind: Kind::IntCounterVec,
                name: "clickhouse_batch_query_errors_total",
                help: "Total number of batch query errors",
                label_names: &["type"],
            },
            MetricConfig {
                kind: Kind::GaugeVec,
                name: "clickhouse_batch_query_duration_seconds",
                help: "Batch query execution time in seconds",
                label_names: &["type"],
            },
            // Connection acquisition
            MetricConfig {
                kind: Kind::GaugeVec,
                name: "clickhouse_connection_acquisition_seconds",
                help: "Time taken to acquire a connection from the pool",
                label_names: &["status"],
            },
            MetricConfig {
                kind: Kind::IntCounterVec,
                name: "clickhouse_connection_acquisition_total",
                help: "Total number of connection acquisition attempts",
                label_names: &["status"],
            },
            MetricConfig {
                kind: Kind::IntCounterVec,
                name: "clickhouse_connections_recycled_total",
                help: "Total number of connections recycled",
                label_names: &["reason"],
            },
            MetricConfig {
                kind: Kind::GaugeVec,
                name: "clickhouse_connection_recycling_seconds",
                help: "Time taken for connection recycling",
                label_names: &["operation"],
            },            
        ];

        metrics.with_metric_configs(&metric_configs).ok();
    }

    pub fn status(&self) -> PoolMetrics {
        let status = self.pool.status();
        
        PoolMetrics {
            size: status.size,
            available: status.available,
            in_use: status.size - status.available,
            max_size: status.max_size,
            min_size: status.max_size,
            waiters: status.waiting,
        }
    }
}