Skip to content

armgit / floci

Public Imported from GitHub
0

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

refactor(cloudformation): move the Batch types into BatchCfnProvisioner (#3285)

Hector Ventura82eaaaeee7dd
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index c6bbd28923..c0a749484d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -3,7 +3,6 @@ package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.XmlBuilder;
-import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
@@ -194,9 +193,6 @@ public class CloudFormationResourceProvisioner {
"AWS::ApiGatewayV2::Stage",
"AWS::AutoScaling::AutoScalingGroup",
"AWS::AutoScaling::LaunchConfiguration",
- "AWS::Batch::ComputeEnvironment",
- "AWS::Batch::JobDefinition",
- "AWS::Batch::JobQueue",
"AWS::CloudFormation::CustomResource",
"AWS::CloudFront::Distribution",
"AWS::DynamoDB::GlobalTable",
@@ -246,7 +242,6 @@ public class CloudFormationResourceProvisioner {
private final CustomResourceResponseStore customResourceResponseStore;
private final ContainerReachableEndpoint reachableEndpoint;
private final StepFunctionsService stepFunctionsService;
- private final BatchService batchService;
private final Ec2Service ec2Service;
private final RdsService rdsService;
private final EksService eksService;
@@ -275,7 +270,6 @@ public class CloudFormationResourceProvisioner {
CustomResourceResponseStore customResourceResponseStore,
ContainerReachableEndpoint reachableEndpoint,
StepFunctionsService stepFunctionsService,
- BatchService batchService,
Ec2Service ec2Service,
RdsService rdsService,
EksService eksService,
@@ -302,7 +296,6 @@ public class CloudFormationResourceProvisioner {
this.customResourceResponseStore = customResourceResponseStore;
this.reachableEndpoint = reachableEndpoint;
this.stepFunctionsService = stepFunctionsService;
- this.batchService = batchService;
this.ec2Service = ec2Service;
this.rdsService = rdsService;
this.eksService = eksService;
@@ -391,12 +384,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::CloudFormation::CustomResource" ->
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
case "Custom::DynamoDBReplica" -> provisionDynamoDbReplica(resource, properties, engine, region);
- case "AWS::Batch::ComputeEnvironment" ->
- provisionBatchComputeEnvironment(resource, properties, engine, region, stackName);
- case "AWS::Batch::JobQueue" ->
- provisionBatchJobQueue(resource, properties, engine, region, stackName);
- case "AWS::Batch::JobDefinition" ->
- provisionBatchJobDefinition(resource, properties, engine, region, stackName);
// EC2 networking. These delegate to Ec2Service so the resources actually exist
// (describe-subnets, ELBv2, etc. can find them) instead of being stubbed with a
// fake physical id. Topological ordering guarantees parents are provisioned first.
@@ -3405,158 +3392,6 @@ public class CloudFormationResourceProvisioner {
}
- // ── Batch ────────────────────────────────────────────────────────────────
-
- private void provisionBatchComputeEnvironment(StackResource r, JsonNode props,
- CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String name = resolveOptional(props, "ComputeEnvironmentName", engine);
- if (name == null || name.isBlank()) {
- name = generatePhysicalName(stackName, r.getLogicalId(), 128, false);
- }
-
- ObjectNode req = JsonNodeFactory.instance.objectNode();
- req.put("computeEnvironmentName", name);
- putResolvedText(req, "type", props, "Type", engine);
- putResolvedText(req, "state", props, "State", engine);
- putResolvedText(req, "serviceRole", props, "ServiceRole", engine);
- putResolvedObject(req, "computeResources", props, "ComputeResources", engine);
- putTagsObject(req, props, engine);
-
- ObjectNode response = batchService.createComputeEnvironment(req, region);
- String arn = response.path("computeEnvironmentArn").asText();
- r.setPhysicalId(arn);
- r.getAttributes().put("Arn", arn);
- r.getAttributes().put("ComputeEnvironmentArn", arn);
- r.getAttributes().put("ComputeEnvironmentName", name);
- }
-
- private void provisionBatchJobQueue(StackResource r, JsonNode props,
- CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String name = resolveOptional(props, "JobQueueName", engine);
- if (name == null || name.isBlank()) {
- name = generatePhysicalName(stackName, r.getLogicalId(), 128, false);
- }
-
- ObjectNode req = JsonNodeFactory.instance.objectNode();
- req.put("jobQueueName", name);
- String priority = resolveOptional(props, "Priority", engine);
- req.put("priority", priority != null ? Integer.parseInt(priority) : 1);
- putResolvedText(req, "state", props, "State", engine);
- putResolvedText(req, "jobQueueType", props, "JobQueueType", engine);
- req.set("computeEnvironmentOrder", batchComputeEnvironmentOrder(props, engine));
- putTagsObject(req, props, engine);
-
- ObjectNode response = batchService.createJobQueue(req, region);
- String arn = response.path("jobQueueArn").asText();
- r.setPhysicalId(arn);
- r.getAttributes().put("Arn", arn);
- r.getAttributes().put("JobQueueArn", arn);
- r.getAttributes().put("JobQueueName", name);
- }
-
- private void provisionBatchJobDefinition(StackResource r, JsonNode props,
- CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String name = resolveOptional(props, "JobDefinitionName", engine);
- if (name == null || name.isBlank()) {
- name = generatePhysicalName(stackName, r.getLogicalId(), 128, false);
- }
-
- ObjectNode req = JsonNodeFactory.instance.objectNode();
- req.put("jobDefinitionName", name);
- req.put("type", resolveOrDefault(props, "Type", engine, "container"));
- putResolvedArray(req, "platformCapabilities", props, "PlatformCapabilities", engine);
- if (props != null && props.has("ContainerProperties")) {
- req.set("containerProperties", batchContainerProperties(
- engine.resolveNode(props.get("ContainerProperties")), engine));
- }
- putStringMapFromObject(req, "parameters", props, "Parameters", engine);
- if (props != null && props.has("RetryStrategy")) {
- req.set("retryStrategy", batchRetryStrategy(engine.resolveNode(props.get("RetryStrategy"))));
- }
- if (props != null && props.has("Timeout")) {
- ObjectNode timeout = JsonNodeFactory.instance.objectNode();
- JsonNode resolved = engine.resolveNode(props.get("Timeout"));
- if (resolved.has("AttemptDurationSeconds")) {
- timeout.set("attemptDurationSeconds", resolved.get("AttemptDurationSeconds"));
- }
- req.set("timeout", timeout);
- }
- putTagsObject(req, props, engine);
-
- ObjectNode response = batchService.registerJobDefinition(req, region);
- String arn = response.path("jobDefinitionArn").asText();
- r.setPhysicalId(arn);
- r.getAttributes().put("Arn", arn);
- r.getAttributes().put("JobDefinitionArn", arn);
- r.getAttributes().put("JobDefinitionName", name);
- r.getAttributes().put("Revision", response.path("revision").asText());
- }
-
- private ArrayNode batchComputeEnvironmentOrder(JsonNode props, CloudFormationTemplateEngine engine) {
- ArrayNode out = JsonNodeFactory.instance.arrayNode();
- if (props == null || !props.has("ComputeEnvironmentOrder")) {
- return out;
- }
- JsonNode resolved = engine.resolveNode(props.get("ComputeEnvironmentOrder"));
- if (!resolved.isArray()) {
- return out;
- }
- for (JsonNode item : resolved) {
- ObjectNode order = out.addObject();
- order.put("order", item.path("Order").asInt());
- order.put("computeEnvironment", item.path("ComputeEnvironment").asText(null));
- }
- return out;
- }
-
- private ObjectNode batchContainerProperties(JsonNode resolved, CloudFormationTemplateEngine engine) {
- ObjectNode container = JsonNodeFactory.instance.objectNode();
- if (resolved == null || !resolved.isObject()) {
- return container;
- }
- copyIfPresent(container, "image", resolved, "Image");
- copyIfPresent(container, "command", resolved, "Command");
- copyIfPresent(container, "jobRoleArn", resolved, "JobRoleArn");
- copyIfPresent(container, "executionRoleArn", resolved, "ExecutionRoleArn");
- copyIfPresent(container, "logConfiguration", resolved, "LogConfiguration");
- copyIfPresent(container, "networkConfiguration", resolved, "NetworkConfiguration");
- copyIfPresent(container, "ephemeralStorage", resolved, "EphemeralStorage");
- if (resolved.has("ResourceRequirements") && resolved.get("ResourceRequirements").isArray()) {
- ArrayNode resources = container.putArray("resourceRequirements");
- for (JsonNode item : resolved.get("ResourceRequirements")) {
- ObjectNode requirement = resources.addObject();
- requirement.put("type", item.path("Type").asText(null));
- requirement.put("value", item.path("Value").asText(null));
- }
- }
- if (resolved.has("Environment") && resolved.get("Environment").isArray()) {
- ArrayNode env = container.putArray("environment");
- for (JsonNode item : resolved.get("Environment")) {
- ObjectNode entry = env.addObject();
- entry.put("name", item.path("Name").asText(null));
- entry.put("value", item.path("Value").asText(null));
- }
- }
- return container;
- }
-
- private ObjectNode batchRetryStrategy(JsonNode resolved) {
- ObjectNode retry = JsonNodeFactory.instance.objectNode();
- if (resolved == null || !resolved.isObject()) {
- return retry;
- }
- if (resolved.has("Attempts")) {
- retry.set("attempts", resolved.get("Attempts"));
- }
- if (resolved.has("EvaluateOnExit")) {
- retry.set("evaluateOnExit", resolved.get("EvaluateOnExit"));
- }
- return retry;
- }
-
private void putResolvedText(ObjectNode req, String target, JsonNode props, String source,
CloudFormationTemplateEngine engine) {
String value = resolveOptional(props, source, engine);
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisioner.java
new file mode 100644
index 0000000000..efd89d58eb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisioner.java
@@ -0,0 +1,642 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.batch.BatchService;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+
+/**
+ * CloudFormation provisioning for Batch: {@code AWS::Batch::ComputeEnvironment},
+ * {@code AWS::Batch::JobQueue} and {@code AWS::Batch::JobDefinition}. Extracted from
+ * {@code CloudFormationResourceProvisioner}.
+ *
+ * <p>The template property names are PascalCase and {@link BatchService} speaks the wire
+ * shape's camelCase, so every arm builds a request node rather than passing properties
+ * through.
+ */
+@ApplicationScoped
+public class BatchCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final int NAME_MAX_LENGTH = 128;
+ private static final int PRIORITY_MIN = 0;
+ private static final int PRIORITY_MAX = 1000;
+
+ // Held rather than injected: AGENTS.md has a provisioner inject only the service it wraps, and
+ // the snapshot below needs nothing the configured mapper adds.
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private final BatchService batchService;
+
+ @Inject
+ public BatchCfnProvisioner(BatchService batchService) {
+ this.batchService = batchService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::Batch::ComputeEnvironment",
+ "AWS::Batch::JobQueue",
+ "AWS::Batch::JobDefinition");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ // A snapshot describes the update in flight; one an earlier update left behind is stale.
+ r.getAttributes().remove(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR);
+ // Taken before the arms run: they overwrite the recorded name, and the prior-entity check
+ // reads it, so a decision made afterwards would compare the new name against itself.
+ Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
+ switch (r.getResourceType()) {
+ case "AWS::Batch::ComputeEnvironment" -> provisionComputeEnvironment(r, props, ctx, attributesBefore);
+ case "AWS::Batch::JobQueue" -> provisionJobQueue(r, props, ctx, attributesBefore);
+ case "AWS::Batch::JobDefinition" -> provisionJobDefinition(r, props, ctx, attributesBefore);
+ default -> throw new IllegalStateException(
+ "BatchCfnProvisioner cannot handle " + r.getResourceType());
+ }
+ }
+
+ /**
+ * Whether this update replaced the physical entity, so the displaced one is still owed a
+ * delete once the update commits. Without these four hooks a renamed compute environment or
+ * job queue stayed live in Batch forever: the engine was never told a replacement happened.
+ */
+ @Override
+ public boolean hasReplacementUpdate(StackResource resource) {
+ return ReplacementCleanup.hasReplacement(resource);
+ }
+
+ @Override
+ public String updateCleanupPhysicalId(StackResource resource) {
+ return ReplacementCleanup.cleanupPhysicalId(resource);
+ }
+
+ @Override
+ public UpdateCleanupResult completeUpdate(StackResource resource) {
+ return ReplacementCleanup.complete(resource, this::delete);
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ resource.getAttributes().remove(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR);
+ ReplacementCleanup.clear(resource);
+ }
+
+ /**
+ * Undoes a Batch update when a later resource fails the same stack update. A replacement is
+ * undone through the cleanup record, which points the resource back at the prior entity and
+ * deletes the one this update created. Otherwise the update was in place, and the snapshot
+ * taken before the mutating call is replayed through the same update call that changed it.
+ *
+ * <p>The snapshot is spent only once the restore succeeded: a restore that throws leaves it in
+ * place for the next attempt rather than reporting a rollback that never happened. A resource
+ * this update never touched carries no snapshot and answers false, so the engine keeps
+ * reporting honestly instead of claiming a rollback it did not perform.
+ *
+ * <p><strong>Known limitation, compute environments only.</strong> The restore is exact for
+ * every value the environment already carried, and cannot remove one the failed update
+ * introduced. A {@code serviceRole}, or a {@code computeResources} key, that was absent before
+ * the update is absent from the snapshot too, so the restore call simply omits it, and
+ * UpdateComputeEnvironment leaves an omitted field alone and merges {@code computeResources}
+ * rather than replacing it. The value therefore survives a rollback the stack reports as
+ * successful.
+ *
+ * <p>This is not a gap that can be closed here. UpdateComputeEnvironment is the only way to
+ * put the environment back, and its request shape has no removal: every member other than
+ * {@code computeEnvironment} is an optional set-value, and the partial-merge semantics are
+ * AWS's own. Recorded rather than worked around, in the way
+ * {@code CognitoCfnProvisioner} records its own in-place rollback limitation, and pinned by
+ * {@code BatchCfnProvisionerTest.aRollbackCannotRemoveAValueTheFailedUpdateAdded}.
+ *
+ * <p>Job queues are not affected: {@code updateJobQueue} assigns
+ * {@code computeEnvironmentOrder} wholesale rather than merging it, and {@code state} and
+ * {@code priority} are always present, so that restore is exact.
+ */
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ if (ReplacementCleanup.rollback(resource, this::delete)) {
+ return true;
+ }
+ String raw = resource.getAttributes().get(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR);
+ if (raw == null || raw.isBlank()) {
+ return false;
+ }
+ JsonNode snapshot;
+ try {
+ snapshot = MAPPER.readTree(raw);
+ } catch (JsonProcessingException unreadableSnapshot) {
+ throw new IllegalStateException("Could not read the Batch update snapshot for "
+ + resource.getLogicalId(), unreadableSnapshot);
+ }
+ restoreSnapshot(resource, snapshot);
+ resource.getAttributes().remove(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR);
+ return true;
+ }
+
+ private void restoreSnapshot(StackResource resource, JsonNode snapshot) {
+ String priorId = snapshot.path("physicalId").asText(null);
+ switch (snapshot.path("type").asText("")) {
+ case "AWS::Batch::ComputeEnvironment" -> {
+ ObjectNode update = JsonNodeFactory.instance.objectNode();
+ update.put("computeEnvironment", priorId);
+ copySnapshotted(update, snapshot, "state", "serviceRole", "computeResources");
+ batchService.updateComputeEnvironment(update);
+ }
+ case "AWS::Batch::JobQueue" -> {
+ ObjectNode update = JsonNodeFactory.instance.objectNode();
+ update.put("jobQueue", priorId);
+ copySnapshotted(update, snapshot, "state", "priority", "computeEnvironmentOrder");
+ batchService.updateJobQueue(update);
+ }
+ case "AWS::Batch::JobDefinition" -> {
+ // A revision bump leaves the prior revision ACTIVE, as on AWS, so rolling back is
+ // deregistering the revision this update registered and naming the prior one again.
+ String registered = resource.getPhysicalId();
+ if (registered != null && !registered.equals(priorId)) {
+ deregisterJobDefinition(registered);
+ }
+ resource.setPhysicalId(priorId);
+ resource.getAttributes().put("Arn", priorId);
+ resource.getAttributes().put("JobDefinitionArn", priorId);
+ }
+ default -> throw new IllegalStateException(
+ "Unreadable Batch update snapshot on " + resource.getLogicalId());
+ }
+ }
+
+ private static void copySnapshotted(ObjectNode into, JsonNode snapshot, String... fields) {
+ for (String field : fields) {
+ if (snapshot.has(field) && !snapshot.get(field).isNull()) {
+ into.set(field, snapshot.get(field));
+ }
+ }
+ }
+
+ /**
+ * Records what the entity looks like now, before the update call about to change it. The
+ * describe is the only source: the template holds the desired state, not the current one.
+ *
+ * <p>Best effort by design. An entity the describe cannot find leaves no snapshot, and
+ * {@code rollbackUpdate} then answers false rather than restoring a guess, which is the honest
+ * answer: the engine reports the resource as not rolled back instead of claiming a restore
+ * that never had anything to restore from. Failing the update here would be worse, since it
+ * would break a working update over missing rollback insurance.
+ */
+ private void snapshotBeforeUpdate(StackResource r, String type, String physicalId,
+ String requestKey, Function<ObjectNode, ObjectNode> describe,
+ String... fields) {
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.putArray(requestKey).add(physicalId);
+ ObjectNode described = describe.apply(req);
+ if (described == null) {
+ return;
+ }
+ JsonNode found = described.path(requestKey);
+ if (found.isEmpty()) {
+ return;
+ }
+ JsonNode current = found.get(0);
+ ObjectNode snapshot = JsonNodeFactory.instance.objectNode();
+ snapshot.put("type", type);
+ snapshot.put("physicalId", physicalId);
+ copySnapshotted(snapshot, current, fields);
+ r.getAttributes().put(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
+ }
+
+ /**
+ * Batch refuses to delete a running entity, exactly as AWS does: DeleteJobQueue rejects an
+ * {@code ENABLED} queue and DeleteComputeEnvironment rejects one that is not {@code DISABLED}
+ * or is still referenced by a queue. So each delete disables first, which is what the real
+ * resource handlers do. CloudFormation already tears down in reverse dependency order, so a
+ * queue is gone before the environment it points at.
+ *
+ * <p>Deliberately no {@code CfnDeletes.safeDelete} here, and it is the API that rules it out
+ * rather than a gap in {@link BatchService}. Batch declares exactly two errors on
+ * DeleteComputeEnvironment, DeleteJobQueue and DeregisterJobDefinition, {@code ClientException}
+ * (400) and {@code ServerException} (500); there is no not-found code in the service model to
+ * name, so there is none to tolerate. {@code safeDelete} takes the specific already-gone code
+ * on purpose, and passing {@code ClientException} would be the catch-all AGENTS.md rules out:
+ * a real refusal such as "Cannot delete compute environment still associated with a job queue"
+ * would be swallowed into a green stack delete instead of failing it. Giving Batch a
+ * Floci-only not-found code to satisfy the pattern would put a code on the wire that AWS never
+ * sends.
+ *
+ * <p>Already-gone is handled by looking first instead, which is also what keeps the disable
+ * step from throwing on a resource someone removed out of band. {@code EcsCfnProvisioner} does
+ * tolerate a blanket {@code ClientException} for its task-definition arm, so the divergence
+ * here is deliberate rather than an oversight.
+ */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ switch (resourceType) {
+ case "AWS::Batch::ComputeEnvironment" -> deleteComputeEnvironment(physicalId);
+ case "AWS::Batch::JobQueue" -> deleteJobQueue(physicalId);
+ case "AWS::Batch::JobDefinition" -> deregisterJobDefinition(physicalId);
+ default -> {
+ // no other type reaches this provisioner
+ }
+ }
+ }
+
+ private void deleteComputeEnvironment(String physicalId) {
+ if (!exists("computeEnvironments", physicalId,
+ req -> batchService.describeComputeEnvironments(req))) {
+ return;
+ }
+ ObjectNode disable = JsonNodeFactory.instance.objectNode();
+ disable.put("computeEnvironment", physicalId);
+ disable.put("state", "DISABLED");
+ batchService.updateComputeEnvironment(disable);
+
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.put("computeEnvironment", physicalId);
+ batchService.deleteComputeEnvironment(req);
+ }
+
+ private void deleteJobQueue(String physicalId) {
+ if (!exists("jobQueues", physicalId, req -> batchService.describeJobQueues(req))) {
+ return;
+ }
+ ObjectNode disable = JsonNodeFactory.instance.objectNode();
+ disable.put("jobQueue", physicalId);
+ disable.put("state", "DISABLED");
+ batchService.updateJobQueue(disable);
+
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.put("jobQueue", physicalId);
+ batchService.deleteJobQueue(req);
+ }
+
+ private void deregisterJobDefinition(String physicalId) {
+ // Unlike the other two, deregister throws when the definition is gone, so the existence
+ // check is what makes a repeated stack delete idempotent.
+ if (!exists("jobDefinitions", physicalId, req -> batchService.describeJobDefinitions(req))) {
+ return;
+ }
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.put("jobDefinition", physicalId);
+ batchService.deregisterJobDefinition(req);
+ }
+
+ private boolean exists(String requestKey, String physicalId,
+ Function<ObjectNode, ObjectNode> describe) {
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.putArray(requestKey).add(physicalId);
+ return !describe.apply(req).path(requestKey).isEmpty();
+ }
+
+ private void provisionComputeEnvironment(StackResource r, JsonNode props, ProvisionContext ctx,
+ Map<String, String> attributesBefore) {
+ String name = stableName(r, ctx, props, "ComputeEnvironmentName");
+ require("AWS::Batch::ComputeEnvironment", "Type", ctx.resolveOptional(props, "Type"));
+
+ String arn;
+ if (reusesPriorEntity(r, ctx, name, "ComputeEnvironmentName")) {
+ // UpdateComputeEnvironment is the schema's update handler and takes only these three;
+ // ComputeEnvironmentName, Type and Tags are createOnly, so a change to those is a
+ // replacement the engine drives, not something to push through here.
+ snapshotBeforeUpdate(r, "AWS::Batch::ComputeEnvironment", ctx.priorPhysicalId(),
+ "computeEnvironments", req -> batchService.describeComputeEnvironments(req),
+ "state", "serviceRole", "computeResources");
+ ObjectNode update = JsonNodeFactory.instance.objectNode();
+ update.put("computeEnvironment", ctx.priorPhysicalId());
+ putResolvedText(update, "state", props, "State", ctx);
+ putResolvedText(update, "serviceRole", props, "ServiceRole", ctx);
+ putResolvedObject(update, "computeResources", props, "ComputeResources", ctx);
+ batchService.updateComputeEnvironment(update);
+ arn = ctx.priorPhysicalId();
+ } else {
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.put("computeEnvironmentName", name);
+ putResolvedText(req, "type", props, "Type", ctx);
+ putResolvedText(req, "state", props, "State", ctx);
+ putResolvedText(req, "serviceRole", props, "ServiceRole", ctx);
+ putResolvedObject(req, "computeResources", props, "ComputeResources", ctx);
+ putTags(req, props, ctx);
+ arn = batchService.createComputeEnvironment(req, ctx.region())
+ .path("computeEnvironmentArn").asText();
+ }
+ r.setPhysicalId(arn);
+ r.getAttributes().put("Arn", arn);
+ r.getAttributes().put("ComputeEnvironmentArn", arn);
+ r.getAttributes().put("ComputeEnvironmentName", name);
+ // An in-place update kept the prior ARN, so this records nothing; a rename minted a new
+ // one, and the environment it displaced is owed a delete once the update commits.
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ }
+
+ private void provisionJobQueue(StackResource r, JsonNode props, ProvisionContext ctx,
+ Map<String, String> attributesBefore) {
+ String name = stableName(r, ctx, props, "JobQueueName");
+ String priority = ctx.resolveOptional(props, "Priority");
+ require("AWS::Batch::JobQueue", "Priority", priority);
+ int priorityValue = requireInt("AWS::Batch::JobQueue", "Priority", priority);
+
+ String arn;
+ if (reusesPriorEntity(r, ctx, name, "JobQueueName")) {
+ // UpdateJobQueue is the schema's update handler; JobQueueName and JobQueueType are
+ // createOnly, so only these three are pushed through.
+ snapshotBeforeUpdate(r, "AWS::Batch::JobQueue", ctx.priorPhysicalId(),
+ "jobQueues", req -> batchService.describeJobQueues(req),
+ "state", "priority", "computeEnvironmentOrder");
+ ObjectNode update = JsonNodeFactory.instance.objectNode();
+ update.put("jobQueue", ctx.priorPhysicalId());
+ putResolvedText(update, "state", props, "State", ctx);
+ update.put("priority", priorityValue);
+ update.set("computeEnvironmentOrder", computeEnvironmentOrder(props, ctx));
+ batchService.updateJobQueue(update);
+ arn = ctx.priorPhysicalId();
+ } else {
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.put("jobQueueName", name);
+ req.put("priority", priorityValue);
+ putResolvedText(req, "state", props, "State", ctx);
+ putResolvedText(req, "jobQueueType", props, "JobQueueType", ctx);
+ req.set("computeEnvironmentOrder", computeEnvironmentOrder(props, ctx));
+ putTags(req, props, ctx);
+ arn = batchService.createJobQueue(req, ctx.region()).path("jobQueueArn").asText();
+ }
+ r.setPhysicalId(arn);
+ r.getAttributes().put("Arn", arn);
+ r.getAttributes().put("JobQueueArn", arn);
+ r.getAttributes().put("JobQueueName", name);
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ }
+
+ private void provisionJobDefinition(StackResource r, JsonNode props, ProvisionContext ctx,
+ Map<String, String> attributesBefore) {
+ // No update branch: RegisterJobDefinition on an existing name records a new revision,
+ // which is how AWS updates a job definition. Only the name has to stay steady.
+ String name = stableName(r, ctx, props, "JobDefinitionName");
+ // Decided before the register call overwrites the recorded name below.
+ boolean sameDefinition = reusesPriorEntity(r, ctx, name, "JobDefinitionName");
+ String type = ctx.resolveOptional(props, "Type");
+ require("AWS::Batch::JobDefinition", "Type", type);
+
+ ObjectNode req = JsonNodeFactory.instance.objectNode();
+ req.put("jobDefinitionName", name);
+ req.put("type", type);
+ putResolvedArray(req, "platformCapabilities", props, "PlatformCapabilities", ctx);
+ if (props != null && props.has("ContainerProperties")) {
+ req.set("containerProperties",
+ containerProperties(ctx.engine().resolveNode(props.get("ContainerProperties"))));
+ }
+ putStringMapFromObject(req, "parameters", props, "Parameters", ctx);
+ if (props != null && props.has("RetryStrategy")) {
+ req.set("retryStrategy", retryStrategy(ctx.engine().resolveNode(props.get("RetryStrategy"))));
+ }
+ if (props != null && props.has("Timeout")) {
+ ObjectNode timeout = JsonNodeFactory.instance.objectNode();
+ JsonNode resolved = ctx.engine().resolveNode(props.get("Timeout"));
+ if (resolved.has("AttemptDurationSeconds")) {
+ timeout.set("attemptDurationSeconds", resolved.get("AttemptDurationSeconds"));
+ }
+ req.set("timeout", timeout);
+ }
+ putTags(req, props, ctx);
+
+ String priorArn = ctx.isUpdate() ? ctx.priorPhysicalId() : null;
+ ObjectNode response = batchService.registerJobDefinition(req, ctx.region());
+ String arn = response.path("jobDefinitionArn").asText();
+ r.setPhysicalId(arn);
+ r.getAttributes().put("Arn", arn);
+ r.getAttributes().put("JobDefinitionArn", arn);
+ r.getAttributes().put("JobDefinitionName", name);
+
+ if (sameDefinition) {
+ // A revision bump is not a replacement. The registry schema's primaryIdentifier for
+ // this type is JobDefinitionName, not the ARN, and the prior revision stays ACTIVE on
+ // AWS: registering revision 2 does not retire revision 1, which a job may still name.
+ // Recording it as displaced would have the cleanup deregister a live revision. Only a
+ // changed name replaces the entity, which is the branch below.
+ //
+ // Rolling one back is still possible, and is the snapshot's job: deregister the
+ // revision this update registered and name the prior one again.
+ ObjectNode snapshot = JsonNodeFactory.instance.objectNode();
+ snapshot.put("type", "AWS::Batch::JobDefinition");
+ snapshot.put("physicalId", priorArn);
+ r.getAttributes().put(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
+ return;
+ }
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ }
+
+ /** The schema's required properties fail the resource with the repo's ValidationError wording. */
+ private static void require(String type, String property, String value) {
+ if (value == null || value.isBlank()) {
+ throw new AwsException("ValidationError", type + " requires " + property, 400);
+ }
+ }
+
+ /**
+ * A template value the schema types as a bounded integer. Template properties arrive as text,
+ * so a non-numeric one reached {@code Integer.parseInt} and left as an uncaught
+ * NumberFormatException, which the stack reported as a 500 rather than the failed validation
+ * it is. The bounds are the registry schema's own: AWS::Batch::JobQueue Priority is
+ * {@code integer, minimum 0, maximum 1000}.
+ */
+ private static int requireInt(String type, String property, String value) {
+ int parsed;
+ try {
+ parsed = Integer.parseInt(value.trim());
+ } catch (NumberFormatException notAnInteger) {
+ throw new AwsException("ValidationError",
+ type + " " + property + " must be an integer, but was '" + value + "'", 400);
+ }
+ if (parsed < PRIORITY_MIN || parsed > PRIORITY_MAX) {
+ throw new AwsException("ValidationError", type + " " + property + " must be between "
+ + PRIORITY_MIN + " and " + PRIORITY_MAX + ", but was " + parsed, 400);
+ }
+ return parsed;
+ }
+
+ /**
+ * The name to use this time round: the template's, else the one this resource already has,
+ * and only failing both a freshly generated one.
+ *
+ * <p>{@code ctx.stablePhysicalName} does not fit these types. It falls back to the prior
+ * physical id, and for Batch that id is an ARN rather than the name, so it would feed an ARN
+ * back in as a name. The prior name comes from the attribute recorded at create time instead,
+ * the way SqsCfnProvisioner reads QueueName beside the queue URL. Without this, an unnamed
+ * resource got a fresh random name on every UpdateStack, creating a second entity and
+ * orphaning the first.
+ */
+ private String stableName(StackResource r, ProvisionContext ctx, JsonNode props, String nameKey) {
+ // For all three types the template property and the recorded attribute share a name.
+ String explicit = ctx.resolveOptional(props, nameKey);
+ if (explicit != null && !explicit.isBlank()) {
+ return explicit;
+ }
+ String prior = priorName(r, ctx, nameKey);
+ if (prior != null && !prior.isBlank()) {
+ return prior;
+ }
+ return ctx.generatePhysicalName(r.getLogicalId(), NAME_MAX_LENGTH, false);
+ }
+
+ /**
+ * Whether {@code name} is the entity this resource already had, so it must be updated rather
+ * than created. {@code ctx.reusesPriorEntity} compares against the physical id, which is the
+ * ARN here, so the comparison is made against the recorded name instead. A replacing update
+ * arrives with a prior id too but has derived a different name, and must still create.
+ */
+ private boolean reusesPriorEntity(StackResource r, ProvisionContext ctx, String name, String attribute) {
+ return ctx.isUpdate() && name.equals(priorName(r, ctx, attribute));
+ }
+
+ /**
+ * The recorded name, falling back to the one embedded in the prior ARN for a resource created
+ * before that attribute was stored. Batch ARNs end in {@code <kind>/<name>}, and the job
+ * definition's also carries {@code :<revision>}.
+ */
+ private String priorName(StackResource r, ProvisionContext ctx, String attribute) {
+ String recorded = r.getAttributes() != null ? r.getAttributes().get(attribute) : null;
+ if (recorded != null && !recorded.isBlank()) {
+ return recorded;
+ }
+ String priorId = ctx.priorPhysicalId();
+ if (priorId == null || !priorId.startsWith("arn:")) {
+ return null;
+ }
+ int slash = priorId.lastIndexOf('/');
+ if (slash < 0 || slash == priorId.length() - 1) {
+ return null;
+ }
+ String tail = priorId.substring(slash + 1);
+ int colon = tail.lastIndexOf(':');
+ return colon > 0 ? tail.substring(0, colon) : tail;
+ }
+
+ private ArrayNode computeEnvironmentOrder(JsonNode props, ProvisionContext ctx) {
+ ArrayNode out = JsonNodeFactory.instance.arrayNode();
+ if (props == null || !props.has("ComputeEnvironmentOrder")) {
+ return out;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props.get("ComputeEnvironmentOrder"));
+ if (!resolved.isArray()) {
+ return out;
+ }
+ for (JsonNode item : resolved) {
+ ObjectNode order = out.addObject();
+ order.put("order", item.path("Order").asInt());
+ order.put("computeEnvironment", item.path("ComputeEnvironment").asText(null));
+ }
+ return out;
+ }
+
+ private ObjectNode containerProperties(JsonNode resolved) {
+ ObjectNode container = JsonNodeFactory.instance.objectNode();
+ if (resolved == null || !resolved.isObject()) {
+ return container;
+ }
+ copyIfPresent(container, "image", resolved, "Image");
+ copyIfPresent(container, "command", resolved, "Command");
+ copyIfPresent(container, "jobRoleArn", resolved, "JobRoleArn");
+ copyIfPresent(container, "executionRoleArn", resolved, "ExecutionRoleArn");
+ copyIfPresent(container, "logConfiguration", resolved, "LogConfiguration");
+ copyIfPresent(container, "networkConfiguration", resolved, "NetworkConfiguration");
+ copyIfPresent(container, "ephemeralStorage", resolved, "EphemeralStorage");
+ if (resolved.has("ResourceRequirements") && resolved.get("ResourceRequirements").isArray()) {
+ ArrayNode resources = container.putArray("resourceRequirements");
+ for (JsonNode item : resolved.get("ResourceRequirements")) {
+ ObjectNode requirement = resources.addObject();
+ requirement.put("type", item.path("Type").asText(null));
+ requirement.put("value", item.path("Value").asText(null));
+ }
+ }
+ if (resolved.has("Environment") && resolved.get("Environment").isArray()) {
+ ArrayNode env = container.putArray("environment");
+ for (JsonNode item : resolved.get("Environment")) {
+ ObjectNode entry = env.addObject();
+ entry.put("name", item.path("Name").asText(null));
+ entry.put("value", item.path("Value").asText(null));
+ }
+ }
+ return container;
+ }
+
+ private ObjectNode retryStrategy(JsonNode resolved) {
+ ObjectNode retry = JsonNodeFactory.instance.objectNode();
+ if (resolved == null || !resolved.isObject()) {
+ return retry;
+ }
+ if (resolved.has("Attempts")) {
+ retry.set("attempts", resolved.get("Attempts"));
+ }
+ if (resolved.has("EvaluateOnExit")) {
+ retry.set("evaluateOnExit", resolved.get("EvaluateOnExit"));
+ }
+ return retry;
+ }
+
+ private void putTags(ObjectNode req, JsonNode props, ProvisionContext ctx) {
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+ if (!tags.isEmpty()) {
+ ObjectNode tagNode = req.putObject("tags");
+ tags.forEach(tagNode::put);
+ }
+ }
+
+ private void putResolvedText(ObjectNode req, String target, JsonNode props, String source,
+ ProvisionContext ctx) {
+ String value = ctx.resolveOptional(props, source);
+ if (value != null) {
+ req.put(target, value);
+ }
+ }
+
+ private void putResolvedObject(ObjectNode req, String target, JsonNode props, String source,
+ ProvisionContext ctx) {
+ if (props == null || !props.has(source) || props.get(source).isNull()) {
+ return;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props.get(source));
+ if (resolved != null && resolved.isObject()) {
+ req.set(target, resolved);
+ }
+ }
+
+ private void putResolvedArray(ObjectNode req, String target, JsonNode props, String source,
+ ProvisionContext ctx) {
+ if (props == null || !props.has(source) || props.get(source).isNull()) {
+ return;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props.get(source));
+ if (resolved != null && resolved.isArray()) {
+ req.set(target, resolved);
+ }
+ }
+
+ private void putStringMapFromObject(ObjectNode req, String target, JsonNode props, String source,
+ ProvisionContext ctx) {
+ if (props == null || !props.has(source) || props.get(source).isNull()) {
+ return;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props.get(source));
+ if (!resolved.isObject()) {
+ return;
+ }
+ ObjectNode out = JsonNodeFactory.instance.objectNode();
+ resolved.fields().forEachRemaining(e -> out.put(e.getKey(), e.getValue().asText()));
+ req.set(target, out);
+ }
+
+ private void copyIfPresent(ObjectNode target, String targetName, JsonNode source, String sourceName) {
+ if (source.has(sourceName) && !source.get(sourceName).isNull()) {
+ target.set(targetName, source.get(sourceName));
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
index 937e7aa7ec..76a1c23dd0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
@@ -53,6 +53,18 @@ public final class CfnRollback {
*/
public static final String RULE_TARGETS_SNAPSHOT_ATTR = "__FlociRuleTargetsSnapshot";
+ /**
+ * Holds the configuration a Batch entity carried before the in-place update in flight changed
+ * it, in the request shape its update call takes, so a failed stack update can put it back.
+ * Written by {@code BatchCfnProvisioner} before its update call and spent by its
+ * {@code rollbackUpdate}. Carries the resource type because one provisioner serves three, and
+ * the rollback hook is handed the stack resource alone: a compute environment is restored
+ * through UpdateComputeEnvironment and a job queue through UpdateJobQueue, and a job
+ * definition instead names the revision the failed update registered so it can be
+ * deregistered.
+ */
+ public static final String BATCH_UPDATE_SNAPSHOT_ATTR = "__FlociBatchUpdateSnapshot";
+
/**
* Holds the settings an event invoke configuration carried before an in-place update changed
* them, in the request shape a put takes, so a failed stack update can put them back. Written
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index b30010461c..90732492d2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.BatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner;
@@ -312,6 +313,9 @@ final class CfnProvisionerFixture {
if (eventBridgeService != null) {
discovered.add(new EventsCfnProvisioner(eventBridgeService));
}
+ if (batchService != null) {
+ discovered.add(new BatchCfnProvisioner(batchService));
+ }
if (wafV2Service != null) {
discovered.add(new WafV2CfnProvisioner(wafV2Service));
}
@@ -618,7 +622,6 @@ final class CfnProvisionerFixture {
customResourceResponseStore,
reachableEndpoint,
stepFunctionsService,
- batchService,
ec2Service,
rdsService,
eksService,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationBatchIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationBatchIntegrationTest.java
index a5e0444d95..65259f3418 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationBatchIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationBatchIntegrationTest.java
@@ -190,6 +190,210 @@ class CloudFormationBatchIntegrationTest {
.body(containsString("CREATE_COMPLETE"));
}
+ /**
+ * The two defects the legacy switch carried, end to end: an update re-created rather than
+ * updating (the second create was rejected as a duplicate name), and a stack delete removed
+ * nothing at all.
+ */
+ @Test
+ void updatingAndDeletingABatchStackUpdatesInPlaceAndRemovesTheResources() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String computeName = "cfn-batch-ud-ce-" + suffix;
+ String queueName = "cfn-batch-ud-queue-" + suffix;
+ String stackName = "cfn-batch-ud-stack-" + suffix;
+
+ String template = """
+ {
+ "Resources": {
+ "Compute": {
+ "Type": "AWS::Batch::ComputeEnvironment",
+ "Properties": {
+ "ComputeEnvironmentName": "%s",
+ "Type": "MANAGED",
+ "ComputeResources": {"Type": "FARGATE", "MaxvCpus": %d}
+ }
+ },
+ "Queue": {
+ "Type": "AWS::Batch::JobQueue",
+ "Properties": {
+ "JobQueueName": "%s",
+ "Priority": %d,
+ "ComputeEnvironmentOrder": [{
+ "Order": 1,
+ "ComputeEnvironment": {"Ref": "Compute"}
+ }]
+ }
+ }
+ },
+ "Outputs": {
+ "ComputeArn": {"Value": {"Fn::GetAtt": ["Compute", "ComputeEnvironmentArn"]}},
+ "QueueArn": {"Value": {"Fn::GetAtt": ["Queue", "JobQueueArn"]}}
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(computeName, 4, queueName, 1))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ // The update changes only updatable properties, so the entities must be mutated, not
+ // replaced: the physical ids the outputs carry have to survive it.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(computeName, 8, queueName, 5))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("UPDATE_COMPLETE"))
+ .body(containsString("compute-environment/" + computeName))
+ .body(containsString("job-queue/" + queueName));
+
+ givenBatchJson("{\"jobQueues\":[\"%s\"]}".formatted(queueName))
+ .when()
+ .post("/v1/describejobqueues")
+ .then()
+ .statusCode(200)
+ .body("jobQueues", hasSize(1))
+ .body("jobQueues[0].priority", equalTo(5));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ // Both entities are gone. Under the legacy switch these describes still returned them.
+ givenBatchJson("{\"jobQueues\":[\"%s\"]}".formatted(queueName))
+ .when()
+ .post("/v1/describejobqueues")
+ .then()
+ .statusCode(200)
+ .body("jobQueues", hasSize(0));
+
+ givenBatchJson("{\"computeEnvironments\":[\"%s\"]}".formatted(computeName))
+ .when()
+ .post("/v1/describecomputeenvironments")
+ .then()
+ .statusCode(200)
+ .body("computeEnvironments", hasSize(0));
+ }
+
+ /**
+ * A failed stack update puts an in-place Batch change back. Without {@code rollbackUpdate} the
+ * queue fell to "Rollback is not implemented for AWS::Batch::JobQueue", which drives the whole
+ * stack to UPDATE_ROLLBACK_FAILED and leaves the queue on the failed update's priority. The
+ * status assertion is the one that proves the hook is reached: the unit tests can show the
+ * provisioner restores, only this shows the engine asks it to.
+ */
+ @Test
+ void aFailedUpdateRollsBackAnInPlaceJobQueueChange() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String computeName = "cfn-batch-rb-ce-" + suffix;
+ String queueName = "cfn-batch-rb-queue-" + suffix;
+ String stackName = "cfn-batch-rb-stack-" + suffix;
+
+ createStack(stackName, queueTemplate(computeName, queueName, 5, false));
+ assertStackStatus(stackName, "CREATE_COMPLETE");
+ assertQueuePriority(queueName, 5);
+
+ // The nested stack has no TemplateURL so it cannot provision, and it depends on the queue,
+ // so the queue's in-place update commits first and the failure lands after it.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", queueTemplate(computeName, queueName, 9, true))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
+ assertQueuePriority(queueName, 5);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void createStack(String stackName, String template) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static String queueTemplate(String computeName, String queueName, int priority,
+ boolean withFailingResource) {
+ return "{\"Resources\":{"
+ + "\"Compute\":{\"Type\":\"AWS::Batch::ComputeEnvironment\",\"Properties\":{"
+ + "\"ComputeEnvironmentName\":\"" + computeName + "\",\"Type\":\"MANAGED\","
+ + "\"ComputeResources\":{\"Type\":\"FARGATE\",\"MaxvCpus\":4,"
+ + "\"Subnets\":[\"subnet-local\"],\"SecurityGroupIds\":[\"sg-local\"]}}},"
+ + "\"Queue\":{\"Type\":\"AWS::Batch::JobQueue\",\"Properties\":{"
+ + "\"JobQueueName\":\"" + queueName + "\",\"Priority\":" + priority + ","
+ + "\"ComputeEnvironmentOrder\":[{\"Order\":1,"
+ + "\"ComputeEnvironment\":{\"Ref\":\"Compute\"}}]}}"
+ + (withFailingResource
+ ? ",\"Nested\":{\"Type\":\"AWS::CloudFormation::Stack\","
+ + "\"DependsOn\":\"Queue\",\"Properties\":{}}"
+ : "")
+ + "}}";
+ }
+
+ private static void assertQueuePriority(String queueName, int priority) {
+ givenBatchJson("{\"jobQueues\":[\"%s\"]}".formatted(queueName))
+ .when()
+ .post("/v1/describejobqueues")
+ .then()
+ .statusCode(200)
+ .body("jobQueues", hasSize(1))
+ .body("jobQueues[0].priority", equalTo(priority));
+ }
+
+ private static void assertStackStatus(String stackName, String status) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackStatus>" + status + "</StackStatus>"));
+ }
+
private static io.restassured.specification.RequestSpecification givenBatchJson(String body) {
return given()
.header("Authorization", BATCH_AUTH)
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisionerTest.java
new file mode 100644
index 0000000000..c33627c31a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BatchCfnProvisionerTest.java
@@ -0,0 +1,683 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.batch.BatchService;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
+
+import java.util.HashMap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** The Batch CFN provisioner in isolation, with only {@link BatchService} mocked. */
+class BatchCfnProvisionerTest {
+
+ private static final String CE_ARN =
+ "arn:aws:batch:us-east-1:000000000000:compute-environment/my-stack-Compute-ab12cd";
+ private static final String JQ_ARN =
+ "arn:aws:batch:us-east-1:000000000000:job-queue/my-stack-Queue-ab12cd";
+ private static final String JD_ARN =
+ "arn:aws:batch:us-east-1:000000000000:job-definition/my-stack-Definition-ab12cd:1";
+
+ private final BatchService batch = mock(BatchService.class);
+ private final BatchCfnProvisioner provisioner = new BatchCfnProvisioner(batch);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ // The engine is a collaborator; these cases use scalar properties and flat objects, so a
+ // pass-through stub keeps this a true isolated unit test.
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
+ }
+
+ private StackResource resource(String type, String logicalId) {
+ StackResource r = new StackResource();
+ r.setResourceType(type);
+ r.setLogicalId(logicalId);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private ObjectNode describeWith(String key, String arn) {
+ ObjectNode out = mapper.createObjectNode();
+ out.putArray(key).addObject().put("arn", arn);
+ return out;
+ }
+
+ private ObjectNode describeEmpty(String key) {
+ ObjectNode out = mapper.createObjectNode();
+ out.putArray(key);
+ return out;
+ }
+
+ // ── create ───────────────────────────────────────────────────────────────
+
+ @Test
+ void computeEnvironmentSetsPhysicalIdAndTheSchemaAttribute() {
+ when(batch.createComputeEnvironment(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN));
+ ObjectNode props = mapper.createObjectNode();
+ props.put("ComputeEnvironmentName", "envy");
+ props.put("Type", "MANAGED");
+
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).createComputeEnvironment(req.capture(), anyString());
+ assertEquals("envy", req.getValue().path("computeEnvironmentName").asText());
+ assertEquals("MANAGED", req.getValue().path("type").asText());
+ // Ref resolves to the physical id, and ComputeEnvironmentArn is the type's only
+ // top-level read-only property in the registry schema.
+ assertEquals(CE_ARN, r.getPhysicalId());
+ assertEquals(CE_ARN, r.getAttributes().get("ComputeEnvironmentArn"));
+ assertEquals("envy", r.getAttributes().get("ComputeEnvironmentName"));
+ }
+
+ @Test
+ void jobQueueCarriesPriorityAndComputeEnvironmentOrder() {
+ when(batch.createJobQueue(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("jobQueueArn", JQ_ARN));
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "7");
+ props.putArray("ComputeEnvironmentOrder").addObject()
+ .put("Order", 1).put("ComputeEnvironment", CE_ARN);
+
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).createJobQueue(req.capture(), anyString());
+ assertEquals(7, req.getValue().path("priority").asInt());
+ assertEquals(CE_ARN,
+ req.getValue().path("computeEnvironmentOrder").get(0).path("computeEnvironment").asText());
+ assertEquals(JQ_ARN, r.getAttributes().get("JobQueueArn"));
+ }
+
+ @Test
+ void jobDefinitionDefaultsTypeToContainer() {
+ when(batch.registerJobDefinition(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN).put("revision", 1));
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobDefinitionName", "def");
+ props.put("Type", "container");
+ props.putObject("ContainerProperties").put("Image", "busybox");
+
+ StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).registerJobDefinition(req.capture(), anyString());
+ assertEquals("container", req.getValue().path("type").asText());
+ assertEquals("busybox", req.getValue().path("containerProperties").path("image").asText());
+ assertEquals(JD_ARN, r.getAttributes().get("JobDefinitionArn"));
+ }
+
+ // ── update ───────────────────────────────────────────────────────────────
+
+ private ProvisionContext updateCtx(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ @Test
+ void updatingAComputeEnvironmentUpdatesInPlaceInsteadOfCreatingAgain() {
+ // createComputeEnvironment rejects a duplicate name, so the second UpdateStack used to
+ // fail the whole stack rather than update the environment.
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ r.getAttributes().put("ComputeEnvironmentName", "envy");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("ComputeEnvironmentName", "envy");
+ props.put("Type", "MANAGED");
+ props.put("State", "DISABLED");
+
+ provisioner.provision(r, props, updateCtx(CE_ARN));
+
+ ArgumentCaptor<JsonNode> update = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).updateComputeEnvironment(update.capture());
+ verify(batch, never()).createComputeEnvironment(any(), anyString());
+ assertEquals(CE_ARN, update.getValue().path("computeEnvironment").asText());
+ assertEquals("DISABLED", update.getValue().path("state").asText());
+ assertEquals(CE_ARN, r.getPhysicalId(), "an in-place update keeps the physical id");
+ }
+
+ @Test
+ void updatingAJobQueueUpdatesInPlace() {
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ r.getAttributes().put("JobQueueName", "queue");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "9");
+
+ provisioner.provision(r, props, updateCtx(JQ_ARN));
+
+ ArgumentCaptor<JsonNode> update = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).updateJobQueue(update.capture());
+ verify(batch, never()).createJobQueue(any(), anyString());
+ assertEquals(9, update.getValue().path("priority").asInt());
+ assertEquals(JQ_ARN, r.getPhysicalId());
+ }
+
+ @Test
+ void renamingAComputeEnvironmentCreatesRatherThanUpdates() {
+ // The name is createOnly, so a changed name is a replacing update: it still arrives with a
+ // prior physical id, but must create a new entity rather than mutate one that has that name.
+ when(batch.createComputeEnvironment(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN + "-new"));
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ r.getAttributes().put("ComputeEnvironmentName", "envy");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("ComputeEnvironmentName", "renamed");
+ props.put("Type", "MANAGED");
+
+ provisioner.provision(r, props, updateCtx(CE_ARN));
+
+ verify(batch).createComputeEnvironment(any(), anyString());
+ verify(batch, never()).updateComputeEnvironment(any());
+ assertEquals(CE_ARN + "-new", r.getPhysicalId());
+ }
+
+ @Test
+ void anUnnamedComputeEnvironmentKeepsItsGeneratedNameAcrossUpdates() {
+ // The defect this guards: generating unconditionally gave an unnamed resource a fresh
+ // random name on every update, creating a second environment and orphaning the first.
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ r.getAttributes().put("ComputeEnvironmentName", "my-stack-Compute-ab12cd");
+
+ provisioner.provision(r, mapper.createObjectNode().put("Type", "MANAGED"), updateCtx(CE_ARN));
+
+ verify(batch).updateComputeEnvironment(any());
+ verify(batch, never()).createComputeEnvironment(any(), anyString());
+ }
+
+ @Test
+ void anUnnamedResourceRecoversItsNameFromThePriorArn() {
+ // Stacks provisioned before the name attribute was recorded still have to update in place
+ // rather than create a duplicate.
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+
+ provisioner.provision(r, mapper.createObjectNode().put("Priority", "1"), updateCtx(JQ_ARN));
+
+ verify(batch).updateJobQueue(any());
+ verify(batch, never()).createJobQueue(any(), anyString());
+ }
+
+ @Test
+ void updatingAJobDefinitionRegistersANewRevisionUnderTheSameName() {
+ // AWS updates a job definition by recording a new revision, which is what
+ // registerJobDefinition already does, so there is no separate update call.
+ when(batch.registerJobDefinition(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN).put("revision", 2));
+ StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
+ r.getAttributes().put("JobDefinitionName", "def");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Type", "container");
+ props.putObject("ContainerProperties").put("Image", "busybox");
+
+ provisioner.provision(r, props, updateCtx(JD_ARN));
+
+ ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).registerJobDefinition(req.capture(), anyString());
+ assertEquals("def", req.getValue().path("jobDefinitionName").asText());
+ }
+
+ // ── required properties ──────────────────────────────────────────────────
+
+ @Test
+ void aJobQueueWithoutPriorityIsRejected() {
+ // Priority is the schema's only required property for this type. The switch substituted 1,
+ // so a template missing it applied cleanly here and failed on AWS.
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource("AWS::Batch::JobQueue", "Queue"), props, ctx()));
+
+ assertEquals("ValidationError", thrown.getErrorCode());
+ assertTrue(thrown.getMessage().contains("Priority"));
+ verify(batch, never()).createJobQueue(any(), anyString());
+ }
+
+ @Test
+ void aComputeEnvironmentWithoutTypeIsRejected() {
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource("AWS::Batch::ComputeEnvironment", "Compute"),
+ mapper.createObjectNode().put("ComputeEnvironmentName", "envy"), ctx()));
+
+ assertEquals("ValidationError", thrown.getErrorCode());
+ assertTrue(thrown.getMessage().contains("Type"));
+ }
+
+ @Test
+ void aJobDefinitionWithoutTypeIsRejected() {
+ // The switch defaulted this to "container"; the schema makes it required.
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource("AWS::Batch::JobDefinition", "Definition"),
+ mapper.createObjectNode().put("JobDefinitionName", "def"), ctx()));
+
+ assertEquals("ValidationError", thrown.getErrorCode());
+ assertTrue(thrown.getMessage().contains("Type"));
+ }
+
+ @Test
+ void aJobDefinitionDoesNotAdvertiseARevisionAttribute() {
+ // Revision is not a property of AWS::Batch::JobDefinition in the registry schema and the
+ // legacy spec gives the type no attributes either, so Fn::GetAtt on it fails on AWS.
+ // Offering it here would let a template pass on floci and break on AWS.
+ when(batch.registerJobDefinition(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN).put("revision", 1));
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobDefinitionName", "def");
+ props.put("Type", "container");
+ props.putObject("ContainerProperties").put("Image", "busybox");
+
+ StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
+ provisioner.provision(r, props, ctx());
+
+ assertFalse(r.getAttributes().containsKey("Revision"));
+ assertEquals(JD_ARN, r.getAttributes().get("JobDefinitionArn"));
+ }
+
+ // ── delete ───────────────────────────────────────────────────────────────
+
+ @Test
+ void deletingAJobQueueDisablesItFirst() {
+ // DeleteJobQueue refuses an ENABLED queue, as on AWS, so the disable has to come first
+ // and in this order.
+ when(batch.describeJobQueues(any())).thenReturn(describeWith("jobQueues", JQ_ARN));
+
+ provisioner.delete("AWS::Batch::JobQueue", JQ_ARN, "us-east-1");
+
+ InOrder order = inOrder(batch);
+ ArgumentCaptor<JsonNode> disable = ArgumentCaptor.forClass(JsonNode.class);
+ order.verify(batch).updateJobQueue(disable.capture());
+ order.verify(batch).deleteJobQueue(any());
+ assertEquals("DISABLED", disable.getValue().path("state").asText());
+ assertEquals(JQ_ARN, disable.getValue().path("jobQueue").asText());
+ }
+
+ @Test
+ void deletingAComputeEnvironmentDisablesItFirst() {
+ when(batch.describeComputeEnvironments(any()))
+ .thenReturn(describeWith("computeEnvironments", CE_ARN));
+
+ provisioner.delete("AWS::Batch::ComputeEnvironment", CE_ARN, "us-east-1");
+
+ InOrder order = inOrder(batch);
+ ArgumentCaptor<JsonNode> disable = ArgumentCaptor.forClass(JsonNode.class);
+ order.verify(batch).updateComputeEnvironment(disable.capture());
+ order.verify(batch).deleteComputeEnvironment(any());
+ assertEquals("DISABLED", disable.getValue().path("state").asText());
+ }
+
+ @Test
+ void deletingAJobDefinitionDeregistersIt() {
+ when(batch.describeJobDefinitions(any())).thenReturn(describeWith("jobDefinitions", JD_ARN));
+
+ provisioner.delete("AWS::Batch::JobDefinition", JD_ARN, "us-east-1");
+
+ ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).deregisterJobDefinition(req.capture());
+ assertEquals(JD_ARN, req.getValue().path("jobDefinition").asText());
+ }
+
+ @Test
+ void deletingAnEntityThatIsAlreadyGoneDoesNothing() {
+ // A repeated stack delete must be idempotent. It matters most for the job definition:
+ // deregister throws when the definition is missing, so the existence check is the guard.
+ when(batch.describeComputeEnvironments(any())).thenReturn(describeEmpty("computeEnvironments"));
+ when(batch.describeJobQueues(any())).thenReturn(describeEmpty("jobQueues"));
+ when(batch.describeJobDefinitions(any())).thenReturn(describeEmpty("jobDefinitions"));
+
+ provisioner.delete("AWS::Batch::ComputeEnvironment", CE_ARN, "us-east-1");
+ provisioner.delete("AWS::Batch::JobQueue", JQ_ARN, "us-east-1");
+ provisioner.delete("AWS::Batch::JobDefinition", JD_ARN, "us-east-1");
+
+ verify(batch, never()).updateComputeEnvironment(any());
+ verify(batch, never()).deleteComputeEnvironment(any());
+ verify(batch, never()).updateJobQueue(any());
+ verify(batch, never()).deleteJobQueue(any());
+ verify(batch, never()).deregisterJobDefinition(any());
+ }
+
+ @Test
+ void aRefusedDeletePropagatesInsteadOfBeingSwallowed() {
+ // The failure that must not be tolerated: a compute environment still attached to a queue.
+ // Swallowing it would report a green stack delete over a resource that is still there.
+ when(batch.describeComputeEnvironments(any()))
+ .thenReturn(describeWith("computeEnvironments", CE_ARN));
+ when(batch.deleteComputeEnvironment(any())).thenThrow(new AwsException("ClientException",
+ "Cannot delete compute environment still associated with a job queue: envy", 400));
+
+ AwsException thrown = assertThrows(AwsException.class,
+ () -> provisioner.delete("AWS::Batch::ComputeEnvironment", CE_ARN, "us-east-1"));
+ assertTrue(thrown.getMessage().contains("still associated with a job queue"));
+ }
+
+ @Test
+ void deleteWithoutAPhysicalIdTouchesNothing() {
+ provisioner.delete("AWS::Batch::JobQueue", null, "us-east-1");
+ provisioner.delete("AWS::Batch::JobQueue", "", "us-east-1");
+
+ verify(batch, never()).describeJobQueues(any());
+ verify(batch, never()).deleteJobQueue(any());
+ }
+
+ // ── replacement cleanup ──────────────────────────────────────────────────
+
+ private ObjectNode detail(String key, String arn, java.util.Map<String, Object> fields) {
+ ObjectNode out = mapper.createObjectNode();
+ ObjectNode item = out.putArray(key).addObject();
+ item.put("arn", arn);
+ fields.forEach((k, v) -> {
+ if (v instanceof Integer i) {
+ item.put(k, i);
+ } else {
+ item.put(k, String.valueOf(v));
+ }
+ });
+ return out;
+ }
+
+ @Test
+ void renamingAComputeEnvironmentRecordsTheDisplacedOneForCleanup() {
+ // The leak this closes: the rename created the replacement, but the engine was never told
+ // a replacement happened, so the old environment stayed live in Batch forever.
+ when(batch.createComputeEnvironment(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN + "-new"));
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ r.getAttributes().put("ComputeEnvironmentName", "envy");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("ComputeEnvironmentName", "renamed");
+ props.put("Type", "MANAGED");
+
+ provisioner.provision(r, props, updateCtx(CE_ARN));
+
+ assertTrue(provisioner.hasReplacementUpdate(r), "the engine has to learn a replacement happened");
+ assertEquals(CE_ARN, provisioner.updateCleanupPhysicalId(r), "the displaced environment is owed a delete");
+ }
+
+ @Test
+ void completingTheUpdateDeletesTheDisplacedComputeEnvironment() {
+ when(batch.createComputeEnvironment(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN + "-new"));
+ when(batch.describeComputeEnvironments(any()))
+ .thenReturn(describeWith("computeEnvironments", CE_ARN));
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ r.getAttributes().put("ComputeEnvironmentName", "envy");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("ComputeEnvironmentName", "renamed");
+ props.put("Type", "MANAGED");
+ provisioner.provision(r, props, updateCtx(CE_ARN));
+
+ UpdateCleanupResult result = provisioner.completeUpdate(r);
+
+ assertTrue(result.applicable());
+ assertTrue(result.complete(), "the displaced environment was deleted");
+ ArgumentCaptor<JsonNode> deleted = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).deleteComputeEnvironment(deleted.capture());
+ assertEquals(CE_ARN, deleted.getValue().path("computeEnvironment").asText());
+ }
+
+ @Test
+ void anInPlaceUpdateOwesNoReplacementCleanup() {
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ r.getAttributes().put("JobQueueName", "queue");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "9");
+
+ provisioner.provision(r, props, updateCtx(JQ_ARN));
+
+ assertFalse(provisioner.hasReplacementUpdate(r), "nothing was displaced");
+ }
+
+ @Test
+ void aJobDefinitionRevisionBumpIsNotAReplacement() {
+ // The prior revision stays ACTIVE on AWS, and the schema's primaryIdentifier for this type
+ // is JobDefinitionName rather than the ARN. Recording the bump as a replacement would have
+ // the cleanup deregister a revision a running job may still name.
+ when(batch.registerJobDefinition(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN + "-r2"));
+ StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
+ r.getAttributes().put("JobDefinitionName", "my-stack-Definition-ab12cd");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobDefinitionName", "my-stack-Definition-ab12cd");
+ props.put("Type", "container");
+
+ provisioner.provision(r, props, updateCtx(JD_ARN));
+
+ assertFalse(provisioner.hasReplacementUpdate(r),
+ "a new revision under the same name replaces nothing");
+ }
+
+ @Test
+ void renamingAJobDefinitionIsAReplacement() {
+ when(batch.registerJobDefinition(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN + "-renamed"));
+ StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
+ r.getAttributes().put("JobDefinitionName", "my-stack-Definition-ab12cd");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobDefinitionName", "renamed");
+ props.put("Type", "container");
+
+ provisioner.provision(r, props, updateCtx(JD_ARN));
+
+ assertTrue(provisioner.hasReplacementUpdate(r), "a changed name replaces the definition");
+ assertEquals(JD_ARN, provisioner.updateCleanupPhysicalId(r));
+ }
+
+ // ── update rollback ──────────────────────────────────────────────────────
+
+ @Test
+ void rollingBackAnInPlaceComputeEnvironmentUpdateRestoresWhatItFound() {
+ // Without this the resource fell to "Rollback is not implemented", which drives the whole
+ // stack to UPDATE_ROLLBACK_FAILED and leaves the environment on the failed update's values.
+ when(batch.describeComputeEnvironments(any())).thenReturn(
+ detail("computeEnvironments", CE_ARN,
+ java.util.Map.of("state", "ENABLED", "serviceRole", "role-before")));
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ r.getAttributes().put("ComputeEnvironmentName", "envy");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("ComputeEnvironmentName", "envy");
+ props.put("Type", "MANAGED");
+ props.put("State", "DISABLED");
+ props.put("ServiceRole", "role-after");
+ provisioner.provision(r, props, updateCtx(CE_ARN));
+
+ assertTrue(provisioner.rollbackUpdate(r), "an in-place update is restorable from the snapshot");
+
+ ArgumentCaptor<JsonNode> calls = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch, org.mockito.Mockito.times(2)).updateComputeEnvironment(calls.capture());
+ JsonNode restore = calls.getAllValues().get(1);
+ assertEquals(CE_ARN, restore.path("computeEnvironment").asText());
+ assertEquals("ENABLED", restore.path("state").asText(), "the state it was found with");
+ assertEquals("role-before", restore.path("serviceRole").asText());
+ }
+
+ /**
+ * Pins a known limitation rather than a fix, the way
+ * {@code CognitoCfnProvisionerTest.anInPlaceUserPoolClientUpdateCannotBeRolledBack} pins
+ * Cognito's. The snapshot records what the describe returned, so a field that was absent
+ * before the update is absent from the snapshot and omitted from the restore call, and
+ * UpdateComputeEnvironment leaves an omitted field alone. The value the failed update added
+ * therefore survives.
+ *
+ * <p>Asserting the survivor explicitly, rather than just that the rollback returned true, is
+ * what makes this test useful: it goes red if the merge semantics ever change without the
+ * disclosure on {@code rollbackUpdate} changing with them.
+ */
+ @Test
+ void aRollbackCannotRemoveAValueTheFailedUpdateAdded() {
+ // No serviceRole before the update: the environment simply does not carry one.
+ when(batch.describeComputeEnvironments(any())).thenReturn(
+ detail("computeEnvironments", CE_ARN, java.util.Map.of("state", "ENABLED")));
+ StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
+ r.getAttributes().put("ComputeEnvironmentName", "envy");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("ComputeEnvironmentName", "envy");
+ props.put("Type", "MANAGED");
+ props.put("State", "DISABLED");
+ props.put("ServiceRole", "role-the-update-added");
+ provisioner.provision(r, props, updateCtx(CE_ARN));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ ArgumentCaptor<JsonNode> calls = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch, org.mockito.Mockito.times(2)).updateComputeEnvironment(calls.capture());
+ JsonNode failedUpdate = calls.getAllValues().get(0);
+ JsonNode restore = calls.getAllValues().get(1);
+
+ assertEquals("role-the-update-added", failedUpdate.path("serviceRole").asText(),
+ "the failed update did set a serviceRole");
+ assertEquals("ENABLED", restore.path("state").asText(),
+ "a value the environment already carried is restored exactly");
+ assertFalse(restore.has("serviceRole"),
+ "the restore cannot ask for a serviceRole it never saw, so the added one survives");
+ }
+
+ @Test
+ void rollingBackAnInPlaceJobQueueUpdateRestoresPriorityAndState() {
+ when(batch.describeJobQueues(any())).thenReturn(
+ detail("jobQueues", JQ_ARN, java.util.Map.of("state", "ENABLED", "priority", 3)));
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ r.getAttributes().put("JobQueueName", "queue");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "9");
+ props.put("State", "DISABLED");
+ provisioner.provision(r, props, updateCtx(JQ_ARN));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ ArgumentCaptor<JsonNode> calls = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch, org.mockito.Mockito.times(2)).updateJobQueue(calls.capture());
+ JsonNode restore = calls.getAllValues().get(1);
+ assertEquals(3, restore.path("priority").asInt(), "the priority it was found with");
+ assertEquals("ENABLED", restore.path("state").asText());
+ }
+
+ @Test
+ void rollingBackAJobDefinitionRevisionDeregistersTheOneTheUpdateRegistered() {
+ when(batch.registerJobDefinition(any(), anyString()))
+ .thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN + "-r2"));
+ when(batch.describeJobDefinitions(any()))
+ .thenReturn(describeWith("jobDefinitions", JD_ARN + "-r2"));
+ StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
+ r.getAttributes().put("JobDefinitionName", "my-stack-Definition-ab12cd");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobDefinitionName", "my-stack-Definition-ab12cd");
+ props.put("Type", "container");
+ provisioner.provision(r, props, updateCtx(JD_ARN));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ ArgumentCaptor<JsonNode> deregistered = ArgumentCaptor.forClass(JsonNode.class);
+ verify(batch).deregisterJobDefinition(deregistered.capture());
+ assertEquals(JD_ARN + "-r2", deregistered.getValue().path("jobDefinition").asText(),
+ "the revision the failed update registered, not the one it started from");
+ assertEquals(JD_ARN, r.getPhysicalId(), "the resource names the prior revision again");
+ }
+
+ @Test
+ void aResourceThisUpdateNeverTouchedReportsItCannotBeRolledBack() {
+ // Answering true here would claim a restore that never happened. False is the honest
+ // answer and is what makes the engine report the resource accurately.
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+
+ assertFalse(provisioner.rollbackUpdate(r));
+ }
+
+ @Test
+ void clearingTheUpdateDropsTheSnapshot() {
+ when(batch.describeJobQueues(any())).thenReturn(
+ detail("jobQueues", JQ_ARN, java.util.Map.of("state", "ENABLED", "priority", 3)));
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ r.getAttributes().put("JobQueueName", "queue");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "9");
+ provisioner.provision(r, props, updateCtx(JQ_ARN));
+
+ provisioner.clearUpdate(r);
+
+ assertFalse(r.getAttributes().containsKey(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR));
+ assertFalse(provisioner.rollbackUpdate(r), "a spent snapshot cannot be replayed");
+ }
+
+ // ── Priority validation ──────────────────────────────────────────────────
+
+ @Test
+ void aNonNumericPriorityFailsValidationInsteadOfThrowingNumberFormatException() {
+ // It used to reach Integer.parseInt unguarded and escape as a 500 rather than the failed
+ // validation it is.
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "high");
+
+ AwsException thrown = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, props, ctx()));
+
+ assertEquals("ValidationError", thrown.getErrorCode());
+ assertEquals(400, thrown.getHttpStatus());
+ assertTrue(thrown.getMessage().contains("must be an integer"));
+ verify(batch, never()).createJobQueue(any(), anyString());
+ }
+
+ @Test
+ void anOutOfRangePriorityFailsValidation() {
+ // The registry schema types Priority as integer, minimum 0, maximum 1000.
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "1001");
+
+ AwsException thrown = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, props, ctx()));
+
+ assertEquals("ValidationError", thrown.getErrorCode());
+ assertTrue(thrown.getMessage().contains("between 0 and 1000"));
+ verify(batch, never()).createJobQueue(any(), anyString());
+ }
+
+ @Test
+ void aNonNumericPriorityIsRejectedOnTheUpdatePathToo() {
+ StackResource r = resource("AWS::Batch::JobQueue", "Queue");
+ r.getAttributes().put("JobQueueName", "queue");
+ ObjectNode props = mapper.createObjectNode();
+ props.put("JobQueueName", "queue");
+ props.put("Priority", "high");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props, updateCtx(JQ_ARN)));
+
+ verify(batch, never()).updateJobQueue(any());
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 466accd0c3..bae1f45baf 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -21,9 +21,9 @@ AWS::AutoScaling::LaunchConfiguration LEGACY_SWITCH
AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner
AWS::AutoScaling::ScalingPolicy AutoScalingScalingPolicyCfnProvisioner
AWS::Backup::BackupVault BackupVaultCfnProvisioner
-AWS::Batch::ComputeEnvironment LEGACY_SWITCH
-AWS::Batch::JobDefinition LEGACY_SWITCH
-AWS::Batch::JobQueue LEGACY_SWITCH
+AWS::Batch::ComputeEnvironment BatchCfnProvisioner
+AWS::Batch::JobDefinition BatchCfnProvisioner
+AWS::Batch::JobQueue BatchCfnProvisioner
AWS::CDK::Metadata CdkMetadataCfnProvisioner
AWS::CertificateManager::Certificate AcmCfnProvisioner
AWS::CloudFormation::CustomResource LEGACY_SWITCH