feat(s3): support bucket metrics configurations (#2382)

* feat(s3): support bucket metrics configurations

PutBucketMetricsConfiguration was not routed, so a metrics call fell through to
the unqualified CreateBucket and came back as BucketAlreadyOwnedByYou, which
tells the caller nothing about what happened. The DELETE was worse: it fell
through to DeleteBucket and silently removed the whole bucket while reporting
success, so delete-bucket-metrics-configuration destroyed the bucket it was
called on.

Adds the four actions, stored per bucket and keyed by id:

- PutBucketMetricsConfiguration, GetBucketMetricsConfiguration,
  ListBucketMetricsConfigurations, DeleteBucketMetricsConfiguration
- the body is parsed and re-serialized rather than echoed back, so responses are
  built by floci and a filter survives the round trip in AWS's shape: repeated
  Tag elements inside And, with no wrapping element
- an id in the body that disagrees with the query string is MalformedXML, and an
  unknown id is NoSuchConfiguration on both get and delete, neither of which AWS
  treats as a no-op
- put and delete take the bucket monitor the other bucket-scoped mutations use,
  so concurrent puts of different ids cannot drop one another

Behaviour taken from a live AWS account: the status codes (204 on put and
delete, 404 for an unknown id), both error codes, and the exact XML of the
single-configuration and list responses.

floci records the configurations and returns them; no metrics are produced from
them, and the listing is unpaged, so a continuation token is neither issued nor
honoured.

* fix(s3): validate metrics filters, use the shared XML utilities, guard the delete

Three problems in the previous commit.

The filter was normalized rather than validated, so bodies AWS rejects were
accepted: a filter naming more than one predicate or none, an And of fewer than
two conjuncts, an unknown predicate, and a tag missing its key or value.
Verified against a live account that each is MalformedXML, and the parser now
answers the same.

Parsing and response building went around XmlParser and XmlBuilder, which
AGENTS.md requires, and the S3 namespace was declared again rather than taken
from AwsNamespaces. The bespoke DocumentBuilderFactory carried its own security
configuration, where XmlParser disables DTDs and external entities for everyone
in one place. The controller branches now delegate to handler methods like their
siblings instead of inlining the work.

A metrics mutation resolved the bucket record before writing it back, while
DeleteBucket took no monitor, so a delete landing in between was undone by the
write and the bucket returned. DeleteBucket now takes the same bucket monitor as
the bucket-scoped mutations, and those re-read the record under it, so a
mutation that lost the race reports NoSuchBucket rather than restoring the
bucket. Its test forces that interleaving rather than racing for it.

* fix(s3): reject malformed metrics bodies and stale writes over a recreated bucket

Re-reading the record for presence was not enough. A bucket deleted and then
recreated under the same name leaves a different record in the store, so a
mutation that had resolved the old one passed the presence check and wrote it
back, replacing the new bucket with the old one's state. The check now compares
the record itself, and a mutation holding a superseded one reports NoSuchBucket.

The parser also accepted bodies whose elements were duplicated or misplaced: a
second Id or Filter, or a stray element under the root, was normalized away
rather than refused, so what was stored was not what was sent. The root now has
to be exactly one Id and at most one Filter, in either order.

The concurrency tests wait on thread state rather than sleeping, so they observe
the interleaving instead of hoping for it: instant on a fast machine and not
flaky on a slow one. DeleteBucket taking the bucket monitor is asserted directly,
since the window it closes — a delete between a mutation's re-read and its write
— is too narrow to force from a test.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-18 18:46:35 -04:00
1 parent f952fffe77
commit 8d33c65129
9 files changed
+937 -2

No files matched your search

@@ -0,0 +1,232 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class S3MetricsConfigurationIntegrationTest {
private static final String BUCKET = "metrics-int-test";
@Test
@Order(1)
void createBucket() {
given()
.when()
.put("/" + BUCKET)
.then()
.statusCode(200);
}
/**
* Regression test for the bucket-creating bug where {@code PUT /{bucket}?metrics} was not
* handled and fell through to the unqualified {@code CreateBucket}, which answered a metrics
* call with BucketAlreadyOwnedByYou. Real S3 stores the configuration and returns 204.
*/
@Test
@Order(2)
void putMetricsConfigurationIsNotTreatedAsCreateBucket() {
given()
.body("""
<MetricsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Id>EntireBucket</Id>
</MetricsConfiguration>
""")
.when()
.put("/" + BUCKET + "?metrics&id=EntireBucket")
.then()
.statusCode(204)
.body(not(containsString("BucketAlreadyOwnedByYou")));
}
@Test
@Order(3)
void getMetricsConfigurationReturnsWhatWasStored() {
given()
.when()
.get("/" + BUCKET + "?metrics&id=EntireBucket")
.then()
.statusCode(200)
.body(containsString("<MetricsConfiguration"))
.body(containsString("<Id>EntireBucket</Id>"));
}
@Test
@Order(4)
void putFilteredConfigurationKeepsTheFilter() {
given()
.body("""
<MetricsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Id>Filtered</Id>
<Filter>
<And>
<Prefix>logs/</Prefix>
<Tag><Key>env</Key><Value>prod</Value></Tag>
<Tag><Key>team</Key><Value>core</Value></Tag>
</And>
</Filter>
</MetricsConfiguration>
""")
.when()
.put("/" + BUCKET + "?metrics&id=Filtered")
.then()
.statusCode(204);
// AWS repeats <Tag> inside <And> with no wrapping element.
given()
.when()
.get("/" + BUCKET + "?metrics&id=Filtered")
.then()
.statusCode(200)
.body(containsString("<And><Prefix>logs/</Prefix>"
+ "<Tag><Key>env</Key><Value>prod</Value></Tag>"
+ "<Tag><Key>team</Key><Value>core</Value></Tag></And>"));
}
@Test
@Order(5)
void listWithoutAnIdReturnsEveryConfiguration() {
given()
.when()
.get("/" + BUCKET + "?metrics")
.then()
.statusCode(200)
.body(containsString("<ListMetricsConfigurationsResult"))
.body(containsString("<Id>EntireBucket</Id>"))
.body(containsString("<Id>Filtered</Id>"))
.body(containsString("<IsTruncated>false</IsTruncated>"));
}
@Test
@Order(6)
void idInTheBodyMustMatchTheIdInTheQuery() {
given()
.body("""
<MetricsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Id>Different</Id>
</MetricsConfiguration>
""")
.when()
.put("/" + BUCKET + "?metrics&id=Mismatch")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
}
@Test
@Order(7)
void unknownIdIsNotFound() {
given()
.when()
.get("/" + BUCKET + "?metrics&id=absent")
.then()
.statusCode(404)
.body(containsString("NoSuchConfiguration"));
// AWS does not treat deleting an absent configuration as a no-op.
given()
.when()
.delete("/" + BUCKET + "?metrics&id=absent")
.then()
.statusCode(404)
.body(containsString("NoSuchConfiguration"));
}
/**
* Regression test for the bucket-destroying bug: {@code DELETE /{bucket}?metrics} fell through
* to the unqualified {@code DeleteBucket} and silently removed the whole bucket, reporting
* success.
*/
@Test
@Order(8)
void deleteMetricsConfigurationDoesNotDeleteBucket() {
given()
.when()
.delete("/" + BUCKET + "?metrics&id=EntireBucket")
.then()
.statusCode(204);
// The bucket, and every other configuration on it, must survive.
given()
.when()
.get("/" + BUCKET + "?metrics&id=Filtered")
.then()
.statusCode(200);
given()
.when()
.get("/" + BUCKET + "?metrics&id=EntireBucket")
.then()
.statusCode(404);
}
@Test
@Order(9)
void aRequestWithoutAnIdIsRefusedRatherThanGuessedAt() {
given()
.body("""
<MetricsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Id>EntireBucket</Id>
</MetricsConfiguration>
""")
.when()
.put("/" + BUCKET + "?metrics")
.then()
.statusCode(400)
.body(containsString("InvalidArgument"));
given()
.when()
.delete("/" + BUCKET + "?metrics")
.then()
.statusCode(400)
.body(containsString("InvalidArgument"));
}
@Test
@Order(10)
void unqualifiedDeleteStillRemovesBucket() {
given()
.when()
.delete("/" + BUCKET)
.then()
.statusCode(204);
given()
.when()
.get("/" + BUCKET + "?metrics")
.then()
.statusCode(404)
.body(containsString("NoSuchBucket"));
}
@Test
@Order(11)
void aRecreatedBucketDoesNotInheritTheOldConfigurations() {
given()
.when()
.put("/" + BUCKET)
.then()
.statusCode(200);
given()
.when()
.get("/" + BUCKET + "?metrics&id=Filtered")
.then()
.statusCode(404)
.body(containsString("NoSuchConfiguration"));
given()
.when()
.delete("/" + BUCKET)
.then()
.statusCode(204);
}
}
@@ -0,0 +1,153 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class S3MetricsConfigurationTest {
private static final String NS = "http://s3.amazonaws.com/doc/2006-03-01/";
private static String body(String inner) {
return "<MetricsConfiguration xmlns=\"" + NS + "\">" + inner + "</MetricsConfiguration>";
}
@Test
void parsesAnIdWithoutAFilter() {
S3MetricsConfiguration parsed = S3MetricsConfiguration.parse(body("<Id>EntireBucket</Id>"));
assertEquals("EntireBucket", parsed.id());
assertEquals("<Id>EntireBucket</Id>", parsed.innerXml());
}
@Test
void parsesEachSingleFilterPredicate() {
assertEquals("<Id>a</Id><Filter><Prefix>logs/</Prefix></Filter>",
S3MetricsConfiguration.parse(body("<Id>a</Id><Filter><Prefix>logs/</Prefix></Filter>")).innerXml());
assertEquals("<Id>a</Id><Filter><Tag><Key>env</Key><Value>prod</Value></Tag></Filter>",
S3MetricsConfiguration.parse(body(
"<Id>a</Id><Filter><Tag><Key>env</Key><Value>prod</Value></Tag></Filter>")).innerXml());
String arn = "arn:aws:s3:eu-central-1:123456789012:accesspoint/ap";
assertEquals("<Id>a</Id><Filter><AccessPointArn>" + arn + "</AccessPointArn></Filter>",
S3MetricsConfiguration.parse(body(
"<Id>a</Id><Filter><AccessPointArn>" + arn + "</AccessPointArn></Filter>")).innerXml());
}
@Test
void parsesAnAndConjunctionKeepingEveryTag() {
// MetricsAndOperator.Tags is a flattened list named Tag, so the tags repeat with no
// wrapping element and all of them have to survive the round trip.
String parsed = S3MetricsConfiguration.parse(body("""
<Id>a</Id>
<Filter>
<And>
<Prefix>logs/</Prefix>
<Tag><Key>env</Key><Value>prod</Value></Tag>
<Tag><Key>team</Key><Value>core</Value></Tag>
</And>
</Filter>
""")).innerXml();
assertEquals("<Id>a</Id><Filter><And><Prefix>logs/</Prefix>"
+ "<Tag><Key>env</Key><Value>prod</Value></Tag>"
+ "<Tag><Key>team</Key><Value>core</Value></Tag></And></Filter>", parsed);
}
@Test
void escapesValuesOnTheWayBackOut() {
String parsed = S3MetricsConfiguration.parse(
body("<Id>a&amp;b</Id><Filter><Prefix>x&lt;y</Prefix></Filter>")).innerXml();
assertEquals("<Id>a&amp;b</Id><Filter><Prefix>x&lt;y</Prefix></Filter>", parsed);
}
@Test
void rejectsBodiesThatDoNotMatchTheSchema() {
// Missing id, wrong root element, empty and non-XML bodies are all MalformedXML on AWS.
for (String invalid : new String[]{
body(""),
body("<Id> </Id>"),
"<SomethingElse><Id>a</Id></SomethingElse>",
"not xml at all",
""}) {
AwsException e = assertThrows(AwsException.class, () -> S3MetricsConfiguration.parse(invalid),
() -> "expected rejection of: " + invalid);
assertEquals("MalformedXML", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
}
}
@Test
void rejectsFiltersThatAreNotExactlyOnePredicate() {
// Verified against AWS: each of these is MalformedXML rather than something to normalize.
String bothPrefixAndTag = "<Id>a</Id><Filter><Prefix>logs/</Prefix>"
+ "<Tag><Key>env</Key><Value>prod</Value></Tag></Filter>";
String emptyFilter = "<Id>a</Id><Filter></Filter>";
String andWithOnePredicate = "<Id>a</Id><Filter><And><Prefix>logs/</Prefix></And></Filter>";
String andWithOneTag = "<Id>a</Id><Filter><And>"
+ "<Tag><Key>env</Key><Value>prod</Value></Tag></And></Filter>";
String tagWithoutAKey = "<Id>a</Id><Filter><Tag><Value>prod</Value></Tag></Filter>";
// botocore marks both Key and Value required on a Tag.
String tagWithoutAValue = "<Id>a</Id><Filter><Tag><Key>env</Key></Tag></Filter>";
String unknownPredicate = "<Id>a</Id><Filter><Something>x</Something></Filter>";
String andWithAnUnknownConjunct = "<Id>a</Id><Filter><And><Prefix>logs/</Prefix>"
+ "<Something>x</Something></And></Filter>";
for (String invalid : new String[]{
bothPrefixAndTag, emptyFilter, andWithOnePredicate, andWithOneTag, tagWithoutAKey,
tagWithoutAValue, unknownPredicate, andWithAnUnknownConjunct}) {
AwsException e = assertThrows(AwsException.class, () -> S3MetricsConfiguration.parse(body(invalid)),
() -> "expected rejection of: " + invalid);
assertEquals("MalformedXML", e.getErrorCode());
}
}
@Test
void rejectsDuplicateOrMisplacedElements() {
// Normalizing these away would store a configuration that is not the one that was sent.
String twoIds = "<Id>a</Id><Id>b</Id>";
String twoFilters = "<Id>a</Id><Filter><Prefix>x</Prefix></Filter>"
+ "<Filter><Prefix>y</Prefix></Filter>";
String strayElement = "<Id>a</Id><Prefix>logs/</Prefix>";
String noId = "<Filter><Prefix>logs/</Prefix></Filter>";
String idOnlyInsideFilter = "<Filter><Id>a</Id></Filter>";
for (String invalid : new String[]{twoIds, twoFilters, strayElement, noId, idOnlyInsideFilter}) {
AwsException e = assertThrows(AwsException.class, () -> S3MetricsConfiguration.parse(body(invalid)),
() -> "expected rejection of: " + invalid);
assertEquals("MalformedXML", e.getErrorCode());
}
}
@Test
void acceptsAFilterBeforeItsId() {
// Element order is not something to be strict about; the set of elements is.
assertEquals("<Id>a</Id><Filter><Prefix>logs/</Prefix></Filter>",
S3MetricsConfiguration.parse(
body("<Filter><Prefix>logs/</Prefix></Filter><Id>a</Id>")).innerXml());
}
@Test
void acceptsAnAndOfExactlyTwoPredicates() {
// The boundary the rejection is drawn at: two conjuncts are legal, one is not.
assertEquals("<Id>a</Id><Filter><And><Prefix>logs/</Prefix>"
+ "<Tag><Key>env</Key><Value>prod</Value></Tag></And></Filter>",
S3MetricsConfiguration.parse(body("<Id>a</Id><Filter><And><Prefix>logs/</Prefix>"
+ "<Tag><Key>env</Key><Value>prod</Value></Tag></And></Filter>")).innerXml());
}
@Test
void refusesToResolveExternalEntities() {
// The parser must not read local files on behalf of a request body.
String xxe = "<?xml version=\"1.0\"?>"
+ "<!DOCTYPE foo [<!ENTITY xxe SYSTEM \"file:///etc/passwd\">]>"
+ "<MetricsConfiguration><Id>&xxe;</Id></MetricsConfiguration>";
AwsException e = assertThrows(AwsException.class, () -> S3MetricsConfiguration.parse(xxe));
assertEquals("MalformedXML", e.getErrorCode());
}
}
@@ -753,4 +753,227 @@ class S3ServiceTest {
assertInstanceOf(S3Service.WebsiteResolution.ErrorDocument.class,
s3Service.resolveWebsiteError("site", UNSIGNED, 500)).status());
}
@Test
void metricsConfigurationsOnABucketWithoutAnyBehaveAsEmpty() {
// A bucket persisted before this field existed deserializes with a null map, which is the
// same shape a freshly created bucket has, so neither may fault.
s3Service.createBucket("no-metrics", "us-east-1");
assertTrue(s3Service.listBucketMetricsConfigurations("no-metrics")
.contains("<IsTruncated>false</IsTruncated>"));
assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
() -> s3Service.getBucketMetricsConfiguration("no-metrics", "any")).getErrorCode());
assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
() -> s3Service.deleteBucketMetricsConfiguration("no-metrics", "any")).getErrorCode());
// And the first put still lands on it.
s3Service.putBucketMetricsConfiguration("no-metrics", "first", "<Id>first</Id>");
assertTrue(s3Service.getBucketMetricsConfiguration("no-metrics", "first")
.contains("<Id>first</Id>"));
}
@Test
void metricsConfigurationsDoNotOutliveTheirBucket() {
s3Service.createBucket("recycled", "us-east-1");
s3Service.putBucketMetricsConfiguration("recycled", "old", "<Id>old</Id>");
s3Service.deleteBucket("recycled");
s3Service.createBucket("recycled", "us-east-1");
assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
() -> s3Service.getBucketMetricsConfiguration("recycled", "old")).getErrorCode());
}
@Test
void metricsConfigurationsSurviveARestart() {
// Through the real storage layer rather than Jackson alone: written, flushed to disk, and
// read back by a second service over the same file, the way a restart does it.
Path bucketsFile = tempDir.resolve("s3-buckets.json");
var beforeRestart = new io.github.hectorvent.floci.core.storage.HybridStorage<String, Bucket>(
bucketsFile, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Bucket>>() {}, 60000);
S3Service before = new S3Service(beforeRestart, new InMemoryStorage<>(), tempDir.resolve("s3a"), false);
before.createBucket("persisted-metrics", "us-east-1");
before.putBucketMetricsConfiguration("persisted-metrics", "EntireBucket", "<Id>EntireBucket</Id>");
beforeRestart.flush();
beforeRestart.shutdown();
var afterRestart = new io.github.hectorvent.floci.core.storage.HybridStorage<String, Bucket>(
bucketsFile, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Bucket>>() {}, 60000);
afterRestart.load();
try {
S3Service after = new S3Service(afterRestart, new InMemoryStorage<>(), tempDir.resolve("s3a"), false);
assertTrue(after.getBucketMetricsConfiguration("persisted-metrics", "EntireBucket")
.contains("<Id>EntireBucket</Id>"));
} finally {
afterRestart.shutdown();
}
}
@Test
void metricsConfigurationsSurviveAJacksonRoundTrip() throws Exception {
// Bucket records are persisted as JSON, so the configurations have to come back after a
// restart, and a record written before the field existed has to still load.
var mapper = new com.fasterxml.jackson.databind.ObjectMapper().findAndRegisterModules();
Bucket bucket = new Bucket("persisted");
bucket.setMetricsConfigurations(new java.util.LinkedHashMap<>(
Map.of("EntireBucket", "<Id>EntireBucket</Id>")));
Bucket reloaded = mapper.readValue(mapper.writeValueAsString(bucket), Bucket.class);
assertEquals("<Id>EntireBucket</Id>", reloaded.getMetricsConfigurations().get("EntireBucket"));
Bucket legacy = mapper.readValue("{\"name\":\"legacy\"}", Bucket.class);
assertNull(legacy.getMetricsConfigurations());
}
/**
* Waits for the thread to reach the bucket monitor. The store is a ConcurrentHashMap, so
* nothing else blocks it: this observes the interleaving rather than sleeping long enough to
* hope for it, which keeps the test both instant and immune to a slow machine.
*/
private static void awaitBlockedOnMonitor(Thread thread) throws InterruptedException {
long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10);
while (thread.getState() != Thread.State.BLOCKED) {
if (System.nanoTime() > deadline) {
fail("thread never reached the bucket monitor");
}
Thread.onSpinWait();
}
}
@Test
void deleteBucketTakesTheBucketMonitor() throws Exception {
// Re-reading the record narrows the window but cannot close it: a delete landing between a
// mutation's re-read and its write would still be undone. That interleaving is too narrow
// to force from a test, so what is asserted here is the property that closes it — the
// delete waits for whoever holds the record's monitor.
var buckets = new InMemoryStorage<String, Bucket>();
S3Service service = new S3Service(buckets, new InMemoryStorage<>(), tempDir.resolve("s3-monitor"), false);
service.createBucket("monitor-bucket", "us-east-1");
Bucket record = buckets.get("monitor-bucket").orElseThrow();
Thread delete = new Thread(() -> service.deleteBucket("monitor-bucket"));
synchronized (record) {
delete.start();
long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10);
while (delete.getState() != Thread.State.BLOCKED) {
assertTrue(buckets.get("monitor-bucket").isPresent(),
"DeleteBucket removed the record without waiting for the bucket monitor");
if (System.nanoTime() > deadline) {
fail("DeleteBucket never reached the bucket monitor");
}
Thread.onSpinWait();
}
}
delete.join(30_000);
assertTrue(buckets.get("monitor-bucket").isEmpty());
}
@Test
void aMetricsPutRacingABucketDeleteCannotRestoreTheBucket() throws Exception {
// A put resolves the bucket record before it writes it back, so a delete landing in between
// would be undone by the write. The interleaving is forced rather than raced for: the test
// holds the bucket monitor, lets the put resolve the record and block on it, deletes the
// bucket from the same thread, and only then releases.
var buckets = new InMemoryStorage<String, Bucket>();
S3Service service = new S3Service(buckets, new InMemoryStorage<>(), tempDir.resolve("s3-race"), false);
service.createBucket("race-bucket", "us-east-1");
Bucket record = buckets.get("race-bucket").orElseThrow();
var putStarted = new java.util.concurrent.CountDownLatch(1);
var thrownByPut = new java.util.concurrent.atomic.AtomicReference<Exception>();
Thread put = new Thread(() -> {
putStarted.countDown();
try {
service.putBucketMetricsConfiguration("race-bucket", "id", "<Id>id</Id>");
} catch (Exception e) {
thrownByPut.set(e);
}
});
synchronized (record) {
put.start();
putStarted.await();
awaitBlockedOnMonitor(put);
service.deleteBucket("race-bucket");
}
put.join(30_000);
assertTrue(buckets.get("race-bucket").isEmpty(),
"the deleted bucket was restored by the concurrent metrics put");
assertEquals("NoSuchBucket",
assertInstanceOf(AwsException.class, thrownByPut.get()).getErrorCode());
}
@Test
void aMetricsPutCannotOverwriteABucketRecreatedWhileItWaited() throws Exception {
// Presence is not enough: deleted and recreated under the same name, the store holds a
// different record, and writing the resolved one back would replace the new bucket with
// the old one's state.
var buckets = new InMemoryStorage<String, Bucket>();
S3Service service = new S3Service(buckets, new InMemoryStorage<>(), tempDir.resolve("s3-recreate"), false);
service.createBucket("recreated-bucket", "us-east-1");
Bucket original = buckets.get("recreated-bucket").orElseThrow();
var putStarted = new java.util.concurrent.CountDownLatch(1);
var thrownByPut = new java.util.concurrent.atomic.AtomicReference<Exception>();
Thread put = new Thread(() -> {
putStarted.countDown();
try {
service.putBucketMetricsConfiguration("recreated-bucket", "stale", "<Id>stale</Id>");
} catch (Exception e) {
thrownByPut.set(e);
}
});
synchronized (original) {
put.start();
putStarted.await();
awaitBlockedOnMonitor(put);
service.deleteBucket("recreated-bucket");
service.createBucket("recreated-bucket", "us-east-1");
}
put.join(30_000);
assertEquals("NoSuchBucket",
assertInstanceOf(AwsException.class, thrownByPut.get()).getErrorCode());
assertNotSame(original, buckets.get("recreated-bucket").orElseThrow(),
"the recreated bucket was replaced by the record the put had resolved");
assertNull(buckets.get("recreated-bucket").orElseThrow().getMetricsConfigurations(),
"the recreated bucket inherited a configuration written against the old record");
}
@Test
void concurrentMetricsConfigurationPutsAllSurvive() throws Exception {
// Each put reads the configuration map, adds to it and writes it back, so without a shared
// monitor concurrent puts of different ids overwrite each other's work.
s3Service.createBucket("metrics-race", "us-east-1");
int count = 24;
var pool = java.util.concurrent.Executors.newFixedThreadPool(8);
var start = new java.util.concurrent.CountDownLatch(1);
try {
var submitted = new java.util.ArrayList<java.util.concurrent.Future<?>>();
for (int i = 0; i < count; i++) {
String id = "config-" + i;
submitted.add(pool.submit(() -> {
start.await();
s3Service.putBucketMetricsConfiguration("metrics-race", id, "<Id>" + id + "</Id>");
return null;
}));
}
start.countDown();
for (var future : submitted) {
future.get(30, java.util.concurrent.TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
String listed = s3Service.listBucketMetricsConfigurations("metrics-race");
for (int i = 0; i < count; i++) {
assertTrue(listed.contains("<Id>config-" + i + "</Id>"),
"configuration config-" + i + " was lost by a concurrent put");
}
}
}