mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(rds-data): opt into retryable database resume errors (#5703)
* feat(rds-data): opt into retryable database resume errors * fix(rds): keep lease release safe after timer shutdown * refactor(rds): share pause cancellation between acquisition modes * docs(rds-data): list resume errors in configuration references
This commit is contained in:
1 parent
ac83817802
commit
fb6adc00d8
14 files changed
+408
-17
No files matched your search
+139
@@ -21,10 +21,12 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
@@ -90,6 +92,139 @@ class AutoPauseControllerTest {
|
||||
assertEquals(State.PAUSED, controller.state(), "idle again after the connection closed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonBlockingAcquisitionStartsOneBackgroundResumeWithoutTakingALease() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ofSeconds(15));
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(2),
|
||||
() -> assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false)));
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
assertEquals(0, controller.leaseCount());
|
||||
assertEquals(0, freezer.unpauses.get(), "Docker resume must not block the Data API request");
|
||||
|
||||
scheduler.advance(Duration.ZERO);
|
||||
assertEquals(State.RESUMING, controller.state());
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
assertEquals(1, freezer.unpauses.get());
|
||||
|
||||
scheduler.advance(Duration.ofSeconds(15));
|
||||
try (RdsBackendGate.Lease lease = controller.acquire(false)) {
|
||||
assertEquals(1, controller.leaseCount());
|
||||
assertFalse(freezer.paused);
|
||||
}
|
||||
assertEquals(0, controller.leaseCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingBeforeTheQueuedResumeThawsTheContainerOnce() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ofSeconds(15));
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
|
||||
controller.close();
|
||||
scheduler.advance(Duration.ofDays(1));
|
||||
|
||||
assertFalse(freezer.paused);
|
||||
assertEquals(1, freezer.unpauses.get());
|
||||
assertSame(RdsBackendGate.Lease.NONE, controller.acquire(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonBlockingArrivalDuringPauseCancelsItWithoutAcquiringALease() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
freezer.blockPause();
|
||||
Thread pausing = Thread.ofVirtual().start(() -> scheduler.advance(IDLE));
|
||||
freezer.awaitPauseEntered();
|
||||
try {
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
assertEquals(0, controller.leaseCount());
|
||||
} finally {
|
||||
freezer.releasePause();
|
||||
pausing.join(5000);
|
||||
}
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertFalse(freezer.paused);
|
||||
}
|
||||
|
||||
@Test
|
||||
void leaseReleaseStillSucceedsAfterTheTimerStops() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
RdsBackendGate.Lease lease = controller.acquire();
|
||||
scheduler.reject = true;
|
||||
|
||||
assertDoesNotThrow(lease::close);
|
||||
assertEquals(0, controller.leaseCount());
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pausedReportingIsBestEffortButResumeSchedulingMustSucceed() throws Exception {
|
||||
AutoPauseController controller = controller(Duration.ZERO);
|
||||
controller.configure(300, listener);
|
||||
scheduler.reject = true;
|
||||
|
||||
assertTrue(assertDoesNotThrow(controller::pauseIfIdle));
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
assertThrows(IllegalStateException.class, () -> controller.acquire(false));
|
||||
scheduler.reject = false;
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
scheduler.advance(Duration.ZERO);
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedBackgroundResumeCanBeRetried() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
scheduler.reject = true;
|
||||
assertThrows(IllegalStateException.class, () -> controller.acquire(false));
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
assertEquals(0, controller.leaseCount());
|
||||
|
||||
scheduler.reject = false;
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
scheduler.advance(Duration.ZERO);
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertEquals(1, freezer.unpauses.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedResumeDelayReleasesBlockingWaitersAfterDockerThaws() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ofSeconds(15));
|
||||
freezer.blockUnpause();
|
||||
Acquirer first = new Acquirer(controller, freezer);
|
||||
freezer.awaitUnpauseEntered();
|
||||
Acquirer second = new Acquirer(controller, freezer);
|
||||
second.awaitWaiting();
|
||||
scheduler.reject = true;
|
||||
freezer.releaseUnpause();
|
||||
|
||||
assertThrows(Exception.class, first::lease);
|
||||
scheduler.reject = false;
|
||||
second.lease().close();
|
||||
assertEquals(State.RUNNING, controller.state());
|
||||
assertEquals(0, controller.leaseCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBackgroundResumeCanBeRetriedWithoutLeakingALease() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ZERO);
|
||||
freezer.unpauseFailure = new IllegalStateException("daemon unavailable");
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
scheduler.advance(Duration.ZERO);
|
||||
assertEquals(State.PAUSED, controller.state());
|
||||
assertEquals(0, controller.leaseCount());
|
||||
|
||||
freezer.unpauseFailure = null;
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> controller.acquire(false));
|
||||
scheduler.advance(Duration.ZERO);
|
||||
try (RdsBackendGate.Lease lease = controller.acquire(false)) {
|
||||
assertFalse(freezer.paused);
|
||||
}
|
||||
assertEquals(0, controller.leaseCount());
|
||||
assertEquals(2, freezer.unpauses.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resumeDelayHoldsConnectionsIncludingOnesThatArriveWhileResuming() throws Exception {
|
||||
AutoPauseController controller = pausedController(Duration.ofSeconds(15));
|
||||
@@ -375,9 +510,13 @@ class AutoPauseControllerTest {
|
||||
private Instant now = Instant.parse("2026-01-01T00:00:00Z");
|
||||
private long sequence;
|
||||
private final List<Scheduled> tasks = new ArrayList<>();
|
||||
private volatile boolean reject;
|
||||
|
||||
@Override
|
||||
public synchronized Future<?> schedule(Runnable task, Duration delay) {
|
||||
if (reject) {
|
||||
throw new IllegalStateException("scheduler stopped");
|
||||
}
|
||||
FutureTask<Void> future = new FutureTask<>(task, null);
|
||||
tasks.add(new Scheduled(now.plus(delay), sequence++, future));
|
||||
return future;
|
||||
|
||||
+1
@@ -1234,6 +1234,7 @@ class RdsContainerManagerTest {
|
||||
assertTrue(manager.pauseIfIdle(runtimeId));
|
||||
verify(pause).exec();
|
||||
|
||||
assertThrows(RdsBackendGate.ResumingException.class, () -> manager.enter("db1", 3306, false));
|
||||
manager.enter("db1", 3306).close();
|
||||
verify(unpause).exec();
|
||||
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.services.rds.RdsService;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static io.restassured.http.ContentType.URLENC;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(RdsDataResumingIntegrationTest.ResumingProfile.class)
|
||||
@Tag("docker")
|
||||
class RdsDataResumingIntegrationTest {
|
||||
|
||||
private static final String RDS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261015/us-east-1/rds/aws4_request";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
RdsService rdsService;
|
||||
|
||||
@Inject
|
||||
RdsContainerManager containerManager;
|
||||
|
||||
@Test
|
||||
void pausedAuroraReturnsTypedHttpErrorsAndExecutesTheRetry() {
|
||||
dockerClient.pingCmd().exec();
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
String clusterId = "data-resuming-" + Long.toString(System.nanoTime(), 36);
|
||||
String instanceId = clusterId + "-1";
|
||||
String secretArn = given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "secretsmanager.CreateSecret")
|
||||
.body(Map.of("Name", clusterId, "SecretString", "{\"username\":\"master\",\"password\":\"Master123!\"}"))
|
||||
.post("/").then().statusCode(200).extract().path("ARN");
|
||||
try {
|
||||
rds("CreateDBCluster").formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("Engine", "aurora-postgresql")
|
||||
.formParam("MasterUsername", "master").formParam("MasterUserPassword", "Master123!")
|
||||
.formParam("DatabaseName", "appdb")
|
||||
.formParam("ServerlessV2ScalingConfiguration.MinCapacity", "0")
|
||||
.formParam("ServerlessV2ScalingConfiguration.MaxCapacity", "2")
|
||||
.formParam("ServerlessV2ScalingConfiguration.SecondsUntilAutoPause", "300")
|
||||
.post("/").then().statusCode(200);
|
||||
rds("CreateDBInstance").formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("DBClusterIdentifier", clusterId).formParam("Engine", "aurora-postgresql")
|
||||
.formParam("DBInstanceClass", "db.serverless").post("/").then().statusCode(200);
|
||||
String clusterArn = rdsService.getDbCluster(clusterId).getDbClusterArn();
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> containerManager.pauseIfIdle(clusterArn));
|
||||
Map<String, Object> request = Map.of("resourceArn", clusterArn, "secretArn", secretArn,
|
||||
"database", "appdb", "sql", "select 1", "parameterSets", List.of(List.of()));
|
||||
|
||||
for (String operation : List.of("Execute", "BeginTransaction", "BatchExecute")) {
|
||||
given().contentType("application/json").body(request).post("/" + operation)
|
||||
.then().statusCode(400)
|
||||
.header("X-Amzn-Errortype", "DatabaseResumingException")
|
||||
.body("__type", equalTo("DatabaseResumingException"));
|
||||
}
|
||||
|
||||
await().atMost(Duration.ofSeconds(20)).untilAsserted(() ->
|
||||
given().contentType("application/json").body(request).post("/Execute")
|
||||
.then().statusCode(200).body("records[0][0].longValue", equalTo(1)));
|
||||
given().contentType("application/json").body(request).post("/Execute")
|
||||
.then().statusCode(200).body("records[0][0].longValue", equalTo(1));
|
||||
} finally {
|
||||
rds("DeleteDBInstance").formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("SkipFinalSnapshot", "true").post("/");
|
||||
rds("DeleteDBCluster").formParam("DBClusterIdentifier", clusterId)
|
||||
.formParam("SkipFinalSnapshot", "true").post("/");
|
||||
given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "secretsmanager.DeleteSecret")
|
||||
.body(Map.of("SecretId", secretArn, "ForceDeleteWithoutRecovery", true)).post("/");
|
||||
}
|
||||
}
|
||||
|
||||
private static RequestSpecification rds(String action) {
|
||||
return given().header("Authorization", RDS_AUTH).contentType(URLENC)
|
||||
.formParam("Action", action).formParam("Version", "2014-10-31");
|
||||
}
|
||||
|
||||
public static class ResumingProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.rds-data.database-resuming-exception-enabled", "true",
|
||||
"floci.services.rds.aurora-resume-delay-millis", "5000");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
import org.h2.Driver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.sql.Connection;
|
||||
@@ -1146,11 +1148,70 @@ class RdsDataServiceTest {
|
||||
});
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ExecuteStatement", "BatchExecuteStatement", "BeginTransaction"})
|
||||
void optedInCallsRejectResumingBackendsBeforeOpeningJdbcAndSucceedOnRetry(String operation) throws Exception {
|
||||
TestHarness harness = new TestHarness(true);
|
||||
harness.createEventsTable();
|
||||
harness.gate.resuming = true;
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> call(harness, operation));
|
||||
|
||||
assertEquals("DatabaseResumingException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertEquals(0, harness.connectionsOpened.get());
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
|
||||
harness.gate.resuming = false;
|
||||
call(harness, operation);
|
||||
assertEquals(1, harness.connectionsOpened.get());
|
||||
if ("BatchExecuteStatement".equals(operation)) {
|
||||
assertEquals(1, harness.service.executeStatement(
|
||||
harness.request("select count(*) from data_api_events"), REGION)
|
||||
.path("records").get(0).get(0).path("longValue").asInt());
|
||||
}
|
||||
harness.service.shutdown();
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultConfigurationStillWaitsForResumingBackends() {
|
||||
TestHarness harness = new TestHarness();
|
||||
harness.gate.resuming = true;
|
||||
|
||||
assertEquals(1, harness.service.executeStatement(harness.request("select 1"), REGION)
|
||||
.path("records").get(0).get(0).path("longValue").asInt());
|
||||
assertEquals(0, harness.gate.held.get());
|
||||
harness.service.shutdown();
|
||||
}
|
||||
|
||||
private void call(TestHarness harness, String operation) {
|
||||
switch (operation) {
|
||||
case "ExecuteStatement" -> harness.service.executeStatement(harness.request("select 1"), REGION);
|
||||
case "BatchExecuteStatement" -> {
|
||||
ObjectNode request = harness.request("insert into data_api_events(name) values ('retry')");
|
||||
request.set("parameterSets", objectMapper.createArrayNode().add(objectMapper.createArrayNode()));
|
||||
harness.service.batchExecuteStatement(request, REGION);
|
||||
}
|
||||
case "BeginTransaction" -> harness.service.beginTransaction(harness.beginRequest(), REGION);
|
||||
default -> throw new AssertionError(operation);
|
||||
}
|
||||
}
|
||||
|
||||
/** Counts the backends the Data API enters and the holds still open on them. */
|
||||
private static final class CountingGate implements RdsBackendGate {
|
||||
private final List<String> entered = new CopyOnWriteArrayList<>();
|
||||
private final AtomicInteger held = new AtomicInteger();
|
||||
private volatile IllegalStateException failure;
|
||||
private boolean resuming;
|
||||
|
||||
@Override
|
||||
public Lease enter(String host, int port, boolean waitForResume) {
|
||||
if (!waitForResume && resuming) {
|
||||
throw new ResumingException();
|
||||
}
|
||||
return enter(host, port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Lease enter(String host, int port) {
|
||||
@@ -1173,12 +1234,17 @@ class RdsDataServiceTest {
|
||||
private final RdsDataResourceResolver resolver;
|
||||
private final RdsDataResourceResolver.DatabaseTarget target;
|
||||
private final CountingGate gate = new CountingGate();
|
||||
private final AtomicInteger connectionsOpened = new AtomicInteger();
|
||||
private final RdsDataService service;
|
||||
|
||||
private TestHarness() {
|
||||
this(DatabaseEngine.MYSQL, Duration.ofSeconds(60));
|
||||
}
|
||||
|
||||
private TestHarness(boolean resumingExceptionEnabled) {
|
||||
this(defaultSecrets(), DatabaseEngine.POSTGRES, Duration.ofSeconds(60), resumingExceptionEnabled);
|
||||
}
|
||||
|
||||
private TestHarness(SecretsManagerService secrets) {
|
||||
this(secrets, DatabaseEngine.MYSQL, Duration.ofSeconds(60));
|
||||
}
|
||||
@@ -1196,6 +1262,11 @@ class RdsDataServiceTest {
|
||||
}
|
||||
|
||||
private TestHarness(SecretsManagerService secrets, DatabaseEngine engine, Duration transactionTtl) {
|
||||
this(secrets, engine, transactionTtl, false);
|
||||
}
|
||||
|
||||
private TestHarness(SecretsManagerService secrets, DatabaseEngine engine, Duration transactionTtl,
|
||||
boolean resumingExceptionEnabled) {
|
||||
jdbcUrl = "jdbc:h2:mem:rdsdata_" + UUID.randomUUID() + ";MODE=" + h2Mode(engine)
|
||||
+ ";DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1";
|
||||
resolver = mock(RdsDataResourceResolver.class);
|
||||
@@ -1211,10 +1282,12 @@ class RdsDataServiceTest {
|
||||
String username,
|
||||
String password,
|
||||
String database) throws SQLException {
|
||||
connectionsOpened.incrementAndGet();
|
||||
return getConnection();
|
||||
}
|
||||
};
|
||||
service = new RdsDataService(resolver, secrets, objectMapper, connectionFactory, transactionTtl, gate);
|
||||
service = new RdsDataService(resolver, secrets, objectMapper, connectionFactory,
|
||||
transactionTtl, gate, resumingExceptionEnabled);
|
||||
}
|
||||
|
||||
private Connection getConnection() throws SQLException {
|
||||
|
||||
Reference in new issue
Block a user