mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
feat(msk): add configuration revision actions (#2344)
* fix(core): extract shared pagination helper, reject maxResults=0 Closes #2339, #2340. ListResult<T> and its paginate()/encode()/decode() helpers existed as five near-identical private copies (BedrockAgentCoreGatewayService, BedrockAgentCoreIdentityService, BedrockAgentCoreMemoryService, BedrockAgentCoreControlService's three list methods, and MskService), not the two originally scoped in #2340 - the ListResult<T> record was already shared within bedrockagentcorecontrol, which is what earlier scoping missed. Extracts core.common.Pagination + PaginatedResult<T> and migrates every one of them, deleting both now-unused per-service ListResult model classes. Every duplicate collapsed "maxResults omitted" and "maxResults=0" onto the same primitive int, defaulting both to the full page instead of rejecting the explicit zero the way AWS's MaxResults min:1 constraint requires (confirmed against botocore's real kafka and verified live: botocore itself refuses to send MaxResults=0 client-side). Pagination.paginate/parseMaxResults take a boxed Integer so the two cases are distinguishable, and every migrated service now rejects 0 with its own existing error code (ValidationException for the bedrockagentcorecontrol services, BadRequestException for MSK) - the fix lands once, not five times. Also carries over the MskController fix from #2336: an Integer-typed @QueryParam converts before the resource method runs, so a non-numeric maxResults was a bare 404 instead of an AWS-shaped 400. Every migrated REST controller now binds maxResults as a String and calls Pagination.parseMaxResults, closing the same gap in BedrockAgentCoreGatewayController/ControlController/MemoryController that MSK already had fixed. * feat(msk): add configuration revision actions Closes #2338. Adds UpdateConfiguration, ListConfigurationRevisions, and DescribeConfigurationRevision, the three actions #2299 explicitly scoped out ("a separate follow-up issue"). MskConfiguration now stores a full revision history (revisions + serverPropertiesByRevision keyed by revision number) instead of a single latest-revision field - UpdateConfiguration appends rather than overwrites, and DescribeConfigurationRevision is the only action that returns serverProperties (base64), matching AWS's real shapes: Configuration/ DescribeConfigurationResponse/CreateConfigurationResponse never include it, verified against botocore's kafka service model the same way as #2336/#2343 rather than trusting the docs page. ListConfigurationRevisions builds on the shared Pagination.paginate helper from #2343 (cursor = zero-padded revision number) instead of introducing a sixth duplicate of that logic. getLatestRevision() is now derived from the revision list rather than a separately-stored field, so it can never drift out of sync with it. * fix(msk): guard configuration schema upgrade and update-race in UpdateConfiguration Old (pre-revision-history) persisted configurations have latestRevision/ serverProperties keys this class no longer maps, which previously threw and failed the entire msk-configurations.json load; ignore them instead and reject updates against such an entry with a 400 rather than NPE-ing. Also serialize UpdateConfiguration's read-modify-write behind a lock so two concurrent updates for the same ARN can no longer derive the same revision number and silently overwrite each other's serverProperties. * fix(msk): stop leaking mutable revision state through getters MskConfiguration#getRevisions/getServerPropertiesByRevision returned the live internal List/Map, which is why MskService#updateConfiguration was mutating through them directly - and in an order (revision appended, then its properties inserted) that let an unsynchronized reader observe a revision with no server properties yet and NPE on Base64-encoding it. Add MskConfiguration#addRevision to own both writes in the safe order, and have the getters return copies so callers can no longer bypass it. * fix(msk): guard revision reads with the same lock updateConfiguration writes under listConfigurationRevisions/describeConfigurationRevision read revisions and serverPropertiesByRevision - plain, non-thread-safe collections - without holding configurationUpdateLock, so a concurrent updateConfiguration could race the reader's iteration/copy, not just return stale data. * fix(msk): close remaining unsynchronized-read races on configuration revisions Two more gaps in the same family as the last fix: - deleteConfiguration didn't take configurationUpdateLock, so it could race updateConfiguration and get resurrected by the update's trailing put(arn, ...) after the delete already removed the entry. - getLatestRevision() is read directly from MskController with no access to the service's lock at all, so no per-call-site synchronized block can close that gap. Make revisions/serverPropertiesByRevision CopyOnWriteArrayList/ConcurrentHashMap instead, so every current and future reader is safe by construction rather than by remembering to take a lock it may not have access to. * fix(msk): migrate pre-revision-history configurations onto revision 1 A configuration persisted before this PR's schema change stored a single "latestRevision" object plus a flat "serverProperties" string. Those keys were only being swallowed by ignoreUnknown, so the entry loaded with an empty revision list and getLatestRevision() == null. AWS marks Configuration's LatestRevision required, and toConfigurationView builds into a HashMap - which keeps a key with a null value, unlike Map.of - with no NON_NULL inclusion configured anywhere in the application. So DescribeConfiguration and ListConfigurations emitted a required member as an explicit "latestRevision": null for those entries, and UpdateConfiguration rejected them permanently. Map both old keys back onto revision 1 at load time instead. The data was always still there, so this is a migration rather than a degradation, and it un-breaks UpdateConfiguration for those configurations as well. - The setters are deserialize-only: @JsonSetter is an explicit marker, so it survives the @JsonIgnore split on getLatestRevision() without re-enabling the write side. The old shape is read, never written back. - Jackson calls the two setters in whatever order the keys sit in the file, so neither can assemble the revision alone; each buffers its half and the pair completes the migration. - A legacy entry with no serverProperties migrates to an empty string, not null: serverPropertiesByRevision is a ConcurrentHashMap, which rejects null values, and DescribeConfigurationRevision base64-encodes what it finds without a null check. - The updateConfiguration guard stays, now covering only an entry with no revision data at all rather than every pre-schema configuration. Also corrects the comment in listConfigurationRevisions, which still justified its lock by calling the collections plain and non-concurrent. That was true when it was written but stopped being true in 93bc30e7; the lock is kept, for consistency with describeConfigurationRevision reading both collections, not to prevent a torn read. Verified locally: MskServiceTest 34, MskControllerTest 2, MskControllerIntegrationTest 20 - 0 failures, 0 errors. Reverting only the MskConfiguration change fails 6 of the new tests, confirming they bite.
This commit is contained in:
1 parent
c54f8ddf02
commit
7505110ed9
8 files changed
+798
-23
No files matched your search
+145
@@ -11,6 +11,7 @@ import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
@@ -296,4 +297,148 @@ class MskControllerIntegrationTest {
|
||||
.when().get("/v1/configurations?nextToken=not-a-valid-token!!")
|
||||
.then().statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateConfigurationAndRevisionRoundTrip() {
|
||||
String propsV1 = Base64.getEncoder().encodeToString("auto.create.topics.enable=true".getBytes(StandardCharsets.UTF_8));
|
||||
String propsV2 = Base64.getEncoder().encodeToString("auto.create.topics.enable=false".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
String arn = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"name": "revision-test", "description": "v1", "kafkaVersions": ["3.6.0"], "serverProperties": "%s"}
|
||||
""".formatted(propsV1))
|
||||
.when()
|
||||
.post("/v1/configurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("arn");
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"description": "v2", "serverProperties": "%s"}
|
||||
""".formatted(propsV2))
|
||||
.when()
|
||||
.put("/v1/configurations/{arn}", arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("arn", equalTo(arn))
|
||||
.body("latestRevision.revision", equalTo(2));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v1/configurations/{arn}/revisions", arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("revisions", hasSize(2))
|
||||
.body("revisions[0].revision", equalTo(1))
|
||||
.body("revisions[1].revision", equalTo(2))
|
||||
// AWS's ConfigurationRevision shape never includes serverProperties.
|
||||
.body("revisions[0]", not(hasKey("serverProperties")));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v1/configurations/{arn}/revisions/1", arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("arn", equalTo(arn))
|
||||
.body("revision", equalTo(1))
|
||||
.body("description", equalTo("v1"))
|
||||
.body("serverProperties", equalTo(propsV1));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v1/configurations/{arn}/revisions/2", arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("revision", equalTo(2))
|
||||
.body("description", equalTo("v2"))
|
||||
.body("serverProperties", equalTo(propsV2));
|
||||
|
||||
// DescribeConfiguration/ListConfigurations still never leak serverProperties.
|
||||
given()
|
||||
.when()
|
||||
.get("/v1/configurations/{arn}", arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("latestRevision.revision", equalTo(2))
|
||||
.body("$", not(hasKey("serverProperties")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateConfigurationReturnsNotFoundForUnknownArn() {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"serverProperties\": \"cHJvcHM=\"}")
|
||||
.when()
|
||||
.put("/v1/configurations/{arn}", "arn:aws:kafka:us-east-1:000000000000:configuration/missing/id")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateConfigurationRejectsMissingServerProperties() {
|
||||
String propsV1 = Base64.getEncoder().encodeToString("props".getBytes(StandardCharsets.UTF_8));
|
||||
String arn = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"name": "update-missing-props", "serverProperties": "%s"}
|
||||
""".formatted(propsV1))
|
||||
.when()
|
||||
.post("/v1/configurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("arn");
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"description\": \"v2\"}")
|
||||
.when()
|
||||
.put("/v1/configurations/{arn}", arn)
|
||||
.then()
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeConfigurationRevisionReturnsNotFoundForUnknownRevision() {
|
||||
String propsV1 = Base64.getEncoder().encodeToString("props".getBytes(StandardCharsets.UTF_8));
|
||||
String arn = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"name": "revision-not-found-test", "serverProperties": "%s"}
|
||||
""".formatted(propsV1))
|
||||
.when()
|
||||
.post("/v1/configurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("arn");
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v1/configurations/{arn}/revisions/99", arn)
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeConfigurationRevisionRejectsNonNumericRevision() {
|
||||
String propsV1 = Base64.getEncoder().encodeToString("props".getBytes(StandardCharsets.UTF_8));
|
||||
String arn = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"name": "revision-bad-path-test", "serverProperties": "%s"}
|
||||
""".formatted(propsV1))
|
||||
.when()
|
||||
.post("/v1/configurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("arn");
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v1/configurations/{arn}/revisions/abc", arn)
|
||||
.then()
|
||||
.statusCode(400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package io.github.hectorvent.floci.services.msk;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.services.msk.model.ConfigurationRevision;
|
||||
import io.github.hectorvent.floci.services.msk.model.MskConfiguration;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
// Covers the response views the controller assembles by hand, without standing up Quarkus.
|
||||
// The configuration views are built into a HashMap, which - unlike Map.of - accepts a null
|
||||
// value and keeps the key, and nothing in this application sets a NON_NULL serialization
|
||||
// inclusion. So a null latestRevision does not vanish from the response: it goes out as an
|
||||
// explicit "latestRevision": null, and AWS marks Configuration's LatestRevision required.
|
||||
class MskControllerTest {
|
||||
|
||||
private MskService mskService;
|
||||
private MskController controller;
|
||||
|
||||
// A configuration exactly as the pre-revision-history schema persisted it - the one case
|
||||
// that used to reach the views with no revision history at all.
|
||||
private static final String LEGACY_JSON = """
|
||||
{
|
||||
"arn": "arn:aws:kafka:us-east-1:000000000000:configuration/legacy/id",
|
||||
"name": "legacy",
|
||||
"description": "desc",
|
||||
"kafkaVersions": ["3.6.0"],
|
||||
"state": "ACTIVE",
|
||||
"creationTime": 1700000000,
|
||||
"latestRevision": {"revision": 1, "creationTime": 1700000000, "description": "desc"},
|
||||
"serverProperties": "auto.create.topics.enable=true"
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mskService = Mockito.mock(MskService.class);
|
||||
controller = new MskController(mskService);
|
||||
}
|
||||
|
||||
private static MskConfiguration legacyConfiguration() throws Exception {
|
||||
return new ObjectMapper().registerModule(new JavaTimeModule())
|
||||
.readValue(LEGACY_JSON, MskConfiguration.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> entityOf(Response response) {
|
||||
return (Map<String, Object>) response.getEntity();
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeConfigurationReturnsLatestRevisionForPreRevisionHistoryEntry() throws Exception {
|
||||
MskConfiguration legacy = legacyConfiguration();
|
||||
when(mskService.describeConfiguration(legacy.getArn())).thenReturn(legacy);
|
||||
|
||||
Map<String, Object> view = entityOf(controller.describeConfiguration(legacy.getArn()));
|
||||
|
||||
// Present as a key at all is not enough - a HashMap holds the key with a null value,
|
||||
// and that is what would be serialized.
|
||||
assertNotNull(view.get("latestRevision"));
|
||||
assertEquals(1L, ((ConfigurationRevision) view.get("latestRevision")).getRevision());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listConfigurationsReturnsLatestRevisionForPreRevisionHistoryEntry() throws Exception {
|
||||
MskConfiguration legacy = legacyConfiguration();
|
||||
when(mskService.listConfigurations(null, null))
|
||||
.thenReturn(new PaginatedResult<>(List.of(legacy), null));
|
||||
|
||||
Map<String, Object> response = entityOf(controller.listConfigurations(null, null));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> configurations = (List<Map<String, Object>>) response.get("configurations");
|
||||
assertEquals(1, configurations.size());
|
||||
assertNotNull(configurations.get(0).get("latestRevision"));
|
||||
assertEquals(1L, ((ConfigurationRevision) configurations.get(0).get("latestRevision")).getRevision());
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,13 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
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.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.services.msk.model.ClusterState;
|
||||
import io.github.hectorvent.floci.services.msk.model.ConfigurationRevision;
|
||||
import io.github.hectorvent.floci.services.msk.model.ConfigurationRevisionDetail;
|
||||
import io.github.hectorvent.floci.services.msk.model.ConfigurationState;
|
||||
import io.github.hectorvent.floci.services.msk.model.MskCluster;
|
||||
import io.github.hectorvent.floci.services.msk.model.MskConfiguration;
|
||||
@@ -17,7 +20,11 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -28,14 +35,26 @@ class MskServiceTest {
|
||||
private StorageFactory storageFactory;
|
||||
private EmulatorConfig config;
|
||||
private RedpandaManager redpandaManager;
|
||||
// MskService's constructor creates the cluster backend first and the configuration backend
|
||||
// second; captured here so tests can seed raw entries directly into the configuration store
|
||||
// (e.g. to simulate a pre-revision-history persisted entry) without exposing it from MskService.
|
||||
private StorageBackend<String, MskConfiguration> configurationStorage;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
storageFactory = Mockito.mock(StorageFactory.class);
|
||||
// A fresh backend per call - MskService now creates two (clusters, configurations),
|
||||
// and a shared instance would let configuration scans see cluster entries and vice versa.
|
||||
// The configuration backend is also captured by filename so tests can seed raw entries
|
||||
// into it directly (e.g. to simulate a pre-revision-history persisted entry).
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
.thenAnswer(invocation -> {
|
||||
AccountAwareStorageBackend<?> backend = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
if ("msk-configurations.json".equals(invocation.getArgument(1))) {
|
||||
configurationStorage = (StorageBackend<String, MskConfiguration>) backend;
|
||||
}
|
||||
return backend;
|
||||
});
|
||||
|
||||
config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
@@ -107,7 +126,8 @@ class MskServiceTest {
|
||||
assertTrue(configuration.getArn().contains("test-config"));
|
||||
assertNotNull(configuration.getLatestRevision());
|
||||
assertEquals(1L, configuration.getLatestRevision().getRevision());
|
||||
assertEquals("auto.create.topics.enable=true", configuration.getServerProperties());
|
||||
assertEquals("auto.create.topics.enable=true",
|
||||
configuration.getServerPropertiesByRevision().get(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -198,6 +218,92 @@ class MskServiceTest {
|
||||
assertTrue(mskService.listConfigurations(null, null).items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateConfiguration() {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"test-config", "v1 desc", List.of("3.6.0"), "auto.create.topics.enable=true");
|
||||
|
||||
MskConfiguration updated = mskService.updateConfiguration(
|
||||
created.getArn(), "v2 desc", "auto.create.topics.enable=false");
|
||||
|
||||
assertEquals(2L, updated.getLatestRevision().getRevision());
|
||||
assertEquals("v2 desc", updated.getLatestRevision().getDescription());
|
||||
// Revision 1 is untouched - update appends, it doesn't overwrite.
|
||||
assertEquals("auto.create.topics.enable=true", updated.getServerPropertiesByRevision().get(1L));
|
||||
assertEquals("auto.create.topics.enable=false", updated.getServerPropertiesByRevision().get(2L));
|
||||
assertEquals(2, updated.getRevisions().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateConfigurationRejectsMissingServerProperties() {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"test-config", "desc", List.of("3.6.0"), "props");
|
||||
assertThrows(AwsException.class, () ->
|
||||
mskService.updateConfiguration(created.getArn(), "desc", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateConfigurationNotFoundThrows() {
|
||||
assertThrows(AwsException.class, () ->
|
||||
mskService.updateConfiguration(
|
||||
"arn:aws:kafka:us-east-1:000000000000:configuration/missing/id", "desc", "props"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listConfigurationRevisions() {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"test-config", "desc", List.of("3.6.0"), "props-v1");
|
||||
mskService.updateConfiguration(created.getArn(), "desc v2", "props-v2");
|
||||
mskService.updateConfiguration(created.getArn(), "desc v3", "props-v3");
|
||||
|
||||
List<ConfigurationRevision> revisions =
|
||||
mskService.listConfigurationRevisions(created.getArn(), null, null).items();
|
||||
assertEquals(3, revisions.size());
|
||||
assertEquals(1L, revisions.get(0).getRevision());
|
||||
assertEquals(3L, revisions.get(2).getRevision());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listConfigurationRevisionsPaginates() {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"test-config", "desc", List.of("3.6.0"), "props-v1");
|
||||
mskService.updateConfiguration(created.getArn(), "desc v2", "props-v2");
|
||||
mskService.updateConfiguration(created.getArn(), "desc v3", "props-v3");
|
||||
|
||||
PaginatedResult<ConfigurationRevision> firstPage =
|
||||
mskService.listConfigurationRevisions(created.getArn(), 2, null);
|
||||
assertEquals(2, firstPage.items().size());
|
||||
assertNotNull(firstPage.nextToken());
|
||||
|
||||
PaginatedResult<ConfigurationRevision> secondPage =
|
||||
mskService.listConfigurationRevisions(created.getArn(), 2, firstPage.nextToken());
|
||||
assertEquals(1, secondPage.items().size());
|
||||
assertEquals(3L, secondPage.items().getFirst().getRevision());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeConfigurationRevisionReturnsServerPropertiesForThatRevision() {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"test-config", "desc", List.of("3.6.0"), "props-v1");
|
||||
mskService.updateConfiguration(created.getArn(), "desc v2", "props-v2");
|
||||
|
||||
ConfigurationRevisionDetail rev1 = mskService.describeConfigurationRevision(created.getArn(), 1L);
|
||||
assertEquals("props-v1", rev1.getServerProperties());
|
||||
assertEquals("desc", rev1.getDescription());
|
||||
|
||||
ConfigurationRevisionDetail rev2 = mskService.describeConfigurationRevision(created.getArn(), 2L);
|
||||
assertEquals("props-v2", rev2.getServerProperties());
|
||||
assertEquals("desc v2", rev2.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeConfigurationRevisionNotFoundThrows() {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"test-config", "desc", List.of("3.6.0"), "props");
|
||||
assertThrows(AwsException.class, () ->
|
||||
mskService.describeConfigurationRevision(created.getArn(), 99L));
|
||||
}
|
||||
|
||||
// StorageBackend persists this model via plain Jackson serialization (PersistentStorage,
|
||||
// HybridStorage, WalStorage all call ObjectMapper#writeValue on it directly), so
|
||||
// serverProperties must round-trip through JSON or persistent/hybrid/wal storage modes
|
||||
@@ -211,6 +317,188 @@ class MskServiceTest {
|
||||
String json = mapper.writeValueAsString(configuration);
|
||||
MskConfiguration restored = mapper.readValue(json, MskConfiguration.class);
|
||||
|
||||
assertEquals("auto.create.topics.enable=true", restored.getServerProperties());
|
||||
assertEquals("auto.create.topics.enable=true",
|
||||
restored.getServerPropertiesByRevision().get(1L));
|
||||
}
|
||||
|
||||
// A configuration persisted by the pre-revision-history schema stored "latestRevision" and
|
||||
// a flat "serverProperties" instead of a revision list. Both are mapped back onto revision 1
|
||||
// as it loads - otherwise the entry would come back with getLatestRevision() == null, and
|
||||
// AWS marks Configuration's LatestRevision required, so DescribeConfiguration and
|
||||
// ListConfigurations would emit a required member as an explicit null for it.
|
||||
@Test
|
||||
void preRevisionHistorySchemaMigratesOntoRevisionOne() throws Exception {
|
||||
String oldSchemaJson = """
|
||||
{
|
||||
"arn": "arn:aws:kafka:us-east-1:000000000000:configuration/legacy/id",
|
||||
"name": "legacy",
|
||||
"description": "desc",
|
||||
"kafkaVersions": ["3.6.0"],
|
||||
"state": "ACTIVE",
|
||||
"creationTime": 1700000000,
|
||||
"latestRevision": {"revision": 1, "creationTime": 1700000000, "description": "desc"},
|
||||
"serverProperties": "auto.create.topics.enable=true"
|
||||
}
|
||||
""";
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
MskConfiguration restored = mapper.readValue(oldSchemaJson, MskConfiguration.class);
|
||||
|
||||
assertEquals("legacy", restored.getName());
|
||||
assertNotNull(restored.getLatestRevision());
|
||||
assertEquals(1L, restored.getLatestRevision().getRevision());
|
||||
assertEquals("desc", restored.getLatestRevision().getDescription());
|
||||
assertEquals(1, restored.getRevisions().size());
|
||||
assertEquals("auto.create.topics.enable=true",
|
||||
restored.getServerPropertiesByRevision().get(1L));
|
||||
}
|
||||
|
||||
// Jackson calls the two legacy setters in whatever order the keys sit in the file, so the
|
||||
// migration cannot assume "serverProperties" is read before "latestRevision". Same fixture
|
||||
// as above with the two keys swapped.
|
||||
@Test
|
||||
void preRevisionHistorySchemaMigratesRegardlessOfKeyOrder() throws Exception {
|
||||
String oldSchemaJson = """
|
||||
{
|
||||
"serverProperties": "auto.create.topics.enable=true",
|
||||
"latestRevision": {"revision": 1, "creationTime": 1700000000, "description": "desc"},
|
||||
"arn": "arn:aws:kafka:us-east-1:000000000000:configuration/legacy/id",
|
||||
"name": "legacy",
|
||||
"kafkaVersions": ["3.6.0"],
|
||||
"state": "ACTIVE",
|
||||
"creationTime": 1700000000
|
||||
}
|
||||
""";
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
MskConfiguration restored = mapper.readValue(oldSchemaJson, MskConfiguration.class);
|
||||
|
||||
assertEquals(1, restored.getRevisions().size());
|
||||
assertEquals("auto.create.topics.enable=true",
|
||||
restored.getServerPropertiesByRevision().get(1L));
|
||||
}
|
||||
|
||||
// serverPropertiesByRevision is a ConcurrentHashMap, which rejects null values, and
|
||||
// DescribeConfigurationRevision base64-encodes what it finds without a null check - so a
|
||||
// legacy entry missing serverProperties has to migrate to an empty string, not a null.
|
||||
@Test
|
||||
void preRevisionHistorySchemaWithoutServerPropertiesMigratesToEmptyProperties() throws Exception {
|
||||
String oldSchemaJson = """
|
||||
{
|
||||
"arn": "arn:aws:kafka:us-east-1:000000000000:configuration/legacy/id",
|
||||
"name": "legacy",
|
||||
"kafkaVersions": ["3.6.0"],
|
||||
"state": "ACTIVE",
|
||||
"creationTime": 1700000000,
|
||||
"latestRevision": {"revision": 1, "creationTime": 1700000000}
|
||||
}
|
||||
""";
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
MskConfiguration restored = mapper.readValue(oldSchemaJson, MskConfiguration.class);
|
||||
|
||||
assertEquals(1L, restored.getLatestRevision().getRevision());
|
||||
assertEquals("", restored.getServerPropertiesByRevision().get(1L));
|
||||
}
|
||||
|
||||
// The migration adds setters for the two old key names; it must not also start writing them
|
||||
// back out, or a file saved today would load as a legacy entry tomorrow.
|
||||
@Test
|
||||
void migrationDoesNotReintroduceLegacyKeysOnSerialization() throws Exception {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"round-trip", "v1", List.of("3.6.0"), "props-v1");
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
String json = mapper.writeValueAsString(created);
|
||||
|
||||
assertFalse(json.contains("latestRevision"));
|
||||
assertFalse(json.contains("legacyServerProperties"));
|
||||
assertFalse(json.contains("legacyRevisionNumber"));
|
||||
// The per-revision map keeps its own name; only the flat legacy key must be gone.
|
||||
assertTrue(json.contains("serverPropertiesByRevision"));
|
||||
}
|
||||
|
||||
// The whole point of the migration: a pre-revision-history entry is updatable again rather
|
||||
// than being rejected for the rest of its life.
|
||||
@Test
|
||||
void updateConfigurationOnMigratedPreRevisionHistoryEntryAppendsRevisionTwo() throws Exception {
|
||||
String oldSchemaJson = """
|
||||
{
|
||||
"arn": "arn:aws:kafka:us-east-1:000000000000:configuration/legacy/id",
|
||||
"name": "legacy",
|
||||
"kafkaVersions": ["3.6.0"],
|
||||
"state": "ACTIVE",
|
||||
"creationTime": 1700000000,
|
||||
"latestRevision": {"revision": 1, "creationTime": 1700000000},
|
||||
"serverProperties": "props"
|
||||
}
|
||||
""";
|
||||
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
MskConfiguration legacy = mapper.readValue(oldSchemaJson, MskConfiguration.class);
|
||||
// Seed the service's own backing store directly - the point of this test is what
|
||||
// happens when MskService reads back an already-persisted legacy entry, not what
|
||||
// happens to an object that was merely deserialized in isolation.
|
||||
configurationStorage.put(legacy.getArn(), legacy);
|
||||
|
||||
MskConfiguration updated = mskService.updateConfiguration(legacy.getArn(), "new desc", "new-props");
|
||||
|
||||
assertEquals(2L, updated.getLatestRevision().getRevision());
|
||||
assertEquals(2, updated.getRevisions().size());
|
||||
// Revision 1's migrated properties survive the update rather than being overwritten.
|
||||
assertEquals("props", updated.getServerPropertiesByRevision().get(1L));
|
||||
assertEquals("new-props", updated.getServerPropertiesByRevision().get(2L));
|
||||
}
|
||||
|
||||
// Nothing the emulator has ever written looks like this, but the guard in
|
||||
// updateConfiguration still has to hold for a store that carries no revision data at all -
|
||||
// hand-edited, or an entry whose latestRevision was explicitly null.
|
||||
@Test
|
||||
void updateConfigurationWithNoRevisionDataAtAllStillThrowsInsteadOfNpe() throws Exception {
|
||||
String noRevisionJson = """
|
||||
{
|
||||
"arn": "arn:aws:kafka:us-east-1:000000000000:configuration/legacy/id",
|
||||
"name": "legacy",
|
||||
"kafkaVersions": ["3.6.0"],
|
||||
"state": "ACTIVE",
|
||||
"creationTime": 1700000000,
|
||||
"latestRevision": null
|
||||
}
|
||||
""";
|
||||
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
MskConfiguration broken = mapper.readValue(noRevisionJson, MskConfiguration.class);
|
||||
assertNull(broken.getLatestRevision());
|
||||
configurationStorage.put(broken.getArn(), broken);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> {
|
||||
mskService.updateConfiguration(broken.getArn(), "new desc", "new-props");
|
||||
});
|
||||
assertEquals("BadRequestException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentUpdatesProduceDistinctRevisionsWithoutOverwritingServerProperties() throws InterruptedException {
|
||||
MskConfiguration created = mskService.createConfiguration(
|
||||
"concurrent-config", "v0", List.of("3.6.0"), "props-v0");
|
||||
|
||||
int updates = 16;
|
||||
ExecutorService pool = Executors.newFixedThreadPool(8);
|
||||
for (int i = 0; i < updates; i++) {
|
||||
int idx = i;
|
||||
pool.submit(() -> mskService.updateConfiguration(created.getArn(), "v" + idx, "props-" + idx));
|
||||
}
|
||||
pool.shutdown();
|
||||
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "updates did not finish");
|
||||
|
||||
MskConfiguration finalState = mskService.describeConfiguration(created.getArn());
|
||||
List<Long> revisionNumbers = finalState.getRevisions().stream()
|
||||
.map(ConfigurationRevision::getRevision).toList();
|
||||
|
||||
assertEquals(1 + updates, revisionNumbers.size(), "revision count");
|
||||
assertEquals(revisionNumbers.size(), new HashSet<>(revisionNumbers).size(),
|
||||
"duplicate revision numbers were assigned");
|
||||
for (long revision : revisionNumbers) {
|
||||
assertNotNull(finalState.getServerPropertiesByRevision().get(revision),
|
||||
"revision " + revision + " lost its serverProperties");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user