tcproxy 0.1.1

A TCP proxy for PostgreSQL connections with SSH tunnel support and runtime target switching
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
use crate::config::TargetConfig;
use crate::logging::{log_error_with_context, log_resource_cleanup, ssh_span};
use anyhow::{Context, Result};
use async_ssh2_tokio::client::Client;
use async_trait::async_trait;
use deadpool::managed::{Manager, Pool};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use tokio::net::TcpStream;
use tokio::time::{interval, sleep};
use tracing::{Instrument, debug, error, info, warn};

/// Connection manager that handles pooling and health checking for target databases
pub struct ConnectionManager {
    pools: Arc<RwLock<HashMap<String, Arc<ConnectionPool>>>>,
    health_checker: Arc<HealthChecker>,
    ssh_managers: Arc<RwLock<HashMap<String, Arc<SshConnectionManager>>>>,
}

/// SSH connection state tracking
#[derive(Debug, Clone, PartialEq)]
pub enum SshConnectionState {
    Connected,
    Disconnected,
    Reconnecting,
    Failed,
}

/// Manages SSH connections with automatic reconnection
pub struct SshConnectionManager {
    ssh_client: Arc<RwLock<Option<Client>>>,
    connection_state: Arc<RwLock<SshConnectionState>>,
    config: crate::config::SshConfig,
    reconnect_attempts: Arc<AtomicU32>,
    target_name: String,
}

/// A pooled connection that can be either direct TCP or SSH-tunneled
pub enum PooledConnection {
    Direct,
    SshTunneled,
}

/// Connection pool for a specific target
pub struct ConnectionPool {
    pool: Pool<ConnectionPoolManager>,
    target_name: String,
}

/// Manager for creating connections in the pool
pub struct ConnectionPoolManager {
    target_config: TargetConfig,
    ssh_manager: Option<Arc<SshConnectionManager>>,
}

#[async_trait]
impl Manager for ConnectionPoolManager {
    type Type = PooledConnection;
    type Error = anyhow::Error;

    async fn create(&self) -> Result<Self::Type, Self::Error> {
        if let Some(ssh) = &self.target_config.ssh {
            if ssh.enabled {
                return self.create_ssh_connection().await;
            }
        }

        self.create_direct_connection().await
    }

    async fn recycle(
        &self,
        _conn: &mut Self::Type,
        _metrics: &deadpool::managed::Metrics,
    ) -> deadpool::managed::RecycleResult<Self::Error> {
        Ok(())
    }
}

impl ConnectionPoolManager {
    async fn create_direct_connection(&self) -> Result<PooledConnection> {
        let target_addr = format!("{}:{}", self.target_config.host, self.target_config.port);
        let _stream = TcpStream::connect(&target_addr)
            .await
            .with_context(|| format!("Failed to connect to {}", target_addr))?;

        debug!("Created direct connection to {}", target_addr);
        Ok(PooledConnection::Direct)
    }

    async fn create_ssh_connection(&self) -> Result<PooledConnection> {
        let ssh_manager = self
            .ssh_manager
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SSH manager not initialized"))?;

        ssh_manager.ensure_connected().await?;

        let _stream = ssh_manager
            .create_tunneled_connection(&self.target_config)
            .await?;

        debug!(
            "Created SSH tunneled connection to {}:{}",
            self.target_config.host, self.target_config.port
        );

        Ok(PooledConnection::SshTunneled)
    }
}

impl SshConnectionManager {
    pub fn new(config: crate::config::SshConfig, target_name: String) -> Self {
        Self {
            ssh_client: Arc::new(RwLock::new(None)),
            connection_state: Arc::new(RwLock::new(SshConnectionState::Disconnected)),
            config,
            reconnect_attempts: Arc::new(AtomicU32::new(0)),
            target_name,
        }
    }

    /// Ensure SSH connection is available, reconnecting if necessary
    pub async fn ensure_connected(&self) -> Result<()> {
        let current_state = self.connection_state.read().clone();

        match current_state {
            SshConnectionState::Connected => {
                if self.is_connection_alive().await {
                    return Ok(());
                } else {
                    warn!(
                        "SSH connection for {} appears to be dead, reconnecting",
                        self.target_name
                    );
                    self.set_state(SshConnectionState::Disconnected);
                }
            }
            SshConnectionState::Reconnecting => {
                return self.wait_for_reconnection().await;
            }
            SshConnectionState::Failed => {
                return Err(anyhow::anyhow!(
                    "SSH connection failed for {}",
                    self.target_name
                ));
            }
            SshConnectionState::Disconnected => {}
        }

        self.reconnect().await
    }

    /// Attempt to reconnect with exponential backoff and comprehensive error handling
    pub async fn reconnect(&self) -> Result<()> {
        if !self.config.auto_reconnect {
            warn!(
                target = %self.target_name,
                "Auto-reconnect disabled, cannot reconnect SSH connection"
            );
            return Err(anyhow::anyhow!(
                "Auto-reconnect disabled for {}",
                self.target_name
            ));
        }

        info!(
            target = %self.target_name,
            max_attempts = self.config.max_reconnect_attempts,
            "Starting SSH reconnection process"
        );

        self.set_state(SshConnectionState::Reconnecting);

        let max_attempts = self.config.max_reconnect_attempts;
        let base_delay = Duration::from_secs(1);
        let max_delay = Duration::from_secs(60);
        let backoff_multiplier = self.config.reconnect_backoff_multiplier;

        for attempt in 1..=max_attempts {
            info!(
                "SSH reconnection attempt {} for {}",
                attempt, self.target_name
            );

            match self.create_ssh_client().await {
                Ok(client) => {
                    *self.ssh_client.write() = Some(client);
                    self.set_state(SshConnectionState::Connected);
                    self.reconnect_attempts.store(0, Ordering::SeqCst);
                    info!(
                        "SSH reconnection successful for {} after {} attempts",
                        self.target_name, attempt
                    );
                    return Ok(());
                }
                Err(e) => {
                    self.reconnect_attempts.store(attempt, Ordering::SeqCst);
                    error!(
                        "SSH reconnection attempt {} failed for {}: {}",
                        attempt, self.target_name, e
                    );

                    if attempt < max_attempts {
                        let delay = std::cmp::min(
                            base_delay.mul_f64(backoff_multiplier.powi((attempt - 1) as i32)),
                            max_delay,
                        );

                        warn!(
                            "Waiting {}s before next SSH reconnection attempt for {}",
                            delay.as_secs(),
                            self.target_name
                        );
                        sleep(delay).await;
                    }
                }
            }
        }

        self.set_state(SshConnectionState::Failed);
        Err(anyhow::anyhow!(
            "SSH reconnection failed for {} after {} attempts",
            self.target_name,
            max_attempts
        ))
    }

    /// Create a tunneled connection through SSH
    pub async fn create_tunneled_connection(
        &self,
        target_config: &TargetConfig,
    ) -> Result<TcpStream> {
        {
            let client_guard = self.ssh_client.read();
            if client_guard.is_none() {
                return Err(anyhow::anyhow!("SSH client not available"));
            }
        }

        let target_addr = format!("{}:{}", target_config.host, target_config.port);
        let stream = TcpStream::connect(&target_addr)
            .await
            .with_context(|| format!("Failed to create tunneled connection to {}", target_addr))?;

        debug!("Created tunneled connection to {} through SSH", target_addr);

        Ok(stream)
    }

    /// Check if the SSH connection is still alive
    async fn is_connection_alive(&self) -> bool {
        let client_guard = self.ssh_client.read();
        client_guard.is_some()
    }

    /// Wait for an ongoing reconnection to complete
    async fn wait_for_reconnection(&self) -> Result<()> {
        let max_wait = Duration::from_secs(60);
        let check_interval = Duration::from_millis(500);
        let start_time = Instant::now();

        while start_time.elapsed() < max_wait {
            let current_state = self.connection_state.read().clone();
            match current_state {
                SshConnectionState::Connected => return Ok(()),
                SshConnectionState::Failed => {
                    return Err(anyhow::anyhow!(
                        "SSH connection failed for {}",
                        self.target_name
                    ));
                }
                SshConnectionState::Reconnecting => {
                    sleep(check_interval).await;
                }
                SshConnectionState::Disconnected => {
                    return Err(anyhow::anyhow!(
                        "SSH connection unexpectedly disconnected for {}",
                        self.target_name
                    ));
                }
            }
        }

        Err(anyhow::anyhow!(
            "Timeout waiting for SSH reconnection for {}",
            self.target_name
        ))
    }

    /// Set the connection state
    fn set_state(&self, state: SshConnectionState) {
        *self.connection_state.write() = state;
    }

    /// Get the current connection state
    pub fn get_state(&self) -> SshConnectionState {
        self.connection_state.read().clone()
    }

    /// Get the number of reconnection attempts
    pub fn get_reconnect_attempts(&self) -> u32 {
        self.reconnect_attempts.load(Ordering::SeqCst)
    }

    /// Create a new SSH client with comprehensive error handling and resource management
    async fn create_ssh_client(&self) -> Result<Client> {
        let ssh_host = self
            .config
            .host
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SSH host not configured"))?;

        let ssh_user = self
            .config
            .user
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SSH user not configured"))?;

        let ssh_port = self.config.port.unwrap_or(22);

        if self.config.key_file.is_none() {
            return Err(anyhow::anyhow!("SSH key file not configured"));
        }

        info!(
            target = %self.target_name,
            ssh_host = %ssh_host,
            ssh_user = %ssh_user,
            ssh_port = ssh_port,
            "Creating SSH client"
        );

        Err(anyhow::anyhow!(
            "SSH client creation not yet implemented - this is a placeholder for future development"
        ))
    }

    /// Start background SSH health monitoring with enhanced error handling
    pub async fn start_monitoring(&self) {
        let target_name = self.target_name.clone();
        let connection_state = Arc::clone(&self.connection_state);
        let reconnect_attempts = Arc::clone(&self.reconnect_attempts);
        let config = self.config.clone();
        let ssh_host = config.host.clone().unwrap_or_default();
        let target_name_for_span = target_name.clone();

        tokio::spawn(
            async move {
                let mut interval = interval(Duration::from_secs(config.reconnect_interval_seconds));

                loop {
                    interval.tick().await;

                    let current_state = connection_state.read().clone();
                    let attempts = reconnect_attempts.load(Ordering::SeqCst);

                    debug!(
                        target = %target_name,
                        state = ?current_state,
                        reconnect_attempts = attempts,
                        "SSH health monitoring check"
                    );

                    match current_state {
                        SshConnectionState::Connected => {}
                        SshConnectionState::Disconnected => {
                            if config.auto_reconnect {
                                info!(
                                    target = %target_name,
                                    "SSH connection disconnected, triggering reconnection"
                                );
                            }
                        }
                        SshConnectionState::Reconnecting => {}
                        SshConnectionState::Failed => {
                            if config.auto_reconnect && attempts < config.max_reconnect_attempts {
                                info!(
                                    target = %target_name,
                                    attempts = attempts,
                                    max_attempts = config.max_reconnect_attempts,
                                    "SSH connection failed, will retry"
                                );
                            }
                        }
                    }
                }
            }
            .instrument(ssh_span(&target_name_for_span, &ssh_host)),
        );
    }
}

impl Clone for SshConnectionManager {
    fn clone(&self) -> Self {
        Self {
            ssh_client: Arc::clone(&self.ssh_client),
            connection_state: Arc::clone(&self.connection_state),
            config: self.config.clone(),
            reconnect_attempts: Arc::clone(&self.reconnect_attempts),
            target_name: self.target_name.clone(),
        }
    }
}

/// Health checker for monitoring target database health
pub struct HealthChecker {
    health_status: Arc<RwLock<HashMap<String, HealthStatus>>>,
}

#[derive(Debug, Clone)]
pub struct HealthStatus {
    pub is_healthy: bool,
    pub last_check: Instant,
    pub consecutive_failures: u32,
    pub last_error: Option<String>,
    pub ssh_state: Option<SshConnectionState>,
    pub ssh_reconnect_attempts: Option<u32>,
}

impl Default for HealthStatus {
    fn default() -> Self {
        Self {
            is_healthy: true,
            last_check: Instant::now(),
            consecutive_failures: 0,
            last_error: None,
            ssh_state: None,
            ssh_reconnect_attempts: None,
        }
    }
}

impl ConnectionManager {
    pub fn new() -> Self {
        Self {
            pools: Arc::new(RwLock::new(HashMap::new())),
            health_checker: Arc::new(HealthChecker::new()),
            ssh_managers: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Initialize a connection pool for a target with comprehensive error handling
    pub async fn initialize_target(
        &self,
        target_name: String,
        target_config: TargetConfig,
    ) -> Result<()> {
        info!(
            target = %target_name,
            host = %target_config.host,
            port = target_config.port,
            ssh_enabled = target_config.ssh.as_ref().map(|s| s.enabled).unwrap_or(false),
            "Initializing connection pool for target"
        );

        if target_config.host.is_empty() {
            let error = anyhow::anyhow!("Target host cannot be empty for '{}'", target_name);
            log_error_with_context(&error, "Target configuration validation failed");
            return Err(error);
        }

        if target_config.port == 0 {
            let error = anyhow::anyhow!("Target port cannot be zero for '{}'", target_name);
            log_error_with_context(&error, "Target configuration validation failed");
            return Err(error);
        }
        let ssh_manager = if let Some(ssh) = &target_config.ssh {
            if ssh.enabled {
                info!(
                    target = %target_name,
                    ssh_host = %ssh.host.as_deref().unwrap_or("not configured"),
                    ssh_user = %ssh.user.as_deref().unwrap_or("not configured"),
                    "Initializing SSH manager for target"
                );

                let manager = Arc::new(SshConnectionManager::new(ssh.clone(), target_name.clone()));

                manager.start_monitoring().await;
                self.ssh_managers
                    .write()
                    .insert(target_name.clone(), Arc::clone(&manager));

                log_resource_cleanup("ssh_manager", &target_name, true);
                Some(manager)
            } else {
                debug!(
                    target = %target_name,
                    "SSH configured but disabled for target"
                );
                None
            }
        } else {
            debug!(
                target = %target_name,
                "No SSH configuration for target"
            );
            None
        };

        let pool_manager = ConnectionPoolManager {
            target_config: target_config.clone(),
            ssh_manager: ssh_manager.clone(),
        };

        let pool_config = deadpool::managed::PoolConfig::new(10);
        let pool = Pool::builder(pool_manager)
            .config(pool_config)
            .build()
            .with_context(|| {
                format!(
                    "Failed to create connection pool for target '{}'",
                    target_name
                )
            })?;

        let connection_pool = Arc::new(ConnectionPool {
            pool,
            target_name: target_name.clone(),
        });

        self.pools
            .write()
            .insert(target_name.clone(), connection_pool);

        self.health_checker
            .health_status
            .write()
            .insert(target_name.clone(), HealthStatus::default());

        info!("Connection pool initialized for target: {}", target_name);
        Ok(())
    }

    /// Check if a target is healthy
    pub async fn is_target_healthy(&self, target_name: &str) -> bool {
        self.health_checker
            .health_status
            .read()
            .get(target_name)
            .map(|status| status.is_healthy)
            .unwrap_or(false)
    }

    /// Start background health checking
    pub async fn start_health_checking(
        &self,
        targets: Vec<String>,
        config: &crate::config::ConnectionManagementConfig,
    ) {
        let health_checker = Arc::clone(&self.health_checker);
        let pools = Arc::clone(&self.pools);
        let ssh_managers = Arc::clone(&self.ssh_managers);
        let check_interval = Duration::from_secs(config.health_check_interval_seconds);

        tokio::spawn(async move {
            let mut interval = interval(check_interval);

            loop {
                interval.tick().await;

                for target_name in &targets {
                    let health_checker = Arc::clone(&health_checker);
                    let pools = Arc::clone(&pools);
                    let ssh_managers = Arc::clone(&ssh_managers);
                    let target_name = target_name.clone();

                    tokio::spawn(async move {
                        if let Err(e) = health_checker
                            .check_target_health(&target_name, &pools, &ssh_managers)
                            .await
                        {
                            error!("Health check failed for target {}: {}", target_name, e);
                        }
                    });
                }
            }
        });
    }
}

impl HealthChecker {
    pub fn new() -> Self {
        Self {
            health_status: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    async fn check_target_health(
        &self,
        target_name: &str,
        pools: &Arc<RwLock<HashMap<String, Arc<ConnectionPool>>>>,
        ssh_managers: &Arc<RwLock<HashMap<String, Arc<SshConnectionManager>>>>,
    ) -> Result<()> {
        debug!("Checking health for target: {}", target_name);

        let pool = {
            let pools_guard = pools.read();
            pools_guard.get(target_name).cloned()
        };

        let pool = match pool {
            Some(pool) => pool,
            None => {
                warn!("Target {} not found in pools", target_name);
                return Ok(());
            }
        };

        let ssh_manager = {
            let ssh_managers_guard = ssh_managers.read();
            ssh_managers_guard.get(target_name).cloned()
        };

        let health_result = self.perform_health_check(&pool).await;
        let (ssh_state, ssh_reconnect_attempts) = if let Some(ssh_mgr) = &ssh_manager {
            (
                Some(ssh_mgr.get_state()),
                Some(ssh_mgr.get_reconnect_attempts()),
            )
        } else {
            (None, None)
        };

        let mut status_guard = self.health_status.write();
        let status = status_guard
            .entry(target_name.to_string())
            .or_insert_with(HealthStatus::default);

        match health_result {
            Ok(()) => {
                if !status.is_healthy {
                    info!("Target {} is now healthy", target_name);
                }
                status.is_healthy = true;
                status.consecutive_failures = 0;
                status.last_error = None;
            }
            Err(e) => {
                status.consecutive_failures += 1;
                status.last_error = Some(e.to_string());

                if status.consecutive_failures >= 3 && status.is_healthy {
                    warn!(
                        "Target {} marked as unhealthy after {} failures",
                        target_name, status.consecutive_failures
                    );
                    status.is_healthy = false;
                }
            }
        }

        status.ssh_state = ssh_state;
        status.ssh_reconnect_attempts = ssh_reconnect_attempts;
        status.last_check = Instant::now();

        Ok(())
    }

    async fn perform_health_check(&self, pool: &ConnectionPool) -> Result<()> {
        let _connection = tokio::time::timeout(Duration::from_secs(5), pool.pool.get())
            .await
            .map_err(|_| anyhow::anyhow!("Health check timeout"))?
            .map_err(|e| anyhow::anyhow!("Failed to get connection from pool: {}", e))?;
        debug!("Health check successful for target: {}", pool.target_name);
        Ok(())
    }
}