Light, fluffy, and always free - The AWS Local Emulator alternative
feat(msk): add configuration CRUD (Create/List/Describe/Delete) (#2336)
Priamo Germosen4c510e576c9b
diff --git a/docs/services/msk.md b/docs/services/msk.mdindex 4e02c7e711..a83ab8646e 100644--- a/docs/services/msk.md+++ b/docs/services/msk.md@@ -17,6 +17,10 @@ Floci emulates Amazon MSK by orchestrating **Redpanda** containers. This provide| `DescribeClusterV2` | Get cluster metadata and state using V2 API || `DeleteCluster` | Stops and removes the Redpanda container || `GetBootstrapBrokers` | Get the connection strings for the cluster |+| `CreateConfiguration` | Create a broker configuration (`server.properties`) |+| `ListConfigurations` | List all configurations |+| `DescribeConfiguration` | Get configuration metadata and latest revision |+| `DeleteConfiguration` | Delete a configuration |## Configurationdiff --git a/src/main/java/io/github/hectorvent/floci/services/msk/MskController.java b/src/main/java/io/github/hectorvent/floci/services/msk/MskController.javaindex 84e3ad8fdd..b8c7f71203 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@@ -1,10 +1,18 @@package io.github.hectorvent.floci.services.msk;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.msk.model.ListResult;import io.github.hectorvent.floci.services.msk.model.MskCluster;+import io.github.hectorvent.floci.services.msk.model.MskConfiguration;import jakarta.inject.Inject;import jakarta.ws.rs.*;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.Response;++import java.nio.charset.StandardCharsets;+import java.util.Base64;+import java.util.HashMap;+import java.util.List;import java.util.Map;@Path("/")@@ -81,4 +89,115 @@ public class MskController {String bootstrapBrokers = mskService.getBootstrapBrokers(clusterArn);return Response.ok(Map.of("bootstrapBrokerString", bootstrapBrokers)).build();}++ // ── Configurations ───────────────────────────────────────────────────────++ @POST+ @Path("/v1/configurations")+ public Response createConfiguration(Map<String, Object> request) {+ String name = asString(request.get("name"), "name");+ String description = asString(request.get("description"), "description");+ List<String> kafkaVersions = asStringList(request.get("kafkaVersions"), "kafkaVersions");+ String serverProperties = decodeServerProperties(asString(request.get("serverProperties"), "serverProperties"));++ MskConfiguration configuration = mskService.createConfiguration(name, description, kafkaVersions, serverProperties);+ return Response.ok(Map.of(+ "arn", configuration.getArn(),+ "name", configuration.getName(),+ "state", configuration.getState(),+ "creationTime", configuration.getCreationTime(),+ "latestRevision", configuration.getLatestRevision())).build();+ }++ @GET+ @Path("/v1/configurations")+ public Response listConfigurations(@QueryParam("maxResults") String maxResultsParam,+ @QueryParam("nextToken") String nextToken) {+ ListResult<MskConfiguration> result = mskService.listConfigurations(+ parseMaxResults(maxResultsParam), nextToken);+ var configurations = result.items().stream()+ .map(this::toConfigurationView)+ .toList();++ Map<String, Object> response = new HashMap<>();+ response.put("configurations", configurations);+ if (result.nextToken() != null) {+ response.put("nextToken", result.nextToken());+ }+ return Response.ok(response).build();+ }++ @GET+ @Path("/v1/configurations/{arn}")+ public Response describeConfiguration(@PathParam("arn") String arn) {+ MskConfiguration configuration = mskService.describeConfiguration(arn);+ return Response.ok(toConfigurationView(configuration)).build();+ }++ @DELETE+ @Path("/v1/configurations/{arn}")+ public Response deleteConfiguration(@PathParam("arn") String arn) {+ mskService.deleteConfiguration(arn);+ return Response.ok(Map.of("arn", arn, "state", "DELETING")).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.+ private Map<String, Object> toConfigurationView(MskConfiguration configuration) {+ Map<String, Object> view = new HashMap<>();+ view.put("arn", configuration.getArn());+ view.put("name", configuration.getName());+ view.put("description", configuration.getDescription() != null ? configuration.getDescription() : "");+ view.put("kafkaVersions", configuration.getKafkaVersions() != null ? configuration.getKafkaVersions() : List.of());+ view.put("state", configuration.getState());+ view.put("creationTime", configuration.getCreationTime());+ view.put("latestRevision", configuration.getLatestRevision());+ return view;+ }++ private String decodeServerProperties(String serverPropertiesB64) {+ if (serverPropertiesB64 == null) {+ return null;+ }+ try {+ return new String(Base64.getDecoder().decode(serverPropertiesB64), StandardCharsets.UTF_8);+ } catch (IllegalArgumentException e) {+ throw new AwsException("BadRequestException", "serverProperties must be base64-encoded.", 400);+ }+ }++ // Bound as String rather than @QueryParam Integer: RESTEasy Reactive's default handling+ // of a non-numeric value for an Integer-typed @QueryParam is a 404, not a 400 - the+ // request never reaches this method at all in that case, so it must be parsed here.+ private int parseMaxResults(String value) {+ if (value == null || value.isBlank()) {+ return 0;+ }+ try {+ return Integer.parseInt(value);+ } catch (NumberFormatException e) {+ throw new AwsException("BadRequestException", "maxResults must be an integer.", 400);+ }+ }++ private String asString(Object value, String fieldName) {+ if (value == null) {+ return null;+ }+ if (!(value instanceof String s)) {+ throw new AwsException("BadRequestException", fieldName + " must be a string.", 400);+ }+ return s;+ }++ private List<String> asStringList(Object value, String fieldName) {+ if (value == null) {+ return null;+ }+ if (!(value instanceof List<?> list) || list.stream().anyMatch(item -> !(item instanceof String))) {+ throw new AwsException("BadRequestException", fieldName + " must be an array of strings.", 400);+ }+ return list.stream().map(String.class::cast).toList();+ }}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.javaindex ed5053a196..5ccb76f923 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@@ -8,7 +8,10 @@ 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.ConfigurationState;+import io.github.hectorvent.floci.services.msk.model.ListResult;import io.github.hectorvent.floci.services.msk.model.MskCluster;+import io.github.hectorvent.floci.services.msk.model.MskConfiguration;import com.fasterxml.jackson.core.type.TypeReference;import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;@@ -16,19 +19,27 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import java.nio.charset.StandardCharsets;import java.security.SecureRandom;+import java.util.Base64;+import java.util.Comparator;import java.util.List;import java.util.Map;+import java.util.UUID;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;+import java.util.function.Function;+import java.util.stream.Collectors;@ApplicationScopedpublic class MskService {private static final Logger LOG = Logger.getLogger(MskService.class);private static final String DEFAULT_KAFKA_VERSION = "3.6.0";+ private static final int MAX_PAGE = 100;private final StorageBackend<String, MskCluster> storage;+ private final StorageBackend<String, MskConfiguration> configurationStorage;private final EmulatorConfig config;private final RegionResolver regionResolver;private final RedpandaManager redpandaManager;@@ -38,6 +49,8 @@ public class MskService {public MskService(StorageFactory storageFactory, EmulatorConfig config,RegionResolver regionResolver, RedpandaManager redpandaManager) {this.storage = storageFactory.create("msk", "msk-clusters.json", new TypeReference<Map<String, MskCluster>>() {});+ this.configurationStorage = storageFactory.create("msk", "msk-configurations.json",+ new TypeReference<Map<String, MskConfiguration>>() {});this.config = config;this.regionResolver = regionResolver;this.redpandaManager = redpandaManager;@@ -112,6 +125,93 @@ public class MskService {return cluster.getBootstrapBrokers();}+ public MskConfiguration createConfiguration(String name, String description,+ List<String> kafkaVersions, String serverProperties) {+ if (name == null || name.isBlank()) {+ throw new AwsException("BadRequestException", "name is required.", 400);+ }+ if (!name.matches("[0-9A-Za-z][0-9A-Za-z-]*")) {+ throw new AwsException("BadRequestException",+ "Configuration name must match the pattern \"^[0-9A-Za-z][0-9A-Za-z-]{0,}$\".", 400);+ }+ if (serverProperties == null || serverProperties.isBlank()) {+ throw new AwsException("BadRequestException", "serverProperties is required.", 400);+ }+ if (configurationStorage.scan(k -> true).stream().anyMatch(c -> c.getName().equals(name))) {+ throw new AwsException("ConflictException", "Configuration already exists: " + name, 409);+ }++ String accountId = regionResolver.getAccountId();+ String arn = AwsArnUtils.Arn.of("kafka", config.defaultRegion(), accountId,+ "configuration/" + name + "/" + UUID.randomUUID()).toString();++ MskConfiguration configuration = new MskConfiguration(arn, name, description, kafkaVersions, serverProperties);+ configuration.setAccountId(accountId);++ configurationStorage.put(arn, configuration);+ LOG.infov("Created MSK configuration: {0}", name);+ return configuration;+ }++ public MskConfiguration describeConfiguration(String arn) {+ return configurationStorage.get(arn)+ .orElseThrow(() -> new AwsException("NotFoundException", "Configuration not found: " + arn, 404));+ }++ public ListResult<MskConfiguration> listConfigurations(int maxResults, String nextToken) {+ List<MskConfiguration> all = configurationStorage.scan(k -> true).stream()+ .sorted(Comparator.comparing(MskConfiguration::getArn))+ .collect(Collectors.toList());+ return paginate(all, MskConfiguration::getArn, maxResults, nextToken);+ }++ private <T> ListResult<T> paginate(List<T> all, Function<T, String> cursorOf, int maxResults, String nextToken) {+ if (maxResults < 0 || maxResults > MAX_PAGE) {+ throw new AwsException("BadRequestException", "maxResults must be between 1 and " + MAX_PAGE, 400);+ }+ int limit = maxResults > 0 ? maxResults : MAX_PAGE;+ String after = decodeToken(nextToken);+ int start = 0;+ if (after != null) {+ for (int i = 0; i < all.size(); i++) {+ if (cursorOf.apply(all.get(i)).compareTo(after) > 0) {+ start = i;+ break;+ }+ start = i + 1;+ }+ }+ List<T> page = all.stream().skip(start).limit(limit).collect(Collectors.toList());+ String token = null;+ if (start + limit < all.size() && !page.isEmpty()) {+ token = encodeToken(cursorOf.apply(page.get(page.size() - 1)));+ }+ return new ListResult<>(page, token);+ }++ private static String encodeToken(String cursor) {+ return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));+ }++ private static String decodeToken(String token) {+ if (token == null || token.isEmpty()) {+ return null;+ }+ try {+ return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);+ } catch (IllegalArgumentException e) {+ throw new AwsException("BadRequestException", "Invalid nextToken.", 400);+ }+ }++ 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;+ }+private void startReadinessPoller() {poller.scheduleAtFixedRate(() -> {try {diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationRevision.java b/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationRevision.javanew file mode 100644index 0000000000..fc4b284f98--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationRevision.java@@ -0,0 +1,36 @@+package io.github.hectorvent.floci.services.msk.model;++import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++@RegisterForReflection+public class ConfigurationRevision {++ @JsonProperty("revision")+ private long revision;++ @JsonProperty("creationTime")+ private Instant creationTime;++ @JsonProperty("description")+ private String description;++ public ConfigurationRevision() {}++ public ConfigurationRevision(long revision, Instant creationTime, String description) {+ this.revision = revision;+ this.creationTime = creationTime;+ this.description = description;+ }++ public long getRevision() { return revision; }+ public void setRevision(long revision) { this.revision = revision; }++ public Instant getCreationTime() { return creationTime; }+ public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationState.java b/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationState.javanew file mode 100644index 0000000000..d27e9e0da5--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/msk/model/ConfigurationState.java@@ -0,0 +1,14 @@+package io.github.hectorvent.floci.services.msk.model;++import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+public enum ConfigurationState {+ @JsonProperty("ACTIVE")+ ACTIVE,+ @JsonProperty("DELETING")+ DELETING,+ @JsonProperty("DELETE_FAILED")+ DELETE_FAILED+}diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/model/ListResult.java b/src/main/java/io/github/hectorvent/floci/services/msk/model/ListResult.javanew file mode 100644index 0000000000..0e6fbe69cb--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/msk/model/ListResult.java@@ -0,0 +1,12 @@+package io.github.hectorvent.floci.services.msk.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++/**+ * A page of list results plus an optional pagination token.+ */+@RegisterForReflection+public record ListResult<T>(List<T> items, String nextToken) {+}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.javanew file mode 100644index 0000000000..0a6aebfedd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/msk/model/MskConfiguration.java@@ -0,0 +1,85 @@+package io.github.hectorvent.floci.services.msk.model;++import com.fasterxml.jackson.annotation.JsonIgnore;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.List;++@RegisterForReflection+public class MskConfiguration {++ @JsonProperty("arn")+ private String arn;++ @JsonProperty("name")+ private String name;++ @JsonProperty("description")+ private String description;++ @JsonProperty("kafkaVersions")+ private List<String> kafkaVersions;++ @JsonProperty("state")+ private ConfigurationState state;++ @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;++ @JsonIgnore+ private String accountId;++ public MskConfiguration() {}++ public MskConfiguration(String arn, String name, String description,+ List<String> kafkaVersions, String serverProperties) {+ this.arn = arn;+ 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);+ }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }++ public List<String> getKafkaVersions() { return kafkaVersions; }+ public void setKafkaVersions(List<String> kafkaVersions) { this.kafkaVersions = kafkaVersions; }++ public ConfigurationState getState() { return state; }+ public void setState(ConfigurationState state) { this.state = state; }++ 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; }++ public String getServerProperties() { return serverProperties; }+ public void setServerProperties(String serverProperties) { this.serverProperties = 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.javaindex ae6dbf947f..1c72c2bbf1 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@@ -3,8 +3,17 @@ package io.github.hectorvent.floci.services.msk;import io.quarkus.test.junit.QuarkusTest;import org.junit.jupiter.api.Test;+import java.nio.charset.StandardCharsets;+import java.util.Base64;+import java.util.UUID;+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.hasSize;+import static org.hamcrest.Matchers.not;+import static org.hamcrest.Matchers.notNullValue;@QuarkusTestclass MskControllerIntegrationTest {@@ -71,4 +80,211 @@ class MskControllerIntegrationTest {.statusCode(200).body("clusterInfo.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.6.0"));}++ @Test+ void configurationCrudRoundTrip() {+ String properties = "auto.create.topics.enable=true\nlog.retention.hours=168";+ String propertiesB64 = Base64.getEncoder().encodeToString(properties.getBytes(StandardCharsets.UTF_8));++ String arn = given()+ .contentType("application/json")+ .body("""+ {"name": "test-config", "description": "a test config", "kafkaVersions": ["3.6.0"], "serverProperties": "%s"}+ """.formatted(propertiesB64))+ .when()+ .post("/v1/configurations")+ .then()+ .statusCode(200)+ .body("name", equalTo("test-config"))+ .body("state", equalTo("ACTIVE"))+ .body("latestRevision.revision", equalTo(1))+ .extract().path("arn");++ given()+ .when()+ .get("/v1/configurations/{arn}", arn)+ .then()+ .statusCode(200)+ .body("name", equalTo("test-config"))+ .body("description", equalTo("a test config"))+ .body("kafkaVersions", hasSize(1))+ .body("arn", equalTo(arn));++ given()+ .when()+ .get("/v1/configurations")+ .then()+ .statusCode(200)+ .body("configurations.name", hasItem("test-config"));++ given()+ .when()+ .delete("/v1/configurations/{arn}", arn)+ .then()+ .statusCode(200)+ .body("arn", equalTo(arn))+ .body("state", equalTo("DELETING"));++ given()+ .when()+ .get("/v1/configurations/{arn}", arn)+ .then()+ .statusCode(404);+ }++ @Test+ void createConfigurationRejectsNonBase64ServerProperties() {+ given()+ .contentType("application/json")+ .body("""+ {"name": "bad-config", "kafkaVersions": ["3.6.0"], "serverProperties": "not-valid-base64!!"}+ """)+ .when()+ .post("/v1/configurations")+ .then()+ .statusCode(400);+ }++ // A wrong-typed field must fail with an AWS-shaped 400, not an unhandled+ // ClassCastException surfacing as a 500.+ @Test+ void createConfigurationRejectsNonStringName() {+ given()+ .contentType("application/json")+ .body("""+ {"name": 123, "kafkaVersions": ["3.6.0"], "serverProperties": "cHJvcHM="}+ """)+ .when()+ .post("/v1/configurations")+ .then()+ .statusCode(400);+ }++ @Test+ void createConfigurationRejectsNonArrayKafkaVersions() {+ given()+ .contentType("application/json")+ .body("""+ {"name": "bad-config", "kafkaVersions": "3.6.0", "serverProperties": "cHJvcHM="}+ """)+ .when()+ .post("/v1/configurations")+ .then()+ .statusCode(400);+ }++ @Test+ void createConfigurationRejectsKafkaVersionsWithNonStringElements() {+ given()+ .contentType("application/json")+ .body("""+ {"name": "bad-config", "kafkaVersions": [3.6], "serverProperties": "cHJvcHM="}+ """)+ .when()+ .post("/v1/configurations")+ .then()+ .statusCode(400);+ }++ @Test+ void describeConfigurationReturnsNotFoundForUnknownArn() {+ given()+ .when()+ .get("/v1/configurations/{arn}", "arn:aws:kafka:us-east-1:000000000000:configuration/missing/id")+ .then()+ .statusCode(404);+ }++ // kafkaVersions is optional on CreateConfigurationRequest. Omitting it must not leak a+ // null into the "kafkaVersions" field of the Configuration shape returned by+ // DescribeConfiguration/ListConfigurations, which AWS always populates as an array.+ @Test+ void configurationWithoutKafkaVersionsReturnsEmptyArrayNotNull() {+ String properties = Base64.getEncoder().encodeToString("props".getBytes(StandardCharsets.UTF_8));+ String arn = given()+ .contentType("application/json")+ .body("""+ {"name": "no-versions-config", "serverProperties": "%s"}+ """.formatted(properties))+ .when()+ .post("/v1/configurations")+ .then()+ .statusCode(200)+ .extract().path("arn");++ given()+ .when()+ .get("/v1/configurations/{arn}", arn)+ .then()+ .statusCode(200)+ .body("kafkaVersions", empty());++ given()+ .when()+ .get("/v1/configurations")+ .then()+ .statusCode(200)+ .body("configurations.find { it.arn == '" + arn + "' }.kafkaVersions", empty());+ }++ @Test+ void listConfigurationsPaginatesWithMaxResultsAndNextToken() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String properties = Base64.getEncoder().encodeToString("props".getBytes(StandardCharsets.UTF_8));++ given().contentType("application/json")+ .body("""+ {"name": "page-a-%s", "serverProperties": "%s"}+ """.formatted(suffix, properties))+ .when().post("/v1/configurations")+ .then().statusCode(200);++ given().contentType("application/json")+ .body("""+ {"name": "page-b-%s", "serverProperties": "%s"}+ """.formatted(suffix, properties))+ .when().post("/v1/configurations")+ .then().statusCode(200);++ var page1 = given()+ .when().get("/v1/configurations?maxResults=1")+ .then().statusCode(200)+ .body("configurations", hasSize(1))+ .body("nextToken", notNullValue())+ .extract().jsonPath();++ String page1Arn = page1.getString("configurations[0].arn");+ String token = page1.getString("nextToken");++ given()+ .when().get("/v1/configurations?maxResults=1&nextToken=" + token)+ .then().statusCode(200)+ .body("configurations", hasSize(1))+ .body("configurations[0].arn", not(equalTo(page1Arn)));+ }++ @Test+ void listConfigurationsRejectsMaxResultsAboveLimit() {+ given()+ .when().get("/v1/configurations?maxResults=101")+ .then().statusCode(400);+ }++ // maxResults is bound as a raw String and parsed by hand rather than @QueryParam+ // Integer specifically because a non-numeric value for an Integer-typed @QueryParam+ // fails RESTEasy Reactive's own conversion before the method body runs, and its+ // default handling for that is a 404, not an AWS-shaped 400.+ @Test+ void listConfigurationsRejectsNonNumericMaxResults() {+ given()+ .when().get("/v1/configurations?maxResults=abc")+ .then().statusCode(400);+ }++ @Test+ void listConfigurationsRejectsInvalidNextToken() {+ given()+ .when().get("/v1/configurations?nextToken=not-a-valid-token!!")+ .then().statusCode(400);+ }}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.javaindex 1616215c4c..766a712644 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@@ -5,8 +5,14 @@ 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.StorageFactory;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.msk.model.ClusterState;+import io.github.hectorvent.floci.services.msk.model.ConfigurationState;+import io.github.hectorvent.floci.services.msk.model.ListResult;import io.github.hectorvent.floci.services.msk.model.MskCluster;+import io.github.hectorvent.floci.services.msk.model.MskConfiguration;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.mockito.Mockito;@@ -26,8 +32,10 @@ class MskServiceTest {@BeforeEachvoid 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.when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))- .thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));+ .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));config = Mockito.mock(EmulatorConfig.class);var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);@@ -87,4 +95,114 @@ class MskServiceTest {mskService.deleteCluster(cluster.getClusterArn());assertTrue(mskService.listClusters().isEmpty());}++ @Test+ void createConfiguration() {+ MskConfiguration configuration = mskService.createConfiguration(+ "test-config", "a test config", List.of("3.6.0"), "auto.create.topics.enable=true");++ assertNotNull(configuration);+ assertEquals("test-config", configuration.getName());+ assertEquals(ConfigurationState.ACTIVE, configuration.getState());+ assertTrue(configuration.getArn().contains("test-config"));+ assertNotNull(configuration.getLatestRevision());+ assertEquals(1L, configuration.getLatestRevision().getRevision());+ assertEquals("auto.create.topics.enable=true", configuration.getServerProperties());+ }++ @Test+ void createConfigurationRejectsMissingName() {+ assertThrows(AwsException.class, () ->+ mskService.createConfiguration(null, "desc", List.of("3.6.0"), "props"));+ }++ @Test+ void createConfigurationRejectsInvalidNamePattern() {+ assertThrows(AwsException.class, () ->+ mskService.createConfiguration("bad name!", "desc", List.of("3.6.0"), "props"));+ }++ @Test+ void createConfigurationRejectsMissingServerProperties() {+ assertThrows(AwsException.class, () ->+ mskService.createConfiguration("test-config", "desc", List.of("3.6.0"), null));+ }++ @Test+ void createConfigurationRejectsDuplicateName() {+ mskService.createConfiguration("test-config", "desc", List.of("3.6.0"), "props");+ assertThrows(AwsException.class, () ->+ mskService.createConfiguration("test-config", "desc", List.of("3.6.0"), "props"));+ }++ @Test+ void describeConfiguration() {+ MskConfiguration created = mskService.createConfiguration(+ "test-config", "desc", List.of("3.6.0"), "props");+ MskConfiguration described = mskService.describeConfiguration(created.getArn());+ assertEquals(created.getArn(), described.getArn());+ }++ @Test+ void describeConfigurationNotFoundThrows() {+ assertThrows(AwsException.class, () ->+ mskService.describeConfiguration("arn:aws:kafka:us-east-1:000000000000:configuration/missing/id"));+ }++ @Test+ void listConfigurations() {+ mskService.createConfiguration("config-1", "desc", List.of("3.6.0"), "props");+ mskService.createConfiguration("config-2", "desc", List.of("3.6.0"), "props");+ List<MskConfiguration> configurations = mskService.listConfigurations(0, null).items();+ assertEquals(2, configurations.size());+ }++ @Test+ void listConfigurationsPaginatesWithMaxResultsAndNextToken() {+ mskService.createConfiguration("config-1", "desc", List.of("3.6.0"), "props");+ mskService.createConfiguration("config-2", "desc", List.of("3.6.0"), "props");+ mskService.createConfiguration("config-3", "desc", List.of("3.6.0"), "props");++ ListResult<MskConfiguration> firstPage = mskService.listConfigurations(2, null);+ assertEquals(2, firstPage.items().size());+ assertNotNull(firstPage.nextToken());++ ListResult<MskConfiguration> secondPage = mskService.listConfigurations(2, firstPage.nextToken());+ assertEquals(1, secondPage.items().size());+ assertNull(secondPage.nextToken());+ }++ @Test+ void listConfigurationsRejectsMaxResultsAboveLimit() {+ assertThrows(AwsException.class, () -> mskService.listConfigurations(101, null));+ }++ @Test+ void listConfigurationsRejectsInvalidNextToken() {+ assertThrows(AwsException.class, () -> mskService.listConfigurations(0, "not-a-valid-token!!"));+ }++ @Test+ void deleteConfiguration() {+ MskConfiguration configuration = mskService.createConfiguration(+ "test-config", "desc", List.of("3.6.0"), "props");+ mskService.deleteConfiguration(configuration.getArn());+ assertTrue(mskService.listConfigurations(0, null).items().isEmpty());+ }++ // 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+ // silently discard the broker configuration on reload.+ @Test+ void configurationServerPropertiesSurvivesJsonRoundTrip() throws Exception {+ MskConfiguration configuration = mskService.createConfiguration(+ "test-config", "desc", List.of("3.6.0"), "auto.create.topics.enable=true");++ ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());+ String json = mapper.writeValueAsString(configuration);+ MskConfiguration restored = mapper.readValue(json, MskConfiguration.class);++ assertEquals("auto.create.topics.enable=true", restored.getServerProperties());+ }}