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:
Priamo Germosen authored and GitHub committed 2026-08-15 21:50:20 -04:00
1 parent 42022fe937
commit 4c510e576c
9 files changed
+705 -1

No files matched your search

@@ -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 {
@@ -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; }
}