Skip to content

Commit

Permalink
fix: use ConnectionGuard to track TCP connections correctly
Browse files Browse the repository at this point in the history
- Add ConnectionGuard in handle_client to track active connections
- Fix connection statistics not being updated
- Add debug logging for connection lifecycle
  • Loading branch information
aljen committed Dec 6, 2024
1 parent fa98bab commit 7a9608c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
7 changes: 7 additions & 0 deletions src/connection/guard.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{net::SocketAddr, sync::Arc};

use tokio::sync::OwnedSemaphorePermit;
use tracing::debug;

use super::ConnectionManager;

Expand All @@ -18,10 +19,16 @@ impl Drop for ConnectionGuard {
let manager = Arc::clone(&self.manager);
let addr = self.addr;

debug!("Closing connection from {}", addr);

tokio::spawn(async move {
let mut stats = manager.stats.lock().await;
if let Some(client_stats) = stats.get_mut(&addr) {
client_stats.active_connections -= 1;
debug!(
"Connection from {} closed, active connections: {}",
addr, client_stats.active_connections
);
}
});
}
Expand Down
6 changes: 4 additions & 2 deletions src/modbus_relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,12 +467,14 @@ async fn handle_client(
manager: Arc<ConnectionManager>,
) -> Result<(), RelayError> {
let start_time = Instant::now();
manager.record_request(peer_addr, true).await;

// Create connection guard to track this connection
let _guard = manager.accept_connection(peer_addr).await?;

let result = handle_client_inner(stream, peer_addr, transport, manager.clone()).await;

if result.is_err() {
manager.record_request(peer_addr, false).await;
manager.record_client_error(&peer_addr).await?;
}

manager.record_response_time(start_time.elapsed()).await;
Expand Down

0 comments on commit 7a9608c

Please sign in to comment.