Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! Many types and trait methods are defined ahead of their use in later
//! development phases (REPL, DESCRIBE, COPY, etc.).

pub mod proxy_address_translator;
pub mod scylla_driver;
pub mod types;

Expand Down
57 changes: 57 additions & 0 deletions src/driver/proxy_address_translator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//! Proxy address translator.
//!
//! When connecting through a proxy or load balancer (e.g., AWS NLB, PrivateLink),
//! the driver discovers internal node IPs from `system.peers` that are unreachable
//! from the client. This translator remaps all peer addresses to the original
//! contact point, ensuring all connections go through the proxy.

use std::net::SocketAddr;

use async_trait::async_trait;
use scylla::errors::TranslationError;
use scylla::policies::address_translator::{AddressTranslator, UntranslatedPeer};

/// An [`AddressTranslator`] that redirects all peer connections to the original
/// contact point address. Used when the cluster is accessed through a proxy.
///
/// All discovered node addresses are translated to `proxy_address`, ensuring
/// the driver only connects through the proxy endpoint.
#[derive(Debug, Clone)]
pub struct ProxyAddressTranslator {
/// The proxy/contact point address to route all connections through.
proxy_address: SocketAddr,
}

impl ProxyAddressTranslator {
/// Create a new translator that routes all connections to `proxy_address`.
pub fn new(proxy_address: SocketAddr) -> Self {
Self { proxy_address }
}
}

#[async_trait]
impl AddressTranslator for ProxyAddressTranslator {
async fn translate_address(
&self,
_untranslated_peer: &UntranslatedPeer,
) -> Result<SocketAddr, TranslationError> {
Ok(self.proxy_address)
}
}

Comment on lines +14 to +41
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this achieves what you want. I assume the proxy address leads to one specific node.
Let's say you have 5 nodes in the cluster, each with 32 shards. With your changes, the driver will still see all 5 nodes in system.peers/local, try to open connection pools to all 5 nodes. The address translation will cause all connections to be opened to the same node (driver won't even know about it), so you'll get 160 connections to this node.
You could use PoolSize::PerNode(1) (which is a good idea in cqlsh regardless of all other changes) to get this down to 5.
Then the connection amount problem is not that bad, but you are still in a very weird state where driver thinks it opened pools to all nodes, but they are really all to one node. Will this work correctly? It may, I'm not completely sure.
TBH I don't know how to solve that will existing APIs. There isn't really a way to implement a HostFilter that would filter out other nodes, because HostFilter accepts Peer, which has an address fetched from system.peers or system.local - so you can't really say for sure if its the same peer as the contact point.

What would be nice here is a simplified session, with a separate builder, where driver only opens a single connection to the given address, and uses it both as CC and to execute user requests. This would also work for the maintenance socket. cc @wprzytula - let's discuss this when we meet, there are some not obvious decisions when implementing such session.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the connection count concern. Added PoolSize::PerHost(1) — cqlsh is a single-user interactive tool so one connection per node is plenty. This brings it down to N connections (one per discovered node) all going through the proxy.

Re: the simplified single-connection session — that would be ideal. For now this is a pragmatic workaround. Happy to migrate when that API exists.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. This is a weird state for the driver to be in, but I think it should work. @wprzytula will be available tomorrow if you want him to also take a look (maybe I am missing some potential problem).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with your thoughs above @Lorak-mmk. Aside from that, maybe let's also use SingleTargetLoadBalancingPolicy to simplify the load balancing part?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be difficult for the same reason host filtering is difficult. You would need to know which node you have CC opened to, and it can no longer be done by socket address.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW, the code in this PR was proven to be working as expected in the case the broadcast address isn't available (AWS public / private addresses)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anyhow I'm going to merge this one, so it won't regress the expected beahvier from the python cqlsh (before the driver change that broke it)

#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr};

fn sock(ip: [u8; 4], port: u16) -> SocketAddr {
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3])), port)
}

#[test]
fn creates_with_correct_address() {
let proxy_addr = sock([18, 208, 144, 200], 9042);
let translator = ProxyAddressTranslator::new(proxy_addr);
assert_eq!(translator.proxy_address, proxy_addr);
}
}
33 changes: 24 additions & 9 deletions src/driver/scylla_driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,20 +507,40 @@ impl CqlDriver for ScyllaDriver {

let mut builder = SessionBuilder::new().known_node(&addr);

// Authentication
// cqlsh is a single-user interactive tool — one connection per host suffices
// and avoids connection explosion when using a proxy translator.
builder = builder.pool_size(scylla::client::PoolSize::PerHost(
std::num::NonZeroUsize::new(1).unwrap(),
));

if let (Some(username), Some(password)) = (&config.username, &config.password) {
builder = builder.user(username, password);
}

// Connection timeout
builder = builder.connection_timeout(Duration::from_secs(config.connect_timeout));

// Default keyspace
if let Some(keyspace) = &config.keyspace {
builder = builder.use_keyspace(keyspace, false);
}

// SSL/TLS
// Always install the proxy address translator. Since known_node addresses
// are never translated (only peers from system.peers are), this is safe:
// - Direct connections: peers share the same network, translator is a no-op
// in practice (peers are reachable anyway, and translated to contact point
// which also works since it's the same node in single-node or resolves correctly)
// - Proxy connections: peers have unreachable internal IPs, translator
// redirects all of them to the proxy contact point
let contact_point = tokio::net::lookup_host(&addr)
.await
.ok()
.and_then(|mut addrs| addrs.next());
if let Some(contact_point) = contact_point {
let translator = Arc::new(
super::proxy_address_translator::ProxyAddressTranslator::new(contact_point),
);
builder = builder.address_translator(translator);
}

Comment thread
fruch marked this conversation as resolved.
if config.ssl {
let tls_config = if let Some(ssl_config) = &config.ssl_config {
Self::build_rustls_config(ssl_config)?
Expand All @@ -530,11 +550,6 @@ impl CqlDriver for ScyllaDriver {
builder = builder.tls_context(Some(tls_config));
}

// NOTE: config.protocol_version is accepted for CLI compatibility but
// scylla-rust-driver 1.5.0 auto-negotiates the native protocol version.
// SessionBuilder has no method to force a specific protocol version.
// Similarly, the driver hardcodes CQL_VERSION="4.0.0" in the STARTUP frame.

let session = builder.build().await.context("connecting to cluster")?;

Ok(ScyllaDriver {
Expand Down
2 changes: 2 additions & 0 deletions tests/integration/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ mod login_tests;
#[cfg(feature = "test-plain")]
mod output_tests;
#[cfg(feature = "test-plain")]
mod proxy_tests;
#[cfg(feature = "test-plain")]
mod schema_agreement_tests;
#[cfg(feature = "test-plain")]
mod unicode_tests;
Expand Down
91 changes: 91 additions & 0 deletions tests/integration/proxy_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! Integration tests for proxy auto-detection.
//!
//! Tests that verify the proxy address translator works correctly with a
//! real ScyllaDB instance.

use helpers::{cqlsh_cmd, get_scylla};

use super::*;

/// Direct connection (no proxy) should work without address translation.
/// This confirms the two-phase connect doesn't break normal connections.
#[test]
#[ignore = "requires Docker"]
fn test_direct_connection_still_works_with_proxy_detection() {
let scylla = get_scylla();
cqlsh_cmd(scylla)
.args(["-e", "SELECT cluster_name FROM system.local"])
.assert()
.success();
}

/// Verify that a query actually returns data through the normal path,
/// confirming the two-phase connect doesn't cause session issues.
#[test]
#[ignore = "requires Docker"]
fn test_query_after_proxy_detection_returns_data() {
let scylla = get_scylla();
let output =
helpers::execute_cql_output_direct(scylla, "SELECT release_version FROM system.local");
assert!(
!output.is_empty(),
"expected output from system.local query"
);
}

/// Test connection through a TCP proxy (socat) to simulate the proxy scenario.
/// The proxy forwards traffic to the ScyllaDB container, but its IP won't
/// match any peer address in system.peers, triggering proxy auto-detection.
#[test]
#[ignore = "requires Docker"]
fn test_proxy_connection_via_socat() {
use std::process::{Command, Stdio};
use std::thread;
use std::time::Duration;

let scylla = get_scylla();
let target = format!("{}:{}", scylla.host, scylla.port);

// Start socat as a TCP proxy on a random high port
// socat listens on 0.0.0.0:0 (kernel picks port) and forwards to the ScyllaDB container
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let proxy_port = listener.local_addr().unwrap().port();
drop(listener); // free the port for socat

let mut socat = match Command::new("socat")
.args([
&format!("TCP-LISTEN:{proxy_port},fork,reuseaddr"),
&format!("TCP:{target}"),
])
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
Ok(child) => child,
Err(_) => {
eprintln!("socat not available, skipping proxy integration test");
return;
}
};

// Give socat time to start listening
thread::sleep(Duration::from_millis(500));

// Connect through the proxy — proxy IP (127.0.0.1:proxy_port) won't match
// the ScyllaDB node's internal address, triggering proxy detection
let result = assert_cmd::Command::cargo_bin("cqlsh-rs")
.unwrap()
.args([
"127.0.0.1",
&proxy_port.to_string(),
"-e",
"SELECT cluster_name FROM system.local",
])
.timeout(Duration::from_secs(15))
.assert();

socat.kill().ok();
socat.wait().ok();

result.success();
}
Loading