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

* fix(core): extract shared pagination helper, reject maxResults=0

Closes #2339, #2340.

ListResult<T> and its paginate()/encode()/decode() helpers existed as
five near-identical private copies (BedrockAgentCoreGatewayService,
BedrockAgentCoreIdentityService, BedrockAgentCoreMemoryService,
BedrockAgentCoreControlService's three list methods, and MskService),
not the two originally scoped in #2340 - the ListResult<T> record was
already shared within bedrockagentcorecontrol, which is what earlier
scoping missed. Extracts core.common.Pagination + PaginatedResult<T>
and migrates every one of them, deleting both now-unused per-service
ListResult model classes.

Every duplicate collapsed "maxResults omitted" and "maxResults=0"
onto the same primitive int, defaulting both to the full page instead
of rejecting the explicit zero the way AWS's MaxResults min:1
constraint requires (confirmed against botocore's real kafka and
verified live: botocore itself refuses to send MaxResults=0
client-side). Pagination.paginate/parseMaxResults take a boxed
Integer so the two cases are distinguishable, and every migrated
service now rejects 0 with its own existing error code
(ValidationException for the bedrockagentcorecontrol services,
BadRequestException for MSK) - the fix lands once, not five times.

Also carries over the MskController fix from #2336: an
Integer-typed @QueryParam converts before the resource method runs,
so a non-numeric maxResults was a bare 404 instead of an AWS-shaped
400. Every migrated REST controller now binds maxResults as a String
and calls Pagination.parseMaxResults, closing the same gap in
BedrockAgentCoreGatewayController/ControlController/MemoryController
that MSK already had fixed.

* feat(msk): add configuration revision actions

Closes #2338.

Adds UpdateConfiguration, ListConfigurationRevisions, and
DescribeConfigurationRevision, the three actions #2299 explicitly
scoped out ("a separate follow-up issue"). MskConfiguration now
stores a full revision history (revisions + serverPropertiesByRevision
keyed by revision number) instead of a single latest-revision field -
UpdateConfiguration appends rather than overwrites, and
DescribeConfigurationRevision is the only action that returns
serverProperties (base64), matching AWS's real shapes: Configuration/
DescribeConfigurationResponse/CreateConfigurationResponse never
include it, verified against botocore's kafka service model the same
way as #2336/#2343 rather than trusting the docs page.

ListConfigurationRevisions builds on the shared Pagination.paginate
helper from #2343 (cursor = zero-padded revision number) instead of
introducing a sixth duplicate of that logic.

getLatestRevision() is now derived from the revision list rather than
a separately-stored field, so it can never drift out of sync with it.

* fix(msk): guard configuration schema upgrade and update-race in UpdateConfiguration

Old (pre-revision-history) persisted configurations have latestRevision/
serverProperties keys this class no longer maps, which previously threw and
failed the entire msk-configurations.json load; ignore them instead and
reject updates against such an entry with a 400 rather than NPE-ing.

Also serialize UpdateConfiguration's read-modify-write behind a lock so two
concurrent updates for the same ARN can no longer derive the same revision
number and silently overwrite each other's serverProperties.

* fix(msk): stop leaking mutable revision state through getters

MskConfiguration#getRevisions/getServerPropertiesByRevision returned the
live internal List/Map, which is why MskService#updateConfiguration was
mutating through them directly - and in an order (revision appended,
then its properties inserted) that let an unsynchronized reader observe
a revision with no server properties yet and NPE on Base64-encoding it.

Add MskConfiguration#addRevision to own both writes in the safe order,
and have the getters return copies so callers can no longer bypass it.

* fix(msk): guard revision reads with the same lock updateConfiguration writes under

listConfigurationRevisions/describeConfigurationRevision read revisions
and serverPropertiesByRevision - plain, non-thread-safe collections -
without holding configurationUpdateLock, so a concurrent updateConfiguration
could race the reader's iteration/copy, not just return stale data.

* fix(msk): close remaining unsynchronized-read races on configuration revisions

Two more gaps in the same family as the last fix:

- deleteConfiguration didn't take configurationUpdateLock, so it could
  race updateConfiguration and get resurrected by the update's trailing
  put(arn, ...) after the delete already removed the entry.
- getLatestRevision() is read directly from MskController with no access
  to the service's lock at all, so no per-call-site synchronized block
  can close that gap. Make revisions/serverPropertiesByRevision
  CopyOnWriteArrayList/ConcurrentHashMap instead, so every current and
  future reader is safe by construction rather than by remembering to
  take a lock it may not have access to.

* fix(msk): migrate pre-revision-history configurations onto revision 1

A configuration persisted before this PR's schema change stored a single
"latestRevision" object plus a flat "serverProperties" string. Those keys
were only being swallowed by ignoreUnknown, so the entry loaded with an
empty revision list and getLatestRevision() == null. AWS marks
Configuration's LatestRevision required, and toConfigurationView builds
into a HashMap - which keeps a key with a null value, unlike Map.of - with
no NON_NULL inclusion configured anywhere in the application. So
DescribeConfiguration and ListConfigurations emitted a required member as
an explicit "latestRevision": null for those entries, and
UpdateConfiguration rejected them permanently.

Map both old keys back onto revision 1 at load time instead. The data was
always still there, so this is a migration rather than a degradation, and
it un-breaks UpdateConfiguration for those configurations as well.

- The setters are deserialize-only: @JsonSetter is an explicit marker, so
  it survives the @JsonIgnore split on getLatestRevision() without
  re-enabling the write side. The old shape is read, never written back.
- Jackson calls the two setters in whatever order the keys sit in the
  file, so neither can assemble the revision alone; each buffers its half
  and the pair completes the migration.
- A legacy entry with no serverProperties migrates to an empty string, not
  null: serverPropertiesByRevision is a ConcurrentHashMap, which rejects
  null values, and DescribeConfigurationRevision base64-encodes what it
  finds without a null check.
- The updateConfiguration guard stays, now covering only an entry with no
  revision data at all rather than every pre-schema configuration.

Also corrects the comment in listConfigurationRevisions, which still
justified its lock by calling the collections plain and non-concurrent.
That was true when it was written but stopped being true in 93bc30e7; the
lock is kept, for consistency with describeConfigurationRevision reading
both collections, not to prevent a torn read.

Verified locally: MskServiceTest 34, MskControllerTest 2,
MskControllerIntegrationTest 20 - 0 failures, 0 errors. Reverting only the
MskConfiguration change fails 6 of the new tests, confirming they bite.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-19 21:53:33 -05:00
1 parent c54f8ddf02
commit 7505110ed9
8 files changed
+798 -23

No files matched your search

@@ -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;
@@ -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() {
@@ -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; }
}
@@ -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;
// 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. 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;
// 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; }