fix(docdb): scope cluster and instance identifiers per region (#2440)

* fix(docdb): scope cluster and instance identifiers per region

AWS scopes these identifiers per region: the same name creates in two regions,
each resource with its own ARN and its own tags. Floci keyed its records by the
identifier alone, so the second region's create was refused as already existing,
and a name spent in one region was spent everywhere.

The key is now region::identifier, the shape RdsService already uses for the
same identifiers. Records written under a bare identifier belong to the
configured default region — that is the region they were created under, the
assumption the ARN backfill already makes — and are moved under their regional
key on first read, under the record's monitor so the move cannot undo a delete.

Every read, write, listing and lock is keyed that way, including the cluster
members list an instance create and delete maintain, and an instance can only
attach to a cluster in its own region. Ownership of an identifier is a lookup
rather than a scan filtered by the region read back off each record's ARN.

Closes #2416.

* fix(docdb): make a field filled in on read safe against a concurrent delete

Filling in a missing ARN on read is still a write, and it was not serialised
against anything: a reader that started before a delete put the record back
after it, leaving a cluster no describe created and no delete can remove.

It takes the monitor every other writer of that record takes now — naming one
after the store key rather than the record gave two monitors, and two monitors
are no mutual exclusion at all — and writes only if the record under the key is
still the one it filled in, so a delete, or a delete and a re-create under the
same name, is not written over.

That second check is also what makes retiring a monitor with its record safe. I
had removed the retirement suggested on #2408, believing it was the cause; a
direct test showed it passes cleanly and the fault was the mismatched monitor,
so it stays.

* fix(docdb): take one monitor per record, and list across a move exactly once

Two things review found in the re-key.

deleteDbInstance took the cluster's monitor by its bare identifier while every
other writer of that record takes it by the regional key. Two names are two
monitors, so removing the last instance could write the cluster back — without
its member, but back — after the cluster had been deleted, leaving metadata no
delete could remove and a name that could not be recreated.

And the listing read the regional keys and then the unscoped ones, so a move
running between the two scans lost the record from both: gone from the bare key
by the time that scan ran, not yet under the regional key when that one did.
The unscoped keys are read first, which leaves no interleaving in which neither
scan sees it, and the result is reduced by identifier for the interleaving where
both do.

Both are staged rather than raced. The tests hold one thread at a chosen store
call while the other runs, because a loop hoping for a window a few instructions
wide passes whether or not the fix is there — as the first versions of these two
tests did.

* test(docdb): stage the interleaving the migration's monitor is for

The only cover for that lock was the racing loop, and a loop does not reach a
window a few instructions wide — removing the lock left every test green. The
move is now held at the write it makes under the regional key while a delete
runs, which is the interleaving the monitor exists to prevent: without it the
held write lands after the delete and the record comes back.

The mutation has to compile to prove anything, incidentally. Replacing the
synchronized block with `if (true)` leaves the method without a return and the
build fails, which reads as a passing suite in a filtered log; locking a
throwaway object removes the exclusion and keeps the code valid.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-21 20:58:54 -04:00
1 parent 353d9c842f
commit 3887a6ca65
6 files changed
+948 -62

No files matched your search

@@ -0,0 +1,385 @@
package io.github.hectorvent.floci.services.docdb;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager;
import io.github.hectorvent.floci.services.docdb.model.DocDbCluster;
import io.github.hectorvent.floci.services.docdb.model.DocDbInstance;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
/**
* Moving a record under its regional key must not undo a delete.
*
* <p>The move is a read-modify-write like a tag update: read the record from the unscoped key,
* write it under the regional one. A delete landing between the two would be undone by that write,
* leaving a cluster no describe created and no delete can remove — so the move takes the record's
* monitor, which is the one the delete already holds.
*/
class DocDbLegacyMigrationRaceTest {
private StorageBackend<String, DocDbCluster> clusterStore;
private DocDbService service;
private void serviceOver(PausingStorageBackend<DocDbCluster> pausing) {
clusterStore = new AccountAwareStorageBackend<>(pausing, null, "000000000000");
StorageBackend<String, DocDbInstance> instanceStore =
AccountAwareStorageBackend.inMemory("000000000000");
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
"docdb-clusters.json".equals(inv.getArgument(1)) ? clusterStore : instanceStore);
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.docdb()).thenReturn(docdbConfig);
when(docdbConfig.mock()).thenReturn(true);
service = new DocDbService(config, new RegionResolver("us-east-1", "000000000000"),
Mockito.mock(DocDbContainerManager.class), storageFactory);
}
private void freshService() {
clusterStore = AccountAwareStorageBackend.inMemory("000000000000");
StorageBackend<String, DocDbInstance> instanceStore =
AccountAwareStorageBackend.inMemory("000000000000");
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
"docdb-clusters.json".equals(inv.getArgument(1)) ? clusterStore : instanceStore);
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.docdb()).thenReturn(docdbConfig);
when(docdbConfig.mock()).thenReturn(true);
service = new DocDbService(config, new RegionResolver("us-east-1", "000000000000"),
Mockito.mock(DocDbContainerManager.class), storageFactory);
}
@Test
void readingALegacyRecordWhileItIsDeletedDoesNotBringItBack() throws Exception {
for (int attempt = 0; attempt < 25; attempt++) {
freshService();
String id = "legacy-race-" + attempt;
// A record as an earlier Floci wrote it: under the bare identifier.
DocDbCluster legacy = new DocDbCluster();
legacy.setDbClusterIdentifier(id);
legacy.setStatus("available");
clusterStore.put(id, legacy);
CountDownLatch start = new CountDownLatch(1);
AtomicReference<Throwable> unexpected = new AtomicReference<>();
Thread reader = new Thread(() -> {
await(start);
try {
service.getDbCluster(id);
} catch (AwsException expected) {
if (!"DBClusterNotFoundFault".equals(expected.getErrorCode())) {
unexpected.set(expected);
}
} catch (Throwable t) {
unexpected.set(t);
}
});
Thread deleter = new Thread(() -> {
await(start);
try {
service.deleteDbCluster(id);
} catch (AwsException expected) {
if (!"DBClusterNotFoundFault".equals(expected.getErrorCode())) {
unexpected.set(expected);
}
} catch (Throwable t) {
unexpected.set(t);
}
});
reader.start();
deleter.start();
start.countDown();
reader.join(TimeUnit.SECONDS.toMillis(10));
deleter.join(TimeUnit.SECONDS.toMillis(10));
assertFalse(reader.isAlive() || deleter.isAlive(), "a thread never finished");
assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get());
// The status is reported because it names the writer: a record put back as "deleting"
// came from the delete's own object, one filled in on read from the reader's.
assertFalse(clusterStore.get("us-east-1::" + id).isPresent(),
() -> id + " came back under its regional key with status "
+ clusterStore.get("us-east-1::" + id).map(DocDbCluster::getStatus).orElse("?"));
assertFalse(clusterStore.get(id).isPresent(),
id + " was left behind under the bare key (attempt " + attempt + ")");
}
}
private static void await(CountDownLatch latch) {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
@Test
void listingStagedAcrossTheMoveSeesTheRecordExactlyOnce() throws Exception {
// Staged rather than raced: the listing is held at its first scan while the move runs to
// completion, which is the interleaving that loses or doubles the record.
PausingStorageBackend<DocDbCluster> pausing =
new PausingStorageBackend<>(new io.github.hectorvent.floci.core.storage.InMemoryStorage<>());
serviceOver(pausing);
String id = "listed-across-the-move";
DocDbCluster legacy = new DocDbCluster();
legacy.setDbClusterIdentifier(id);
legacy.setStatus("available");
clusterStore.put(id, legacy);
AtomicReference<java.util.List<String>> listed = new AtomicReference<>();
AtomicReference<Throwable> unexpected = new AtomicReference<>();
// The second scan: the first runs before the move, so holding the second is what puts the
// move between them — the interleaving in which a record can be lost or counted twice.
pausing.pauseOn(PausingStorageBackend.Call.SCAN, null, 1);
Thread lister = new Thread(() -> {
try {
listed.set(service.listDbClusters(null).stream()
.map(DocDbCluster::getDbClusterIdentifier).toList());
} catch (Throwable t) {
unexpected.set(t);
}
});
lister.start();
pausing.awaitReached();
// The move happens entirely inside the listing's first scan.
service.getDbCluster(id);
pausing.release();
lister.join(TimeUnit.SECONDS.toMillis(10));
assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get());
assertEquals(java.util.List.of(id), listed.get(),
"the cluster should be listed exactly once across the move");
}
@Test
void removingTheLastInstanceCannotWriteOverAClusterDelete() throws Exception {
// Staged: the instance delete is held as it writes the cluster back without its member,
// and the cluster delete runs to completion first. Sharing one monitor is what stops the
// held write from landing afterwards.
PausingStorageBackend<DocDbCluster> pausing =
new PausingStorageBackend<>(new io.github.hectorvent.floci.core.storage.InMemoryStorage<>());
serviceOver(pausing);
String clusterId = "co-delete-staged";
String instanceId = "co-delete-staged-instance";
service.createDbCluster(clusterId, "5.0.0", "admin", "secret99password", false);
service.createDbInstance(instanceId, clusterId, "db.r5.large", "5.0.0", false);
AtomicReference<Throwable> unexpected = new AtomicReference<>();
pausing.pauseOn(PausingStorageBackend.Call.PUT, "us-east-1::" + clusterId);
Thread instanceDeleter = new Thread(() -> {
try {
service.deleteDbInstance(instanceId);
} catch (Throwable t) {
unexpected.set(t);
}
});
instanceDeleter.start();
pausing.awaitReached();
// Held mid-write, the instance is already out of the store, so the cluster deletes.
Thread clusterDeleter = new Thread(() -> {
try {
service.deleteDbCluster(clusterId);
} catch (Throwable t) {
unexpected.set(t);
}
});
clusterDeleter.start();
clusterDeleter.join(TimeUnit.SECONDS.toMillis(2));
pausing.release();
instanceDeleter.join(TimeUnit.SECONDS.toMillis(10));
clusterDeleter.join(TimeUnit.SECONDS.toMillis(10));
assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get());
assertFalse(clusterStore.get("us-east-1::" + clusterId).isPresent(),
"the member-list write landed after the cluster was deleted");
}
@Test
void listingWhileALegacyRecordIsMovedSeesItExactlyOnce() throws Exception {
// The listing reads two sets of keys while a migration is moving a record between them.
// Whichever way the two scans straddle the move, the record has to appear once: missing it
// hides a resource that exists, and seeing it twice reports one resource as two.
for (int attempt = 0; attempt < 25; attempt++) {
freshService();
String id = "listed-during-move-" + attempt;
DocDbCluster legacy = new DocDbCluster();
legacy.setDbClusterIdentifier(id);
legacy.setStatus("available");
clusterStore.put(id, legacy);
CountDownLatch start = new CountDownLatch(1);
AtomicReference<Throwable> unexpected = new AtomicReference<>();
AtomicReference<java.util.List<String>> listed = new AtomicReference<>();
Thread mover = new Thread(() -> {
await(start);
try {
service.getDbCluster(id);
} catch (Throwable t) {
unexpected.set(t);
}
});
Thread lister = new Thread(() -> {
await(start);
try {
listed.set(service.listDbClusters(null).stream()
.map(DocDbCluster::getDbClusterIdentifier).toList());
} catch (Throwable t) {
unexpected.set(t);
}
});
mover.start();
lister.start();
start.countDown();
mover.join(TimeUnit.SECONDS.toMillis(10));
lister.join(TimeUnit.SECONDS.toMillis(10));
assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get());
assertEquals(java.util.List.of(id), listed.get(),
"the cluster should be listed exactly once, attempt " + attempt);
}
}
@Test
void deletingTheLastInstanceWhileItsClusterIsDeletedLeavesNothingBehind() throws Exception {
// Both paths write the cluster record — one removes the instance from its member list,
// the other deletes it — so they have to take the same monitor. Naming one of them after
// the bare identifier is a second monitor, and the member update then lands after the
// delete, leaving cluster metadata no delete can remove.
for (int attempt = 0; attempt < 25; attempt++) {
freshService();
String clusterId = "co-delete-" + attempt;
String instanceId = "co-delete-instance-" + attempt;
service.createDbCluster(clusterId, "5.0.0", "admin", "secret99password", false);
service.createDbInstance(instanceId, clusterId, "db.r5.large", "5.0.0", false);
CountDownLatch start = new CountDownLatch(1);
AtomicReference<Throwable> unexpected = new AtomicReference<>();
Thread instanceDeleter = new Thread(() -> {
await(start);
try {
service.deleteDbInstance(instanceId);
} catch (AwsException expected) {
// losing the race is fine; answering wrongly is not
} catch (Throwable t) {
unexpected.set(t);
}
});
Thread clusterDeleter = new Thread(() -> {
await(start);
try {
service.deleteDbCluster(clusterId);
} catch (AwsException expected) {
// the cluster still has a member until the other thread finishes
} catch (Throwable t) {
unexpected.set(t);
}
});
instanceDeleter.start();
clusterDeleter.start();
start.countDown();
instanceDeleter.join(TimeUnit.SECONDS.toMillis(10));
clusterDeleter.join(TimeUnit.SECONDS.toMillis(10));
assertFalse(instanceDeleter.isAlive() || clusterDeleter.isAlive(), "a thread never finished");
assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get());
// Whoever won, the instance is gone and the cluster is either gone or still deletable.
assertFalse(clusterStore.get("us-east-1::" + clusterId)
.map(c -> c.getDbClusterMembers().contains(instanceId)).orElse(false),
"the deleted instance is still a member of " + clusterId);
if (clusterStore.get("us-east-1::" + clusterId).isPresent()) {
service.deleteDbCluster(clusterId);
}
assertFalse(clusterStore.get("us-east-1::" + clusterId).isPresent(),
clusterId + " could not be removed after the race (attempt " + attempt + ")");
}
}
@Test
void aDeleteCannotSlipBetweenTheMovesReadAndItsWrite() throws Exception {
// Staged, because the racing loop above does not reach this one: the move reads the record
// from the unscoped key and writes it under the regional one, and a delete landing between
// those two would be undone by that write. Holding the move at its write and letting a
// delete run is that interleaving exactly.
PausingStorageBackend<DocDbCluster> pausing =
new PausingStorageBackend<>(new io.github.hectorvent.floci.core.storage.InMemoryStorage<>());
serviceOver(pausing);
String id = "moved-while-deleted";
DocDbCluster legacy = new DocDbCluster();
legacy.setDbClusterIdentifier(id);
legacy.setStatus("available");
clusterStore.put(id, legacy);
AtomicReference<Throwable> unexpected = new AtomicReference<>();
pausing.pauseOn(PausingStorageBackend.Call.PUT, "us-east-1::" + id);
Thread mover = new Thread(() -> {
try {
service.getDbCluster(id);
} catch (AwsException expected) {
// losing to the delete is a legitimate outcome
} catch (Throwable t) {
unexpected.set(t);
}
});
mover.start();
pausing.awaitReached();
Thread deleter = new Thread(() -> {
try {
service.deleteDbCluster(id);
} catch (AwsException expected) {
// so is finding it already gone
} catch (Throwable t) {
unexpected.set(t);
}
});
deleter.start();
// Sharing the monitor is what stops the delete finishing here: it should still be waiting.
deleter.join(TimeUnit.SECONDS.toMillis(1));
pausing.release();
mover.join(TimeUnit.SECONDS.toMillis(10));
deleter.join(TimeUnit.SECONDS.toMillis(10));
assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get());
assertFalse(clusterStore.get("us-east-1::" + id).isPresent(),
"the move wrote the record back after it was deleted");
assertFalse(clusterStore.get(id).isPresent(), "the unscoped key was left behind");
}
}
@@ -0,0 +1,222 @@
package io.github.hectorvent.floci.services.docdb;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* One identifier per region, as AWS scopes them.
*
* <p>Checked against a live account: the same name creates in two regions, each with its own ARN,
* and tagging one leaves the other untouched. Floci refused the second create, because its records
* were keyed by identifier alone — so the name a caller used in one region was spent everywhere.
*/
@QuarkusTest
@TestProfile(DocDbRegionScopedIdentifierIntegrationTest.NoContainersProfile.class)
class DocDbRegionScopedIdentifierIntegrationTest {
public static class NoContainersProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.docdb.mock", "true");
}
}
@Inject
DocDbService service;
private static final String ID = "shared-across-regions";
private static io.restassured.specification.RequestSpecification docdb(String region, String action) {
return given().header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260615/" + region + "/docdb/aws4_request, "
+ "SignedHeaders=content-type;host, Signature=test")
.contentType(URLENC)
.formParam("Action", action)
.formParam("Version", "2014-10-31");
}
private static void createCluster(String region, String tagValue) {
docdb(region, "CreateDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("Engine", "docdb")
.formParam("MasterUsername", "docdbadmin")
.formParam("MasterUserPassword", "secret99password")
.formParam("Tags.Tag.1.Key", "where")
.formParam("Tags.Tag.1.Value", tagValue)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("arn:aws:rds:" + region + ":000000000000:cluster:" + ID));
}
@Test
void oneNameCreatesInEveryRegionAndEachCarriesItsOwnState() {
createCluster("us-east-1", "east");
createCluster("eu-west-1", "west");
// Each region describes its own record and not the other's.
for (String region : new String[]{"us-east-1", "eu-west-1"}) {
docdb(region, "DescribeDBClusters")
.formParam("DBClusterIdentifier", ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("arn:aws:rds:" + region + ":000000000000:cluster:" + ID));
}
// Tags belong to the record, not to the name.
docdb("us-east-1", "ListTagsForResource")
.formParam("ResourceName", "arn:aws:rds:us-east-1:000000000000:cluster:" + ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<Value>east</Value>"))
.body(not(containsString("<Value>west</Value>")));
// A third region has neither.
docdb("ap-south-1", "DescribeDBClusters")
.formParam("DBClusterIdentifier", ID)
.when().post("/")
.then().statusCode(404);
// Deleting one leaves the other alone.
docdb("us-east-1", "DeleteDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
docdb("us-east-1", "DescribeDBClusters")
.formParam("DBClusterIdentifier", ID)
.when().post("/").then().statusCode(404);
docdb("eu-west-1", "DescribeDBClusters")
.formParam("DBClusterIdentifier", ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("arn:aws:rds:eu-west-1:000000000000:cluster:" + ID));
// Its tags survived the other region's delete too.
docdb("eu-west-1", "ListTagsForResource")
.formParam("ResourceName", "arn:aws:rds:eu-west-1:000000000000:cluster:" + ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<Value>west</Value>"));
docdb("eu-west-1", "DeleteDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
}
@Test
void instancesAreScopedTheSameWay() {
createCluster("us-east-1", "east");
createCluster("eu-west-1", "west");
String instanceId = "shared-instance";
for (String region : new String[]{"us-east-1", "eu-west-1"}) {
docdb(region, "CreateDBInstance")
.formParam("DBInstanceIdentifier", instanceId)
.formParam("DBClusterIdentifier", ID)
.formParam("Engine", "docdb")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("arn:aws:rds:" + region + ":000000000000:db:" + instanceId));
}
// Each cluster lists only the instance created against it.
for (String region : new String[]{"us-east-1", "eu-west-1"}) {
docdb(region, "DescribeDBInstances")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("arn:aws:rds:" + region + ":000000000000:db:" + instanceId));
docdb(region, "DeleteDBInstance")
.formParam("DBInstanceIdentifier", instanceId)
.when().post("/").then().statusCode(200);
docdb(region, "DeleteDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
}
}
@Test
void aRecordWrittenBeforeRegionsWereInTheKeyBelongsToTheDefaultRegion() {
// Written the way an earlier Floci wrote it: the service call runs outside a request, so
// it lands under the default region — which is where such a record belongs.
String legacyId = "pre-rekey-cluster";
service.createDbCluster(legacyId, "5.0.0", "admin", "secret99password", false);
docdb("us-east-1", "DescribeDBClusters")
.formParam("DBClusterIdentifier", legacyId)
.when().post("/")
.then()
.statusCode(200)
.body(containsString(legacyId));
// And it is not visible from anywhere else, nor does it block that name there.
docdb("eu-west-1", "DescribeDBClusters")
.formParam("DBClusterIdentifier", legacyId)
.when().post("/").then().statusCode(404);
docdb("eu-west-1", "CreateDBCluster")
.formParam("DBClusterIdentifier", legacyId)
.formParam("Engine", "docdb")
.formParam("MasterUsername", "docdbadmin")
.formParam("MasterUserPassword", "secret99password")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("arn:aws:rds:eu-west-1:000000000000:cluster:" + legacyId));
assertEquals("arn:aws:rds:us-east-1:000000000000:cluster:" + legacyId,
service.getDbCluster(legacyId).getDbClusterArn());
assertTrue(service.hasCluster(legacyId, "us-east-1"));
assertTrue(service.hasCluster(legacyId, "eu-west-1"));
docdb("eu-west-1", "DeleteDBCluster")
.formParam("DBClusterIdentifier", legacyId)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
service.deleteDbCluster(legacyId);
}
@Test
void anInstanceCannotAttachToAClusterInAnotherRegion() {
// The reference has to resolve in the region the create is made from — a cluster that
// exists only elsewhere is not there to attach to.
createCluster("eu-west-1", "west");
docdb("us-east-1", "CreateDBInstance")
.formParam("DBInstanceIdentifier", "orphan-instance")
.formParam("DBClusterIdentifier", ID)
.formParam("Engine", "docdb")
.when().post("/")
.then()
.statusCode(404)
.body(containsString("DBClusterNotFoundFault"));
docdb("eu-west-1", "DeleteDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager;
import io.github.hectorvent.floci.services.docdb.model.DocDbCluster;
@@ -13,10 +14,12 @@ import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -183,4 +186,47 @@ class DocDbServiceTest {
() -> docDbService.listTagsForResource("scoped-cluster"));
assertTrue(notAnArn.getMessage().contains("Invalid resource name"));
}
@Test
void aRecordStoredUnderABareIdentifierIsFoundAndMovedUnderItsRegionalKey() {
// The upgrade path: records written before regions were part of the key sit under the
// bare identifier. They belong to the default region — that is the region they were
// created under — and are moved there on the first read, so the bare key is consulted
// once rather than for ever.
StorageBackend<String, DocDbCluster> clusterStore =
AccountAwareStorageBackend.inMemory("000000000000");
StorageBackend<String, DocDbInstance> instanceStore =
AccountAwareStorageBackend.inMemory("000000000000");
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
"docdb-clusters.json".equals(inv.getArgument(1)) ? clusterStore : instanceStore);
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.docdb()).thenReturn(docdbConfig);
when(docdbConfig.mock()).thenReturn(true);
DocDbService service = new DocDbService(config,
new RegionResolver("us-east-1", "000000000000"),
Mockito.mock(DocDbContainerManager.class), storageFactory);
DocDbCluster legacy = new DocDbCluster();
legacy.setDbClusterIdentifier("bare-key-cluster");
legacy.setStatus("available");
clusterStore.put("bare-key-cluster", legacy);
assertEquals("available", service.getDbCluster("bare-key-cluster").getStatus());
assertTrue(clusterStore.get("us-east-1::bare-key-cluster").isPresent(),
"the record should have been moved under its regional key");
assertTrue(clusterStore.get("bare-key-cluster").isEmpty(),
"the bare key should not be left behind");
// It is the default region's, and only that region's.
assertTrue(service.hasCluster("bare-key-cluster", "us-east-1"));
assertFalse(service.hasCluster("bare-key-cluster", "eu-west-1"));
// And it lists there, once rather than twice.
assertEquals(1, service.listDbClusters(null).size());
}
}
@@ -0,0 +1,123 @@
package io.github.hectorvent.floci.services.docdb;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
/**
* A store that can be stopped in the middle of an operation, so a race can be staged rather than
* hoped for.
*
* <p>A concurrency test that loops and waits for an unlucky interleaving proves nothing when the
* window is a few instructions wide: it passes with the fix and without it. Holding one thread at a
* chosen call while another runs to completion makes the interleaving the test claims to cover the
* one it actually runs.
*/
final class PausingStorageBackend<V> implements StorageBackend<String, V> {
/** Which call to hold, and on which key. */
enum Call { PUT, DELETE, SCAN }
private final StorageBackend<String, V> delegate;
private volatile Call pauseOn;
private volatile String pauseKey;
private final java.util.concurrent.atomic.AtomicInteger skip =
new java.util.concurrent.atomic.AtomicInteger();
private final CountDownLatch reached = new CountDownLatch(1);
private final CountDownLatch release = new CountDownLatch(1);
PausingStorageBackend(StorageBackend<String, V> delegate) {
this.delegate = delegate;
}
/** Hold the next matching call until {@link #release()}; {@code key} may be null for SCAN. */
void pauseOn(Call call, String key) {
pauseOn(call, key, 0);
}
/** As above, after letting {@code skipFirst} matching calls through untouched. */
void pauseOn(Call call, String key, int skipFirst) {
this.pauseOn = call;
this.pauseKey = key;
this.skip.set(skipFirst);
}
/** Waits until the paused call has been reached. */
void awaitReached() throws InterruptedException {
if (!reached.await(10, TimeUnit.SECONDS)) {
throw new IllegalStateException("the paused call was never reached");
}
}
void release() {
release.countDown();
}
private void pauseIfMatching(Call call, String key) {
// Keys arrive account-prefixed here, since this sits underneath the account-aware layer.
if (pauseOn != call || (pauseKey != null && (key == null || !key.endsWith(pauseKey)))) {
return;
}
if (skip.getAndDecrement() > 0) {
return;
}
pauseOn = null;
reached.countDown();
try {
if (!release.await(10, TimeUnit.SECONDS)) {
throw new IllegalStateException("the paused call was never released");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
@Override
public void put(String key, V value) {
pauseIfMatching(Call.PUT, key);
delegate.put(key, value);
}
@Override
public Optional<V> get(String key) {
return delegate.get(key);
}
@Override
public void delete(String key) {
pauseIfMatching(Call.DELETE, key);
delegate.delete(key);
}
@Override
public List<V> scan(Predicate<String> keyFilter) {
pauseIfMatching(Call.SCAN, null);
return delegate.scan(keyFilter);
}
@Override
public Set<String> keys() {
return delegate.keys();
}
@Override
public void flush() {
delegate.flush();
}
@Override
public void load() {
delegate.load();
}
@Override
public void clear() {
delegate.clear();
}
}
@@ -187,7 +187,12 @@ class SharedClusterIdentifierIntegrationTest {
assertTrue(rdsService.listTagsForResource(
"arn:aws:rds:us-east-1:000000000000:cluster:" + id, "us-east-1").isEmpty());
docDbService.deleteDbCluster(id);
// Deleted over the endpoint: the record lives under its own region's key, and a direct
// call from the test thread carries no request to take a region from.
queryIn("eu-west-1", "DeleteDBCluster")
.formParam("DBClusterIdentifier", id)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
rdsService.deleteDbCluster(id, "us-east-1");
}