Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(msk): add configuration revision actions (#2344)

Priamo Germosen7505110ed96b
diff --git a/docs/services/msk.md b/docs/services/msk.md
index a83ab8646e..47ca8e4948 100644
--- a/docs/services/msk.md
+++ b/docs/services/msk.md
@@ -21,6 +21,9 @@ Floci emulates Amazon MSK by orchestrating **Redpanda** containers. This provide
| `ListConfigurations` | List all configurations |
| `DescribeConfiguration` | Get configuration metadata and latest revision |
| `DeleteConfiguration` | Delete a configuration |
+| `UpdateConfiguration` | Create a new revision of a configuration |
+| `ListConfigurationRevisions` | List all revisions of a configuration |
+| `DescribeConfigurationRevision` | Get a specific revision, including its `server.properties` |
## Configuration
diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/MskController.java b/src/main/java/io/github/hectorvent/floci/services/msk/MskController.java
index 80b7101bbf..ef14520403 100644
--- a/src/main/java/io/github/hectorvent/floci/services/msk/MskController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/msk/MskController.java
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.msk;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
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.ConfigurationRevisionDetail;
import io.github.hectorvent.floci.services.msk.model.MskCluster;
import io.github.hectorvent.floci.services.msk.model.MskConfiguration;
import jakarta.inject.Inject;
@@ -142,6 +144,51 @@ public class MskController {
return Response.ok(Map.of("arn", arn, "state", "DELETING")).build();
}
+ @PUT
+ @Path("/v1/configurations/{arn}")
+ public Response updateConfiguration(@PathParam("arn") String arn, Map<String, Object> request) {
+ String description = asString(request.get("description"), "description");
+ String serverProperties = decodeServerProperties(asString(request.get("serverProperties"), "serverProperties"));
+
+ MskConfiguration configuration = mskService.updateConfiguration(arn, description, serverProperties);
+ return Response.ok(Map.of(
+ "arn", configuration.getArn(),
+ "latestRevision", configuration.getLatestRevision())).build();
+ }
+
+ @GET
+ @Path("/v1/configurations/{arn}/revisions")
+ public Response listConfigurationRevisions(@PathParam("arn") String arn,
+ @QueryParam("maxResults") String maxResultsParam,
+ @QueryParam("nextToken") String nextToken) {
+ PaginatedResult<ConfigurationRevision> result = mskService.listConfigurationRevisions(arn,
+ Pagination.parseMaxResults(maxResultsParam, "BadRequestException"), nextToken);
+
+ Map<String, Object> response = new HashMap<>();
+ response.put("revisions", result.items());
+ if (result.nextToken() != null) {
+ response.put("nextToken", result.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ @GET
+ @Path("/v1/configurations/{arn}/revisions/{revision}")
+ public Response describeConfigurationRevision(@PathParam("arn") String arn,
+ @PathParam("revision") String revisionParam) {
+ long revision = parseRevision(revisionParam);
+ ConfigurationRevisionDetail detail = mskService.describeConfigurationRevision(arn, revision);
+
+ Map<String, Object> response = new HashMap<>();
+ response.put("arn", detail.getArn());
+ response.put("creationTime", detail.getCreationTime());
+ response.put("description", detail.getDescription() != null ? detail.getDescription() : "");
+ response.put("revision", detail.getRevision());
+ response.put("serverProperties",
+ Base64.getEncoder().encodeToString(detail.getServerProperties().getBytes(StandardCharsets.UTF_8)));
+ return Response.ok(response).build();
+ }
+
// AWS's Configuration/DescribeConfigurationResponse shape never includes
// serverProperties (that's only returned via DescribeConfigurationRevision), so build
// an explicit view instead of serializing the model directly.
@@ -157,6 +204,17 @@ public class MskController {
return view;
}
+ // Bound as String rather than @PathParam long, matching the same reasoning as
+ // maxResults: a failed path-param conversion should return an AWS-shaped 400, not
+ // whatever the framework's own default handling produces.
+ private long parseRevision(String value) {
+ try {
+ return Long.parseLong(value);
+ } catch (NumberFormatException e) {
+ throw new AwsException("BadRequestException", "revision must be an integer.", 400);
+ }
+ }
+
private String decodeServerProperties(String serverPropertiesB64) {
if (serverPropertiesB64 == null) {
return null;
diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java
index a99f13554e..f1748cc36a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java
@@ -10,6 +10,8 @@ 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.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;
@@ -21,6 +23,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
+import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -40,6 +43,7 @@ public class MskService {
private final RegionResolver regionResolver;
private final RedpandaManager redpandaManager;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
+ private final Object configurationUpdateLock = new Object();
@Inject
public MskService(StorageFactory storageFactory, EmulatorConfig config,
@@ -160,11 +164,82 @@ public class MskService {
}
public MskConfiguration deleteConfiguration(String arn) {
- MskConfiguration configuration = describeConfiguration(arn);
- configuration.setState(ConfigurationState.DELETING);
- configurationStorage.delete(arn);
- LOG.infov("Deleted MSK configuration: {0}", configuration.getName());
- return configuration;
+ // Shares updateConfiguration's lock so the two can't interleave: without it, a delete
+ // could remove the entry while an in-flight update still holds its pre-delete read,
+ // then that update's own put(arn, ...) at the end of its critical section would put the
+ // "deleted" configuration right back, resurrecting it.
+ synchronized (configurationUpdateLock) {
+ MskConfiguration configuration = describeConfiguration(arn);
+ configuration.setState(ConfigurationState.DELETING);
+ configurationStorage.delete(arn);
+ LOG.infov("Deleted MSK configuration: {0}", configuration.getName());
+ return configuration;
+ }
+ }
+
+ public MskConfiguration updateConfiguration(String arn, String description, String serverProperties) {
+ if (serverProperties == null || serverProperties.isBlank()) {
+ throw new AwsException("BadRequestException", "serverProperties is required.", 400);
+ }
+
+ // Read-modify-write on the shared configuration: two concurrent updates for the same
+ // ARN could otherwise derive the same "next revision" number before either persists,
+ // silently overwriting one request's serverProperties under the other's revision key.
+ synchronized (configurationUpdateLock) {
+ MskConfiguration configuration = describeConfiguration(arn);
+ if (configuration.getState() != ConfigurationState.ACTIVE) {
+ throw new AwsException("BadRequestException",
+ "Configuration must be ACTIVE to update: " + arn, 400);
+ }
+ ConfigurationRevision latestRevision = configuration.getLatestRevision();
+ if (latestRevision == null) {
+ // MskConfiguration now maps a pre-revision-history entry onto revision 1 as
+ // it loads, so this no longer catches every configuration written before the
+ // schema changed - only one with no revision data at all to build on (a
+ // hand-edited store, or an entry whose latestRevision was explicitly null).
+ throw new AwsException("BadRequestException",
+ "Configuration has no revision history and cannot be updated: " + arn, 400);
+ }
+
+ long newRevisionNumber = latestRevision.getRevision() + 1;
+ configuration.addRevision(new ConfigurationRevision(newRevisionNumber, Instant.now(), description), serverProperties);
+
+ configurationStorage.put(arn, configuration);
+ LOG.infov("Updated MSK configuration {0} to revision {1}", configuration.getName(), newRevisionNumber);
+ return configuration;
+ }
+ }
+
+ public PaginatedResult<ConfigurationRevision> listConfigurationRevisions(String arn, Integer maxResults, String nextToken) {
+ // Snapshot revisions under the same lock updateConfiguration writes under. Now that
+ // MskConfiguration's collections are concurrent-safe this is no longer what prevents a
+ // torn read - getRevisions() copies a CopyOnWriteArrayList, which cannot tear on its
+ // own. It is kept so every reader of revision state serializes against an in-flight
+ // update the same way, rather than leaving describeConfigurationRevision - which reads
+ // both collections and does need them to agree - as the only one holding the lock.
+ List<ConfigurationRevision> revisions;
+ synchronized (configurationUpdateLock) {
+ revisions = describeConfiguration(arn).getRevisions();
+ }
+ return Pagination.paginate(revisions,
+ revision -> String.format("%019d", revision.getRevision()),
+ maxResults, nextToken, MAX_PAGE, "BadRequestException");
+ }
+
+ public ConfigurationRevisionDetail describeConfigurationRevision(String arn, long revision) {
+ ConfigurationRevision found;
+ String serverProperties;
+ synchronized (configurationUpdateLock) {
+ MskConfiguration configuration = describeConfiguration(arn);
+ found = configuration.getRevisions().stream()
+ .filter(r -> r.getRevision() == revision)
+ .findFirst()
+ .orElseThrow(() -> new AwsException("NotFoundException",
+ "Revision not found: " + revision + " for configuration " + arn, 404));
+ serverProperties = configuration.getServerPropertiesByRevision().get(revision);
+ }
+ return new ConfigurationRevisionDetail(arn, found.getCreationTime(), found.getDescription(),
+ revision, serverProperties);
}
private void startReadinessPoller() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationRevisionDetail.java b/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationRevisionDetail.java
new file mode 100644
index 0000000000..fa7c0ff3e4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationRevisionDetail.java
@@ -0,0 +1,35 @@
+package io.github.hectorvent.floci.services.msk.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+/**
+ * Full shape of DescribeConfigurationRevision - the only MSK configuration action that
+ * returns serverProperties. Transient: never serialized directly, only assembled by a
+ * service method and read field-by-field by the controller.
+ */
+@RegisterForReflection
+public class ConfigurationRevisionDetail {
+
+ private final String arn;
+ private final Instant creationTime;
+ private final String description;
+ private final long revision;
+ private final String serverProperties;
+
+ public ConfigurationRevisionDetail(String arn, Instant creationTime, String description,
+ long revision, String serverProperties) {
+ this.arn = arn;
+ this.creationTime = creationTime;
+ this.description = description;
+ this.revision = revision;
+ this.serverProperties = serverProperties;
+ }
+
+ public String getArn() { return arn; }
+ public Instant getCreationTime() { return creationTime; }
+ public String getDescription() { return description; }
+ public long getRevision() { return revision; }
+ public String getServerProperties() { return serverProperties; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/model/MskConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/msk/model/MskConfiguration.java
index 0a6aebfedd..93aa187605 100644
--- a/src/main/java/io/github/hectorvent/floci/services/msk/model/MskConfiguration.java
+++ b/src/main/java/io/github/hectorvent/floci/services/msk/model/MskConfiguration.java
@@ -1,12 +1,25 @@
package io.github.hectorvent.floci.services.msk.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonSetter;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
-
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+// A configuration persisted by the previous (pre-revision-history) schema stored one
+// "latestRevision" object plus a flat "serverProperties" string instead of a revision list.
+// Both keys are mapped back onto revision 1 at load time (see the legacy setters at the bottom
+// of this class), so an entry written before this schema still reports a latestRevision and can
+// still be updated, rather than loading as a configuration with no revision history at all.
+// ignoreUnknown stays for anything else an older writer may have left behind: without it a
+// single stale key would fail the whole msk-configurations.json load, not just that entry.
+@JsonIgnoreProperties(ignoreUnknown = true)
@RegisterForReflection
public class MskConfiguration {
@@ -28,16 +41,22 @@ public class MskConfiguration {
@JsonProperty("creationTime")
private Instant creationTime;
- @JsonProperty("latestRevision")
- private ConfigurationRevision latestRevision;
-
- // Decoded server.properties content. Must round-trip through persistent/hybrid/wal
- // storage (StorageBackend serializes this same model via Jackson), so it cannot be
- // @JsonIgnore - the controller builds explicit response views instead to keep it out
- // of Create/List/Describe responses, since AWS only returns it via
- // DescribeConfigurationRevision (a separate follow-up issue, out of scope here).
- @JsonProperty("serverProperties")
- private String serverProperties;
+ // Full revision history, oldest first. AWS's Configuration/CreateConfigurationResponse/
+ // DescribeConfigurationResponse shapes only ever expose the latest one (see
+ // getLatestRevision()); the full list backs ListConfigurationRevisions.
+ //
+ // Concurrent-safe by construction (CopyOnWriteArrayList/ConcurrentHashMap), not just by
+ // convention: getLatestRevision() and the getters below are read from MskController with no
+ // access to MskService#configurationUpdateLock, so a plain ArrayList/HashMap here would let
+ // an in-flight updateConfiguration() on another thread corrupt or crash an unrelated read.
+ @JsonProperty("revisions")
+ private List<ConfigurationRevision> revisions = new CopyOnWriteArrayList<>();
+
+ // Decoded server.properties content, keyed by revision. AWS never returns this on the
+ // configuration/latestRevision shapes - only DescribeConfigurationRevision - so it's kept
+ // out of ConfigurationRevision itself, which those other shapes serialize directly.
+ @JsonProperty("serverPropertiesByRevision")
+ private Map<Long, String> serverPropertiesByRevision = new ConcurrentHashMap<>();
@JsonIgnore
private String accountId;
@@ -50,10 +69,9 @@ public class MskConfiguration {
this.name = name;
this.description = description;
this.kafkaVersions = kafkaVersions;
- this.serverProperties = serverProperties;
this.state = ConfigurationState.ACTIVE;
this.creationTime = Instant.now();
- this.latestRevision = new ConfigurationRevision(1L, this.creationTime, description);
+ addRevision(new ConfigurationRevision(1L, this.creationTime, description), serverProperties);
}
public String getArn() { return arn; }
@@ -74,11 +92,76 @@ public class MskConfiguration {
public Instant getCreationTime() { return creationTime; }
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
- public ConfigurationRevision getLatestRevision() { return latestRevision; }
- public void setLatestRevision(ConfigurationRevision latestRevision) { this.latestRevision = latestRevision; }
+ // Derived from revisions, not its own stored field, so it can never drift out of sync.
+ // Must stay @JsonIgnore: writing it back out would re-create the pre-revision-history shape
+ // this class now migrates away from, so a file saved today would load as a legacy entry
+ // tomorrow. Only the serialization half is off - @JsonSetter("latestRevision") on
+ // setLegacyLatestRevision below keeps reading the old key working.
+ @JsonIgnore
+ public ConfigurationRevision getLatestRevision() {
+ return revisions.isEmpty() ? null : revisions.get(revisions.size() - 1);
+ }
- public String getServerProperties() { return serverProperties; }
- public void setServerProperties(String serverProperties) { this.serverProperties = serverProperties; }
+ // Read-only views: callers must go through addRevision() to mutate, so this class controls
+ // publish order (server properties land before the revision that references them becomes
+ // visible) rather than letting a caller append to a live list a reader can observe mid-update.
+ public List<ConfigurationRevision> getRevisions() { return List.copyOf(revisions); }
+ public void setRevisions(List<ConfigurationRevision> revisions) {
+ this.revisions = revisions != null ? new CopyOnWriteArrayList<>(revisions) : new CopyOnWriteArrayList<>();
+ }
+
+ public Map<Long, String> getServerPropertiesByRevision() { return Map.copyOf(serverPropertiesByRevision); }
+ public void setServerPropertiesByRevision(Map<Long, String> serverPropertiesByRevision) {
+ this.serverPropertiesByRevision = serverPropertiesByRevision != null
+ ? new ConcurrentHashMap<>(serverPropertiesByRevision) : new ConcurrentHashMap<>();
+ }
+
+ // Server properties are stored before the revision that references them is appended, so a
+ // reader who isn't holding the caller's update lock can never observe a revision whose
+ // properties aren't there yet (see MskService#updateConfiguration).
+ public void addRevision(ConfigurationRevision revision, String serverProperties) {
+ this.serverPropertiesByRevision.put(revision.getRevision(), serverProperties);
+ this.revisions.add(revision);
+ }
+
+ // ── Pre-revision-history schema migration ────────────────────────────────────────────
+
+ // The old schema's two halves arrive as separate setter calls, in whatever order the keys
+ // happen to sit in the file, so neither can assemble the revision alone. These buffer what
+ // has been seen so far. Deliberately un-annotated and private: Jackson's default field
+ // visibility is PUBLIC_ONLY, so they stay invisible to serialization on their own, and an
+ // explicit @JsonIgnore here would risk splitting the logical property the renamed setters
+ // below belong to.
+ private String legacyServerProperties;
+ private Long legacyRevisionNumber;
+
+ // Deserialize-only - getLatestRevision() is @JsonIgnore, so this key is never written back.
+ // Ignored when revisions is already populated: a current-schema file sets "revisions"
+ // directly and never writes "latestRevision", but this way the two can't fight if one ever
+ // did carry both, whichever order they load in.
+ @JsonSetter("latestRevision")
+ public void setLegacyLatestRevision(ConfigurationRevision latestRevision) {
+ if (latestRevision == null || !revisions.isEmpty()) {
+ return;
+ }
+ // Empty string rather than null when the old entry carried no serverProperties:
+ // serverPropertiesByRevision is a ConcurrentHashMap and would reject a null value, and
+ // DescribeConfigurationRevision base64-encodes whatever it finds without a null check.
+ addRevision(latestRevision, legacyServerProperties != null ? legacyServerProperties : "");
+ this.legacyRevisionNumber = latestRevision.getRevision();
+ }
+
+ // Same deserialize-only treatment. Back-fills rather than assuming it runs first, since it
+ // may arrive after setLegacyLatestRevision has already seeded the revision with the empty
+ // placeholder above. Keyed off legacyRevisionNumber so a current-schema entry that somehow
+ // carried a stray top-level "serverProperties" is left alone.
+ @JsonSetter("serverProperties")
+ public void setLegacyServerProperties(String serverProperties) {
+ this.legacyServerProperties = serverProperties;
+ if (serverProperties != null && legacyRevisionNumber != null) {
+ this.serverPropertiesByRevision.put(legacyRevisionNumber, serverProperties);
+ }
+ }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/msk/MskControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/msk/MskControllerIntegrationTest.java
index 142292b622..24758a51f6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/msk/MskControllerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/msk/MskControllerIntegrationTest.java
@@ -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);
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/msk/MskControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/msk/MskControllerTest.java
new file mode 100644
index 0000000000..14fb79db77
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/msk/MskControllerTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java
index 6db74d38f2..ab43ebd189 100644
--- a/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java
@@ -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");
+ }
}
}