mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(msk): add configuration CRUD (Create/List/Describe/Delete) (#2336)
* feat(msk): add configuration CRUD (Create/List/Describe/Delete) MskController only served /v1/clusters and /api/v2/clusters, so every configuration action 404s. An MSK configuration is the only supported way to set broker-level server_properties, and aws_msk_configuration / aws_msk_domain_policy are first-class Terraform resources - any stack setting broker properties failed before the cluster was even attempted. Adds a second StorageBackend on MskService (msk-configurations.json, mirroring msk-clusters.json), a new MskConfiguration model, and four endpoints on MskController mirroring the existing cluster handlers. serverProperties is base64 on the wire; decoded and kept internal (@JsonIgnore) since AWS only returns it via DescribeConfigurationRevision, which is a separate follow-up issue - this stays plain CRUD. Field names verified against botocore's actual kafka service model rather than trusting the API reference docs verbatim: every field is lowerCamelCase, including DeleteConfigurationResponse's `arn` (the public API reference page shows "Arn" capitalized, which does not match the real wire format). * fix(msk): validate request field types and persist serverProperties CreateConfiguration cast request fields directly (String)/(List<String>), so a wrong-typed field threw ClassCastException instead of an AWS-shaped BadRequestException, surfacing as an internal server error. serverProperties was @JsonIgnore, which excludes it from Jackson serialization entirely - not just REST responses, but also the persistent/hybrid/wal StorageBackend serialization that uses the same model. A configuration would silently lose its broker properties on reload under any non-memory storage mode. The field now serializes normally; the controller instead builds explicit response views for Describe/List/Create so serverProperties still never appears on the wire outside CreateConfiguration's own request, matching AWS (which only returns it via the out-of-scope DescribeConfigurationRevision). * fix(msk): default kafkaVersions to an empty array when omitted kafkaVersions is optional on CreateConfigurationRequest, but asStringList returns null when it's absent, and toConfigurationView put that null straight into the response - AWS's Configuration shape always populates it as an array. Default it the same way description already is. No existing test created a configuration without the field, which is why it slipped through. * feat(msk): support maxResults/nextToken pagination on ListConfigurations ListConfigurations previously returned every configuration in one response, ignoring the maxResults/nextToken query parameters the model declares. Mirrors the existing pagination pattern from BedrockAgentCoreGatewayService (ListResult<T> + a private paginate() helper): the cursor is the last returned item's ARN, base64 URL-encoded, resumed by scanning the ARN-sorted list past that value. maxResults is bounded to [1, 100] and an undecodable token both throw BadRequestException, matching CreateConfiguration's existing error family for this service.
This commit is contained in:
1 parent
42022fe937
commit
4c510e576c
9 files changed
+705
-1
No files matched your search
@@ -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 |
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@ApplicationScoped
|
||||
public 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 {
|
||||
|
||||
+36
@@ -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; }
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
+216
@@ -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;
|
||||
|
||||
@QuarkusTest
|
||||
class 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);
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@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.
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user