fix(rdsdata): refresh backend endpoints before JDBC connect (#6148)

* refactor(rdsdata): carry backend runtime identity

* fix(rdsdata): resolve runtime endpoint before JDBC connect

* test(rdsdata): cover backend endpoint refresh

* refactor(rds): make backend gates runtime-only

* test(rds): enforce proxy runtime identity

* test(rdsdata): reuse proxy endpoint refresh backends

* docs(rds): fix backend gate Javadoc link
This commit is contained in:
joão pedro brito authored and GitHub committed 2026-10-22 16:02:10 -04:00
1 parent d2f2625005
commit b58947c70a
17 files changed
+350 -146

No files matched your search

@@ -3847,6 +3847,11 @@ public class RdsService implements Resettable, ResourceProvider {
return instance;
}
/** Returns the runtime that owns an instance's backing container. Cluster members share their cluster runtime. */
public String instanceBackendRuntimeId(DbInstance instance) {
return instanceBackendIdentity(instance).runtimeId();
}
private InstanceBackendIdentity instanceBackendIdentity(DbInstance instance) {
String clusterId = instance.getDbClusterIdentifier();
if (clusterId != null && !clusterId.isBlank()) {
@@ -0,0 +1,11 @@
package io.github.hectorvent.floci.services.rds.container;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
/** Resolves the current reachable endpoint of the container owned by an RDS runtime. */
@FunctionalInterface
public interface RdsBackendEndpointResolver {
EndpointInfo resolveBackendEndpoint(String runtimeId, DatabaseEngine engine);
}
@@ -8,32 +8,23 @@ package io.github.hectorvent.floci.services.rds.container;
public interface RdsBackendGate {
/** A gate for backends that never pause. */
RdsBackendGate OPEN = (host, port) -> Lease.NONE;
RdsBackendGate OPEN = runtimeId -> Lease.NONE;
/**
* Waits until the container serving {@code host:port} can take a client, resuming it when it
* Waits until the container owned by {@code runtimeId} can take a client, resuming it when it
* is auto-paused, and keeps it awake until the lease is closed. A backend with no auto-pause
* gets {@link Lease#NONE}.
*
* @throws InterruptedException when interrupted while a pause or resume is under way
*/
Lease enter(String host, int port) throws InterruptedException;
Lease enterRuntime(String runtimeId) throws InterruptedException;
/**
* Like {@link #enter(String, int)}, but with {@code waitForResume=false} starts resume in the
* background and throws {@link ResumingException} if the backend is not yet ready.
* Backends without auto-pause may use this default implementation.
* Like {@link #enterRuntime(String)}, but with {@code waitForResume=false} starts resume in the
* background and throws {@link ResumingException} if the runtime is not yet ready.
*/
default Lease enter(String host, int port, boolean waitForResume) throws InterruptedException {
return enter(host, port);
}
/**
* Enters the container owned by {@code runtimeId}. Backends that do not track runtime
* identities may use this default implementation.
*/
default Lease enterRuntime(String runtimeId) throws InterruptedException {
return Lease.NONE;
default Lease enterRuntime(String runtimeId, boolean waitForResume) throws InterruptedException {
return enterRuntime(runtimeId);
}
/** The backend is being resumed; no lease was acquired and the caller must retry. */
@@ -51,11 +51,11 @@ import java.util.regex.Pattern;
/**
* Manages backend Docker container lifecycle for RDS DB instances and clusters.
* Starts postgres/mysql/mariadb containers and resolves the backend host:port for the auth proxy.
* Every client of a container enters it through {@link #enter}, which is how an Aurora Serverless
* Every client of a container enters it through {@link #enterRuntime(String)}, which is how an Aurora Serverless
* v2 cluster with MinCapacity 0 knows when it is idle enough to pause and when to resume.
*/
@ApplicationScoped
public class RdsContainerManager implements RdsBackendGate, Resettable {
public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointResolver, Resettable {
private static final Logger LOG = Logger.getLogger(RdsContainerManager.class);
private static final Pattern SAFE_STORAGE_COMPONENT = Pattern.compile("[A-Za-z0-9._-]+");
@@ -516,26 +516,16 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
@Override
public Lease enterRuntime(String runtimeId) throws InterruptedException {
AutoPauseController controller = runtimeId != null ? autoPauses.get(runtimeId) : null;
return controller != null ? controller.acquire() : Lease.NONE;
return enterRuntime(runtimeId, true);
}
@Override
public Lease enter(String host, int port) throws InterruptedException {
return enter(host, port, true);
}
@Override
public Lease enter(String host, int port, boolean waitForResume) throws InterruptedException {
if (host == null) {
return Lease.NONE;
public Lease enterRuntime(String runtimeId, boolean waitForResume) throws InterruptedException {
if (runtimeId == null || runtimeId.isBlank()) {
throw new IllegalArgumentException("RDS runtime ID is required to enter its backend");
}
for (AutoPauseController controller : autoPauses.values()) {
if (controller.serves(host, port)) {
return controller.acquire(waitForResume);
}
}
return Lease.NONE;
AutoPauseController controller = autoPauses.get(runtimeId);
return controller != null ? controller.acquire(waitForResume) : Lease.NONE;
}
/**
@@ -571,8 +561,8 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
AutoPauseController controller = new AutoPauseController(
handle.getContainerId(), handle.getHost(), handle.getPort(), dockerFreezer,
this::scheduleAutoPauseTask, autoPauseEvents, Clock.systemUTC(), resumeDelay);
// Clients find a container by its address, so the new container owns it from now on,
// even if Docker removed the previous owner without Floci stopping it.
// Drop any controller still tied to this endpoint: Docker may have removed its container
// without Floci observing the stop before assigning the endpoint to this runtime.
for (Map.Entry<String, AutoPauseController> entry : List.copyOf(autoPauses.entrySet())) {
if (entry.getValue().serves(handle.getHost(), handle.getPort())
&& autoPauses.remove(entry.getKey(), entry.getValue())) {
@@ -51,32 +51,35 @@ public class RdsAuthProxy {
Duration acceptRetirementTimeout = Duration.ofSeconds(5);
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
String backendRuntimeId,
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
MasterPasswordCheck passwordValidator,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections) {
this(instanceId, backendHost, backendPort, engine, iamEnabled, masterUsername, masterPassword,
dbName, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
backendConnectTimeoutMillis, maxConnections, null, username -> false,
RdsBackendGate.OPEN);
this(instanceId, backendHost, backendPort, backendRuntimeId, engine, iamEnabled,
masterUsername, masterPassword, dbName, sigV4, tlsCertificates, passwordValidator,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, null,
username -> false, RdsBackendGate.OPEN);
}
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
String backendRuntimeId,
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
MasterPasswordCheck passwordValidator,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, RdsProxyBinding binding, RdsBackendGate backendGate) {
this(instanceId, backendHost, backendPort, engine, iamEnabled, masterUsername, masterPassword,
dbName, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
backendConnectTimeoutMillis, maxConnections, binding,
this(instanceId, backendHost, backendPort, backendRuntimeId, engine, iamEnabled,
masterUsername, masterPassword, dbName, sigV4, tlsCertificates, passwordValidator,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, binding,
username -> binding != null, backendGate);
}
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
String backendRuntimeId,
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
@@ -85,13 +88,14 @@ public class RdsAuthProxy {
int maxConnections, RdsProxyBinding binding,
MySqlProtocolHandler.IamUserChecker iamUserChecker,
RdsBackendGate backendGate) {
this(instanceId, backendHost, backendPort, engine, iamEnabled, masterUsername, masterPassword,
dbName, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
backendConnectTimeoutMillis, maxConnections, binding, iamUserChecker, backendGate,
EndpointKind.DATABASE);
this(instanceId, backendHost, backendPort, backendRuntimeId, engine, iamEnabled,
masterUsername, masterPassword, dbName, sigV4, tlsCertificates, passwordValidator,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, binding,
iamUserChecker, backendGate, EndpointKind.DATABASE);
}
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
String backendRuntimeId,
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
@@ -101,24 +105,7 @@ public class RdsAuthProxy {
MySqlProtocolHandler.IamUserChecker iamUserChecker,
RdsBackendGate backendGate, EndpointKind endpointKind) {
this(instanceId, backendHost, backendPort,
() -> new BackendEndpoint(backendHost, backendPort),
engine, iamEnabled, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, handshakeTimeoutMillis,
backendConnectTimeoutMillis, maxConnections, binding, iamUserChecker,
backendGate, endpointKind);
}
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
BackendEndpointResolver backendEndpointResolver,
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
MasterPasswordCheck passwordValidator,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, RdsProxyBinding binding,
MySqlProtocolHandler.IamUserChecker iamUserChecker,
RdsBackendGate backendGate, EndpointKind endpointKind) {
this(instanceId, backendHost, backendPort, backendEndpointResolver, null,
() -> new BackendEndpoint(backendHost, backendPort), backendRuntimeId,
engine, iamEnabled, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, handshakeTimeoutMillis,
backendConnectTimeoutMillis, maxConnections, binding, iamUserChecker,
@@ -135,6 +122,9 @@ public class RdsAuthProxy {
int maxConnections, RdsProxyBinding binding,
MySqlProtocolHandler.IamUserChecker iamUserChecker,
RdsBackendGate backendGate, EndpointKind endpointKind) {
if (backendRuntimeId == null || backendRuntimeId.isBlank()) {
throw new IllegalArgumentException("RDS backend runtime ID is required");
}
this.instanceId = instanceId;
this.backendHost = backendHost;
this.backendPort = backendPort;
@@ -241,9 +231,7 @@ public class RdsAuthProxy {
try {
// An auto-paused Aurora backend resumes before the client is served: the client is
// held, not refused, and the backend stays awake for as long as the connection lasts.
lease = backendRuntimeId != null
? backendGate.enterRuntime(backendRuntimeId)
: backendGate.enter(backendHost, backendPort);
lease = backendGate.enterRuntime(backendRuntimeId);
client.setTcpNoDelay(true);
// RDS only proxy-validates the master user; a non-master user passes through so the
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.rdsdata;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import jakarta.enterprise.context.ApplicationScoped;
@@ -18,10 +19,11 @@ class RdsDataConnectionFactory {
}
Connection open(RdsDataResourceResolver.DatabaseTarget target,
EndpointInfo endpoint,
String username,
String password,
String database) throws SQLException {
String url = buildUrl(target.engine(), target.host(), target.port(), database);
String url = buildUrl(target.engine(), endpoint.host(), endpoint.port(), database);
Properties props = new Properties();
props.setProperty("user", username);
props.setProperty("password", password);
@@ -78,25 +78,25 @@ class RdsDataResourceResolver {
&& !rdsService.hasMissingClusterMemberBackends(cluster, region)
? cluster
: rdsService.ensureClusterBackend(cluster.getDbClusterIdentifier(), region);
return target(resolved.getDbClusterArn(), resolved.getEngine(), resolved.getContainerHost(),
resolved.getContainerPort(), resolved.getMasterUsername(), resolved.getMasterPassword(),
resolved.getDatabaseName());
return target(resolved.getDbClusterArn(), resolved.getDbClusterArn(), resolved.getEngine(),
resolved.getContainerHost(), resolved.getContainerPort(), resolved.getMasterUsername(),
resolved.getMasterPassword(), resolved.getDatabaseName());
}
private DatabaseTarget fromInstance(DbInstance instance, String region) {
DbInstance resolved = hasRuntime(instance.getContainerHost(), instance.getContainerPort())
? instance
: rdsService.ensureInstanceBackend(instance.getDbInstanceIdentifier(), region);
return target(resolved.getDbInstanceArn(), resolved.getEngine(), resolved.getContainerHost(),
resolved.getContainerPort(), resolved.getMasterUsername(), resolved.getMasterPassword(),
resolved.getDbName());
return target(resolved.getDbInstanceArn(), rdsService.instanceBackendRuntimeId(resolved),
resolved.getEngine(), resolved.getContainerHost(), resolved.getContainerPort(),
resolved.getMasterUsername(), resolved.getMasterPassword(), resolved.getDbName());
}
private static boolean hasRuntime(String host, int port) {
return host != null && !host.isBlank() && port > 0;
}
private DatabaseTarget target(String arn, DatabaseEngine engine, String host, int port,
private DatabaseTarget target(String arn, String runtimeId, DatabaseEngine engine, String host, int port,
String username, String password, String databaseName) {
if (!hasRuntime(host, port)) {
// The Data API is RDS's data plane: it needs a real database, which Floci can only
@@ -111,10 +111,10 @@ class RdsDataResourceResolver {
throw new AwsException("BadRequestException",
"RDS resource runtime is not available for Data API execution.", 400);
}
return new DatabaseTarget(arn, engine, host, port, username, password, databaseName);
return new DatabaseTarget(arn, runtimeId, engine, username, password, databaseName);
}
record DatabaseTarget(String arn, DatabaseEngine engine, String host, int port,
record DatabaseTarget(String arn, String runtimeId, DatabaseEngine engine,
String username, String password, String databaseName) {
}
}
@@ -9,6 +9,8 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.DatabaseSecretCredentials;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.services.rds.container.RdsBackendEndpointResolver;
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
@@ -73,6 +75,7 @@ public class RdsDataService implements Resettable {
private final ConcurrentMap<String, TransactionContext> transactions = new ConcurrentHashMap<>();
private final ScheduledExecutorService transactionCleanupExecutor;
private final RdsBackendGate backendGate;
private final RdsBackendEndpointResolver backendEndpointResolver;
private final boolean databaseResumingExceptionEnabled;
@Inject
@@ -81,19 +84,11 @@ public class RdsDataService implements Resettable {
ObjectMapper objectMapper,
RdsDataConnectionFactory connectionFactory,
EmulatorConfig config,
RdsBackendGate backendGate) {
RdsBackendGate backendGate,
RdsBackendEndpointResolver backendEndpointResolver) {
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory,
Duration.ofSeconds(config.services().rdsData().transactionTtlSeconds()), backendGate,
config.services().rdsData().databaseResumingExceptionEnabled());
}
RdsDataService(RdsDataResourceResolver resourceResolver,
SecretsManagerService secretsManagerService,
ObjectMapper objectMapper,
RdsDataConnectionFactory connectionFactory,
Duration transactionTtl) {
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory, transactionTtl,
RdsBackendGate.OPEN);
backendEndpointResolver, config.services().rdsData().databaseResumingExceptionEnabled());
}
RdsDataService(RdsDataResourceResolver resourceResolver,
@@ -101,8 +96,9 @@ public class RdsDataService implements Resettable {
ObjectMapper objectMapper,
RdsDataConnectionFactory connectionFactory,
Duration transactionTtl,
RdsBackendGate backendGate) {
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory, transactionTtl, backendGate, false);
RdsBackendEndpointResolver backendEndpointResolver) {
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory, transactionTtl,
RdsBackendGate.OPEN, backendEndpointResolver);
}
RdsDataService(RdsDataResourceResolver resourceResolver,
@@ -111,6 +107,18 @@ public class RdsDataService implements Resettable {
RdsDataConnectionFactory connectionFactory,
Duration transactionTtl,
RdsBackendGate backendGate,
RdsBackendEndpointResolver backendEndpointResolver) {
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory, transactionTtl,
backendGate, backendEndpointResolver, false);
}
RdsDataService(RdsDataResourceResolver resourceResolver,
SecretsManagerService secretsManagerService,
ObjectMapper objectMapper,
RdsDataConnectionFactory connectionFactory,
Duration transactionTtl,
RdsBackendGate backendGate,
RdsBackendEndpointResolver backendEndpointResolver,
boolean databaseResumingExceptionEnabled) {
this.resourceResolver = resourceResolver;
this.secretsManagerService = secretsManagerService;
@@ -118,6 +126,7 @@ public class RdsDataService implements Resettable {
this.connectionFactory = connectionFactory;
this.transactionTtl = transactionTtl;
this.backendGate = backendGate;
this.backendEndpointResolver = backendEndpointResolver;
this.databaseResumingExceptionEnabled = databaseResumingExceptionEnabled;
this.transactionCleanupExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r, "rds-data-transaction-cleanup");
@@ -205,7 +214,9 @@ public class RdsDataService implements Resettable {
boolean leaseHandedOver = false;
Connection connection = null;
try {
connection = connectionFactory.open(target, credentials.username(), credentials.password(), database);
EndpointInfo endpoint = resolveBackendEndpoint(target);
connection = connectionFactory.open(
target, endpoint, credentials.username(), credentials.password(), database);
connection.setAutoCommit(false);
String transactionId = UUID.randomUUID().toString();
transactions.put(transactionId, new TransactionContext(
@@ -305,9 +316,22 @@ public class RdsDataService implements Resettable {
resourceResolver.resolve(resourceArn, region);
DatabaseSecretCredentials credentials = credentials(request, target, region);
String database = databaseName(request, target);
try (RdsBackendGate.Lease _ = enterBackend(target);
Connection connection = connectionFactory.open(target, credentials.username(), credentials.password(), database)) {
return work.execute(connection, target.engine());
try (RdsBackendGate.Lease _ = enterBackend(target)) {
EndpointInfo endpoint = resolveBackendEndpoint(target);
try (Connection connection = connectionFactory.open(
target, endpoint, credentials.username(), credentials.password(), database)) {
return work.execute(connection, target.engine());
}
}
}
private EndpointInfo resolveBackendEndpoint(RdsDataResourceResolver.DatabaseTarget target) {
try {
return backendEndpointResolver.resolveBackendEndpoint(target.runtimeId(), target.engine());
} catch (RuntimeException e) {
LOG.warnv(e, "Could not resolve backend endpoint for RDS runtime {0}", target.runtimeId());
throw new AwsException("InternalServerErrorException",
"Could not resolve backend endpoint for RDS runtime " + target.runtimeId(), 500);
}
}
@@ -317,7 +341,7 @@ public class RdsDataService implements Resettable {
*/
private RdsBackendGate.Lease enterBackend(RdsDataResourceResolver.DatabaseTarget target) {
try {
return backendGate.enter(target.host(), target.port(), !databaseResumingExceptionEnabled);
return backendGate.enterRuntime(target.runtimeId(), !databaseResumingExceptionEnabled);
} catch (RdsBackendGate.ResumingException e) {
throw new AwsException("DatabaseResumingException",
"The Aurora Serverless v2 DB instance is resuming. Wait a few seconds and try again.", 400);