mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): keep generated names across updates for Scheduler, SQS and MicrovmImage (#2985)
provision runs again on every UpdateStack. #2788 gave seven provisioners ProvisionContext.stablePhysicalName so an unnamed resource keeps the name it already had instead of creating a second one and orphaning the first, and left AWS::SQS::Queue and AWS::Lambda::MicrovmImage for a follow-up. The Scheduler ScheduleGroup provisioner solved the same problem by reading the id off the resource, the pattern AGENTS.md step 4 now documents as an anti-pattern because provision assigns the new id as it works. All three names are createOnly in their registry schemas. Scheduler: stablePhysicalName plus reusesPriorEntity in place of the ConflictException catch; the tag diff goes through ProvisionContext.staleTagKeys. One behaviour change: the old path called createScheduleGroup and adopted only on ConflictException, so a group deleted outside the stack was silently recreated; the new path reads the group first and surfaces ResourceNotFoundException, which is what CloudFormation does. SQS: the physical id is the queue URL, so the prior name is read from the QueueName attribute the way SnsCfnProvisioner reads the topic name beside its ARN, and only when its .fifo suffix still matches FifoQueue, which is createOnly too. On reuse the update goes through SetQueueAttributes, the schema's update handler, because createQueue on an existing name answers QueueAlreadyExists the moment an attribute differs; that also fixes an explicitly named queue whose VisibilityTimeout changed. An explicitly named queue whose FifoQueue changes fails with ValidationError instead of reconciling around it: the schema's own QueueName text says a named queue cannot take an update that requires replacement, and that is the refusal the other provisioners use for a createOnly change under a kept name. AWS::SQS::QueuePolicy keeps its id across updates, the same two-line fix S3::BucketPolicy got. MicrovmImage: stablePhysicalName, and on reuse updateImage (the schema's UpdateMicrovmImage handler) rather than createImage, which would mint a new version on every update. CfnStableNameUpdatePathTest gains one case per type pinning exactly one create across create plus update; the SQS integration test drives an unnamed queue through UpdateStack with a changed VisibilityTimeout against the real service. Left for follow-ups: SQS Tags, the NetworkConnector name, resetting an attribute the template dropped, and recreating a resource deleted out of band the way EcsCapacityCfnProvisioner does, if that leniency is wanted.
This commit is contained in:
1 parent
96d16de998
commit
9162b990ec
9 files changed
+562
-82
No files matched your search
+15
-12
@@ -56,22 +56,25 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
private void provisionImage(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String name = ctx.resolveOptional(props, "Name");
|
||||
if (name == null || name.isBlank()) {
|
||||
name = ctx.generatePhysicalName(r.getLogicalId(), 64, false);
|
||||
}
|
||||
// Name is a createOnlyProperty and the physical id, so an unnamed image keeps the name it
|
||||
// already had across updates instead of a fresh one each time provision runs.
|
||||
String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false);
|
||||
String codeArtifactUri = null;
|
||||
if (props != null && props.has("CodeArtifact") && props.get("CodeArtifact").has("Uri")) {
|
||||
codeArtifactUri = ctx.engine().resolve(props.get("CodeArtifact").get("Uri"));
|
||||
}
|
||||
LambdaMicrovmsService.MicrovmImage image = microvmsService.createImage(
|
||||
ctx.region(),
|
||||
ctx.accountId(),
|
||||
name,
|
||||
ctx.resolveOptional(props, "BaseImageArn"),
|
||||
ctx.resolveOptional(props, "BuildRoleArn"),
|
||||
codeArtifactUri,
|
||||
ctx.resolveOptional(props, "Description"));
|
||||
String baseImageArn = ctx.resolveOptional(props, "BaseImageArn");
|
||||
String buildRoleArn = ctx.resolveOptional(props, "BuildRoleArn");
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
// provision is also the update path. With the name stable, the second UpdateStack reaches
|
||||
// the service with an image that exists; the registry schema's update handler is
|
||||
// UpdateMicrovmImage, so reconcile through updateImage rather than mint a version through
|
||||
// createImage. A replacing update derives a different name and still creates.
|
||||
LambdaMicrovmsService.MicrovmImage image = ctx.reusesPriorEntity(name)
|
||||
? microvmsService.updateImage(ctx.region(), name, baseImageArn, buildRoleArn,
|
||||
codeArtifactUri, description)
|
||||
: microvmsService.createImage(ctx.region(), ctx.accountId(), name, baseImageArn,
|
||||
buildRoleArn, codeArtifactUri, description);
|
||||
r.setPhysicalId(image.name);
|
||||
r.getAttributes().put("ImageArn", image.imageArn);
|
||||
r.getAttributes().put("Arn", image.imageArn);
|
||||
|
||||
+25
-35
@@ -9,9 +9,8 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -39,22 +38,18 @@ public class SchedulerScheduleGroupCfnProvisioner implements CfnResourceProvisio
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String name = ctx.resolveOptional(props, "Name");
|
||||
if (name == null || name.isBlank()) {
|
||||
// No explicit name and this resource already has a physical id: keep it across updates
|
||||
// instead of generating a fresh random one each retry, same as LogGroup/Queue do.
|
||||
name = r.getPhysicalId() != null
|
||||
? r.getPhysicalId()
|
||||
: ctx.generatePhysicalName(r.getLogicalId(), 64, false);
|
||||
}
|
||||
// Name is a createOnlyProperty in the registry schema, so an unnamed group keeps the name
|
||||
// it already had across updates instead of getting a fresh random one each time provision
|
||||
// runs. Read from the context, not the resource: provision assigns the new id as it works.
|
||||
String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false);
|
||||
// Tags wrapped in an intrinsic (e.g. Fn::If choosing between two tag lists) is not resolved
|
||||
// here: the engine's Fn::If support is scalar-only, so a conditional list would collapse to
|
||||
// a string rather than the chosen array. tagsAreResolvable is true both when Tags is absent
|
||||
// (the template genuinely wants no tags) and when it is a plain array (the template's actual
|
||||
// desired tags), and false only when Tags is present but not a plain array - the one case
|
||||
// where the desired state genuinely cannot be read, so the retry path below must not treat
|
||||
// "couldn't resolve the intended tags" as "the intended tags are empty" and delete everything
|
||||
// live.
|
||||
// here: the engine collapses a list-valued intrinsic to a string (#2983), so a conditional
|
||||
// list would not arrive as the chosen array. tagsAreResolvable is true both when Tags is
|
||||
// absent (the template genuinely wants no tags) and when it is a plain array (the template's
|
||||
// actual desired tags), and false only when Tags is present but not a plain array, the one
|
||||
// case where the desired state genuinely cannot be read, so the reconcile path below must
|
||||
// not treat "couldn't resolve the intended tags" as "the intended tags are empty" and delete
|
||||
// everything live.
|
||||
boolean hasTagsProperty = props != null && props.has("Tags");
|
||||
boolean tagsAreResolvable = !hasTagsProperty || props.get("Tags").isArray();
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
@@ -68,32 +63,27 @@ public class SchedulerScheduleGroupCfnProvisioner implements CfnResourceProvisio
|
||||
}
|
||||
|
||||
ScheduleGroup group;
|
||||
try {
|
||||
group = schedulerService.createScheduleGroup(name, tags, ctx.region());
|
||||
} catch (AwsException e) {
|
||||
if (!"ConflictException".equals(e.getErrorCode()) || !name.equals(r.getPhysicalId())) {
|
||||
throw e;
|
||||
}
|
||||
// Same-stack create-retry: CloudFormation only retries a resource under the physical id
|
||||
// it previously assigned, so a conflict on that exact name means this logical resource's
|
||||
// own group already exists from an earlier attempt. Adopt it instead of failing the whole
|
||||
// stack on a retry of a step that already succeeded.
|
||||
if (ctx.reusesPriorEntity(name)) {
|
||||
// provision is also the update path, and createScheduleGroup answers ConflictException
|
||||
// for a name that exists. The derived name matching the prior physical id means this
|
||||
// logical resource's own group is already there, so reconcile it rather than create:
|
||||
// per the registry schema the update handler is a tag diff and nothing else. A key
|
||||
// dropped from the template (or the whole Tags list emptied, or Tags removed entirely)
|
||||
// must not linger on the live resource. Skipped only when Tags is present but
|
||||
// unresolvable, where untagging every live key would erase tags for a reason unrelated
|
||||
// to what the template asked for.
|
||||
group = schedulerService.getScheduleGroup(name, ctx.region());
|
||||
// Reconcile tags both ways: a key dropped from the template (or the whole Tags list
|
||||
// emptied, or Tags removed entirely) must not linger on the live resource, matching how
|
||||
// the same-stack retry path applies every other property change rather than only ever
|
||||
// adding. Skipped only when Tags is present but unresolvable (Fn::If) - untagging every
|
||||
// live key there would erase tags for a reason unrelated to what the template asked for.
|
||||
if (tagsAreResolvable) {
|
||||
Set<String> staleKeys = new HashSet<>(group.getTags().keySet());
|
||||
staleKeys.removeAll(tags.keySet());
|
||||
List<String> staleKeys = ProvisionContext.staleTagKeys(group.getTags(), tags);
|
||||
if (!staleKeys.isEmpty()) {
|
||||
schedulerService.untagScheduleGroup(name, ctx.region(), new ArrayList<>(staleKeys));
|
||||
schedulerService.untagScheduleGroup(name, ctx.region(), staleKeys);
|
||||
}
|
||||
}
|
||||
if (!tags.isEmpty()) {
|
||||
schedulerService.tagScheduleGroup(name, ctx.region(), tags);
|
||||
}
|
||||
} else {
|
||||
group = schedulerService.createScheduleGroup(name, tags, ctx.region());
|
||||
}
|
||||
r.setPhysicalId(group.getName());
|
||||
r.getAttributes().put("Arn", group.getArn());
|
||||
|
||||
+49
-11
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Queue;
|
||||
@@ -36,7 +37,7 @@ public class SqsCfnProvisioner implements CfnResourceProvisioner {
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
switch (r.getResourceType()) {
|
||||
case "AWS::SQS::Queue" -> provisionQueue(r, props, ctx);
|
||||
case "AWS::SQS::QueuePolicy" -> provisionQueuePolicy(r);
|
||||
case "AWS::SQS::QueuePolicy" -> provisionQueuePolicy(r, ctx);
|
||||
default -> throw new IllegalStateException("SqsCfnProvisioner cannot handle " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
@@ -55,12 +56,23 @@ public class SqsCfnProvisioner implements CfnResourceProvisioner {
|
||||
: null;
|
||||
boolean fifo = "true".equalsIgnoreCase(fifoFlag);
|
||||
String queueName = ctx.resolveOptional(props, "QueueName");
|
||||
// The physical id is the queue URL, so ctx.stablePhysicalName does not fit: the prior name
|
||||
// comes from the QueueName attribute recorded at create time, as SnsCfnProvisioner reads
|
||||
// the topic name beside its ARN. Keeping it means an unnamed queue survives an update
|
||||
// instead of being orphaned with its messages. FifoQueue is createOnly like QueueName, so a
|
||||
// prior name whose .fifo suffix no longer matches the flag is a replacing update and gets a
|
||||
// fresh name.
|
||||
String priorName = r.getAttributes() != null ? r.getAttributes().get("QueueName") : null;
|
||||
if (queueName == null || queueName.isBlank()) {
|
||||
// Like real CloudFormation, generated names of FIFO queues must end in .fifo
|
||||
// (SqsService rejects FifoQueue=true otherwise). Keep within the 80-char limit.
|
||||
queueName = fifo
|
||||
? ctx.generatePhysicalName(r.getLogicalId(), 75, false) + ".fifo"
|
||||
: ctx.generatePhysicalName(r.getLogicalId(), 80, false);
|
||||
if (priorName != null && !priorName.isBlank() && priorName.endsWith(".fifo") == fifo) {
|
||||
queueName = priorName;
|
||||
} else {
|
||||
// Like real CloudFormation, generated names of FIFO queues must end in .fifo
|
||||
// (SqsService rejects FifoQueue=true otherwise). Keep within the 80-char limit.
|
||||
queueName = fifo
|
||||
? ctx.generatePhysicalName(r.getLogicalId(), 75, false) + ".fifo"
|
||||
: ctx.generatePhysicalName(r.getLogicalId(), 80, false);
|
||||
}
|
||||
}
|
||||
Map<String, String> attrs = new HashMap<>();
|
||||
if (props != null) {
|
||||
@@ -88,18 +100,44 @@ public class SqsCfnProvisioner implements CfnResourceProvisioner {
|
||||
attrs.put("RedrivePolicy", ctx.engine().resolveJsonAttribute(props.path("RedrivePolicy")));
|
||||
}
|
||||
}
|
||||
Queue queue = sqsService.createQueue(queueName, attrs, ctx.region());
|
||||
// provision is also the update path. createQueue on a name that exists hands back the
|
||||
// queue only when every attribute matches and answers QueueAlreadyExists otherwise, so the
|
||||
// second UpdateStack that changes VisibilityTimeout must go through SetQueueAttributes, the
|
||||
// registry schema's update handler, rather than a second create. The prior physical id is
|
||||
// the queue URL SetQueueAttributes addresses. A replacing update derives a different name
|
||||
// and still creates.
|
||||
// FifoQueue is createOnly and encoded in the name. An explicitly named queue keeps its name
|
||||
// across updates, so a changed FifoQueue would need a replacement under the same name,
|
||||
// which CloudFormation refuses for a custom-named resource: the SQS registry schema says a
|
||||
// named queue cannot take an update that requires replacement. Fail it, as the other
|
||||
// provisioners do, instead of reconciling everything but the mode.
|
||||
if (ctx.isUpdate() && queueName.equals(priorName) && priorName.endsWith(".fifo") != fifo) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Updating FifoQueue requires resource replacement, which is not supported.", 400);
|
||||
}
|
||||
String queueUrl;
|
||||
if (ctx.isUpdate() && queueName.equals(priorName)) {
|
||||
attrs.remove("FifoQueue");
|
||||
sqsService.setQueueAttributes(ctx.priorPhysicalId(), attrs, ctx.region());
|
||||
queueUrl = ctx.priorPhysicalId();
|
||||
} else {
|
||||
Queue queue = sqsService.createQueue(queueName, attrs, ctx.region());
|
||||
queueUrl = queue.getQueueUrl();
|
||||
}
|
||||
// QueueArn is computed on demand in SqsService#getQueueAttributes and is not stored on the
|
||||
// Queue object, so build it here from region + accountId + queueName. Without this,
|
||||
// Fn::GetAtt [Queue, Arn] references resolve to an empty string.
|
||||
String queueArn = AwsArnUtils.Arn.of("sqs", ctx.region(), ctx.accountId(), queueName).toString();
|
||||
r.setPhysicalId(queue.getQueueUrl());
|
||||
r.setPhysicalId(queueUrl);
|
||||
r.getAttributes().put("Arn", queueArn);
|
||||
r.getAttributes().put("QueueName", queueName);
|
||||
r.getAttributes().put("QueueUrl", queue.getQueueUrl());
|
||||
r.getAttributes().put("QueueUrl", queueUrl);
|
||||
}
|
||||
|
||||
private void provisionQueuePolicy(StackResource r) {
|
||||
r.setPhysicalId("queue-policy-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
private void provisionQueuePolicy(StackResource r, ProvisionContext ctx) {
|
||||
// A policy has no backing entity, so its id only has to stay put across updates.
|
||||
r.setPhysicalId(ctx.isUpdate()
|
||||
? ctx.priorPhysicalId()
|
||||
: "queue-policy-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
}
|
||||
+87
@@ -865,6 +865,93 @@ class CloudFormationIntegrationTest {
|
||||
assertThat(secondRevisionId, equalTo(firstRevisionId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_unnamedQueueKeepsItsUrlAndReconcilesAttributes() {
|
||||
// QueueName is createOnly, so an unnamed queue keeps its generated name across updates.
|
||||
// The second UpdateStack then reaches SqsService with a name that exists, which answers
|
||||
// QueueAlreadyExists once an attribute differs: the changed VisibilityTimeout must go
|
||||
// through SetQueueAttributes against the same queue URL instead of a second create.
|
||||
String stackName = "cfn-queue-stable-name-stack";
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MyQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": { "VisibilityTimeout": %d }
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template.formatted(30))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
String createdResourceXml = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackResources")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>MyQueue</LogicalResourceId>"))
|
||||
.extract().asString();
|
||||
String queueUrl = firstPhysicalResourceId(createdResourceXml);
|
||||
assertThat(queueUrl, containsString("/" + stackName + "-MyQueue-"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template.formatted(45))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));
|
||||
|
||||
String updatedResourceXml = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackResources")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
assertThat(firstPhysicalResourceId(updatedResourceXml), equalTo(queueUrl));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "GetQueueAttributes")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.formParam("AttributeName.1", "VisibilityTimeout")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Name>VisibilityTimeout</Name>"))
|
||||
.body(containsString("<Value>45</Value>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_lambdaMutableConfigurationUpdatesInPlace() {
|
||||
String stackName = "cfn-lambda-config-update-stack";
|
||||
|
||||
+96
@@ -6,7 +6,12 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.ecr.EcrService;
|
||||
import io.github.hectorvent.floci.services.ecr.model.Repository;
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.ScheduleGroup;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Queue;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.firehose.FirehoseService;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
@@ -14,6 +19,8 @@ import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
import io.github.hectorvent.floci.services.pipes.model.Pipe;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -195,6 +202,95 @@ class CfnStableNameUpdatePathTest {
|
||||
any(), any(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulerUpdateReconcilesTheGroupItAlreadyOwnsInsteadOfRecreatingIt() {
|
||||
SchedulerService scheduler = mock(SchedulerService.class);
|
||||
when(scheduler.createScheduleGroup(anyString(), any(), anyString())).thenAnswer(inv -> {
|
||||
String name = inv.getArgument(0);
|
||||
return new ScheduleGroup(name, "arn:aws:scheduler:us-east-1:000000000000:schedule-group/" + name,
|
||||
"ACTIVE", Instant.now(), Instant.now());
|
||||
});
|
||||
when(scheduler.getScheduleGroup(anyString(), anyString())).thenAnswer(inv -> {
|
||||
String name = inv.getArgument(0);
|
||||
return new ScheduleGroup(name, "arn:aws:scheduler:us-east-1:000000000000:schedule-group/" + name,
|
||||
"ACTIVE", Instant.now(), Instant.now());
|
||||
});
|
||||
SchedulerScheduleGroupCfnProvisioner provisioner = new SchedulerScheduleGroupCfnProvisioner(scheduler);
|
||||
JsonNode props = mapper.createObjectNode();
|
||||
|
||||
StackResource created = resource("AWS::Scheduler::ScheduleGroup", "Group");
|
||||
provisioner.provision(created, props, ctx(null));
|
||||
String generatedName = created.getPhysicalId();
|
||||
|
||||
StackResource updated = resource("AWS::Scheduler::ScheduleGroup", "Group");
|
||||
provisioner.provision(updated, props, ctx(generatedName));
|
||||
|
||||
assertEquals(generatedName, updated.getPhysicalId(), "the generated name must stay stable");
|
||||
// createScheduleGroup answers ConflictException for a name that exists. Exactly one create.
|
||||
verify(scheduler, times(1)).createScheduleGroup(eq(generatedName), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsUpdateReconcilesTheQueueItAlreadyOwnsInsteadOfRecreatingIt() {
|
||||
SqsService sqs = mock(SqsService.class);
|
||||
when(sqs.createQueue(anyString(), any(), anyString()))
|
||||
.thenAnswer(inv -> new Queue(inv.getArgument(0), "http://q/" + inv.getArgument(0)));
|
||||
SqsCfnProvisioner provisioner = new SqsCfnProvisioner(sqs);
|
||||
JsonNode props = mapper.createObjectNode().put("VisibilityTimeout", 45);
|
||||
|
||||
StackResource created = resource("AWS::SQS::Queue", "Queue");
|
||||
provisioner.provision(created, props, ctx(null));
|
||||
String queueUrl = created.getPhysicalId();
|
||||
String generatedName = created.getAttributes().get("QueueName");
|
||||
|
||||
// The physical id is the URL, so the prior name travels in the attributes the engine
|
||||
// hands back to provision on an update.
|
||||
StackResource updated = resource("AWS::SQS::Queue", "Queue");
|
||||
updated.setAttributes(new HashMap<>(created.getAttributes()));
|
||||
provisioner.provision(updated, props, ctx(queueUrl));
|
||||
|
||||
assertEquals(queueUrl, updated.getPhysicalId(), "the queue URL must stay stable");
|
||||
assertEquals(generatedName, updated.getAttributes().get("QueueName"));
|
||||
// createQueue on an existing name answers QueueAlreadyExists once an attribute differs, so
|
||||
// the update goes through SetQueueAttributes. Exactly one create.
|
||||
verify(sqs, times(1)).createQueue(eq(generatedName), any(), anyString());
|
||||
verify(sqs).setQueueAttributes(eq(queueUrl), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void microvmImageUpdateGoesThroughUpdateImageInsteadOfRecreatingIt() {
|
||||
LambdaMicrovmsService microvms = mock(LambdaMicrovmsService.class);
|
||||
when(microvms.createImage(anyString(), anyString(), anyString(), any(), any(), any(), any()))
|
||||
.thenAnswer(inv -> microvmImage(inv.getArgument(2)));
|
||||
when(microvms.updateImage(anyString(), anyString(), any(), any(), any(), any()))
|
||||
.thenAnswer(inv -> microvmImage(inv.getArgument(1)));
|
||||
LambdaMicrovmsCfnProvisioner provisioner = new LambdaMicrovmsCfnProvisioner(microvms);
|
||||
JsonNode props = mapper.createObjectNode()
|
||||
.put("BaseImageArn", "arn:aws:lambda:us-east-1::base-image:nodejs")
|
||||
.put("BuildRoleArn", "arn:aws:iam::000000000000:role/build");
|
||||
|
||||
StackResource created = resource("AWS::Lambda::MicrovmImage", "Image");
|
||||
provisioner.provision(created, props, ctx(null));
|
||||
String generatedName = created.getPhysicalId();
|
||||
|
||||
StackResource updated = resource("AWS::Lambda::MicrovmImage", "Image");
|
||||
provisioner.provision(updated, props, ctx(generatedName));
|
||||
|
||||
assertEquals(generatedName, updated.getPhysicalId(), "the generated name must stay stable");
|
||||
// createImage on an existing image silently mints a new version rather than rejecting, so
|
||||
// here the assertion is that the update went to the schema's update handler instead.
|
||||
verify(microvms, times(1)).createImage(anyString(), anyString(), eq(generatedName), any(), any(), any(), any());
|
||||
verify(microvms).updateImage(eq("us-east-1"), eq(generatedName), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
private static LambdaMicrovmsService.MicrovmImage microvmImage(String name) {
|
||||
LambdaMicrovmsService.MicrovmImage image = new LambdaMicrovmsService.MicrovmImage();
|
||||
image.name = name;
|
||||
image.imageArn = "arn:aws:lambda:us-east-1:000000000000:microvm-image:" + name;
|
||||
image.latestActiveImageVersion = "1.0";
|
||||
return image;
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3UpdateDoesNotRecreateTheBucketItAlreadyOwns() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
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.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@code AWS::Lambda::MicrovmImage} in isolation. Name is a createOnlyProperty in the registry
|
||||
* schema and the physical id, so an unnamed image must keep its generated name across updates and
|
||||
* the update must go through UpdateMicrovmImage, the schema's update handler, rather than mint a
|
||||
* fresh version through create.
|
||||
*/
|
||||
class LambdaMicrovmsCfnProvisionerTest {
|
||||
|
||||
private static final String BASE_IMAGE = "arn:aws:lambda:us-east-1::base-image:nodejs";
|
||||
private static final String BUILD_ROLE = "arn:aws:iam::000000000000:role/build";
|
||||
private static final String CODE_URI = "s3://bucket/code.zip";
|
||||
|
||||
private final LambdaMicrovmsService service = mock(LambdaMicrovmsService.class);
|
||||
private final LambdaMicrovmsCfnProvisioner provisioner = new LambdaMicrovmsCfnProvisioner(service);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("MyImage");
|
||||
r.setResourceType("AWS::Lambda::MicrovmImage");
|
||||
return r;
|
||||
}
|
||||
|
||||
private ObjectNode props(String name) {
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("BaseImageArn", BASE_IMAGE)
|
||||
.put("BuildRoleArn", BUILD_ROLE)
|
||||
.put("Description", "an image");
|
||||
if (name != null) {
|
||||
props.put("Name", name);
|
||||
}
|
||||
props.set("CodeArtifact", mapper.createObjectNode().put("Uri", CODE_URI));
|
||||
return props;
|
||||
}
|
||||
|
||||
private static LambdaMicrovmsService.MicrovmImage image(String name, String version) {
|
||||
LambdaMicrovmsService.MicrovmImage image = new LambdaMicrovmsService.MicrovmImage();
|
||||
image.name = name;
|
||||
image.imageArn = "arn:aws:lambda:us-east-1:000000000000:microvm-image:" + name;
|
||||
image.latestActiveImageVersion = version;
|
||||
return image;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSetsThePhysicalIdAndTheGetAttAttributes() {
|
||||
when(service.createImage(eq("us-east-1"), eq("000000000000"), eq("img"), eq(BASE_IMAGE),
|
||||
eq(BUILD_ROLE), eq(CODE_URI), eq("an image"))).thenReturn(image("img", "1.0"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("img"), ctx(null));
|
||||
|
||||
assertEquals("img", r.getPhysicalId());
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:microvm-image:img", r.getAttributes().get("ImageArn"));
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:microvm-image:img", r.getAttributes().get("Arn"));
|
||||
assertEquals("img", r.getAttributes().get("Name"));
|
||||
assertEquals("1.0", r.getAttributes().get("LatestActiveImageVersion"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedImageKeepsItsNameAndIsUpdatedRatherThanRecreated() {
|
||||
when(service.createImage(anyString(), anyString(), anyString(), any(), any(), any(), any()))
|
||||
.thenAnswer(inv -> image(inv.getArgument(2), "1.0"));
|
||||
when(service.updateImage(anyString(), anyString(), any(), any(), any(), any()))
|
||||
.thenAnswer(inv -> image(inv.getArgument(1), "2.0"));
|
||||
StackResource created = resource();
|
||||
provisioner.provision(created, props(null), ctx(null));
|
||||
String generatedName = created.getPhysicalId();
|
||||
assertTrue(generatedName.startsWith("my-stack-MyImage-"), generatedName);
|
||||
|
||||
StackResource updated = resource();
|
||||
provisioner.provision(updated, props(null), ctx(generatedName));
|
||||
|
||||
assertEquals(generatedName, updated.getPhysicalId());
|
||||
assertEquals("2.0", updated.getAttributes().get("LatestActiveImageVersion"));
|
||||
verify(service, times(1)).createImage(anyString(), anyString(), anyString(), any(), any(), any(), any());
|
||||
verify(service).updateImage("us-east-1", generatedName, BASE_IMAGE, BUILD_ROLE, CODE_URI, "an image");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRenamedImageIsAReplacingUpdateAndStillCreates() {
|
||||
when(service.createImage(anyString(), anyString(), anyString(), any(), any(), any(), any()))
|
||||
.thenAnswer(inv -> image(inv.getArgument(2), "1.0"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("renamed"), ctx("old-name"));
|
||||
|
||||
assertEquals("renamed", r.getPhysicalId());
|
||||
verify(service).createImage(eq("us-east-1"), eq("000000000000"), eq("renamed"), any(), any(), any(), any());
|
||||
verify(service, never()).updateImage(anyString(), anyString(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
+15
@@ -177,4 +177,19 @@ class ProvisionContextTest {
|
||||
"a replacing update derives a different name and must still create");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void staleTagKeysListsTheCurrentKeysTheTemplateDropped() {
|
||||
Map<String, String> current = new java.util.LinkedHashMap<>();
|
||||
current.put("Keep", "same");
|
||||
current.put("Old", "value");
|
||||
current.put("Gone", "too");
|
||||
|
||||
assertEquals(List.of("Old", "Gone"),
|
||||
ProvisionContext.staleTagKeys(current, Map.of("Keep", "same", "New", "added")));
|
||||
assertEquals(List.of(), ProvisionContext.staleTagKeys(null, Map.of("Keep", "same")),
|
||||
"no stored tags means nothing to untag");
|
||||
assertEquals(List.of("Keep", "Old", "Gone"), ProvisionContext.staleTagKeys(current, Map.of()),
|
||||
"a template with no Tags leaves the resource untagged");
|
||||
}
|
||||
}
|
||||
+52
-24
@@ -23,6 +23,7 @@ import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -39,12 +40,17 @@ class SchedulerScheduleGroupCfnProvisionerTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
return ctx(null);
|
||||
}
|
||||
|
||||
/** An update-path context carries the physical id the previous provision assigned. */
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private StackResource resource(String logicalId) {
|
||||
@@ -90,6 +96,25 @@ class SchedulerScheduleGroupCfnProvisionerTest {
|
||||
assertTrue(r.getPhysicalId().length() <= 64, "schedule group names are capped at 64 characters");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutNameKeepsTheGeneratedNameAcrossUpdates() {
|
||||
// Name is createOnly in the registry schema: provision runs again on every UpdateStack, and
|
||||
// generating unconditionally would create a second group under a new name each time.
|
||||
when(schedulerService.createScheduleGroup(anyString(), any(), eq("us-east-1")))
|
||||
.thenAnswer(inv -> group(inv.getArgument(0), Map.of()));
|
||||
StackResource created = resource("MyGroup");
|
||||
provisioner.provision(created, mapper.createObjectNode(), ctx());
|
||||
String generatedName = created.getPhysicalId();
|
||||
when(schedulerService.getScheduleGroup(generatedName, "us-east-1"))
|
||||
.thenReturn(group(generatedName, Map.of()));
|
||||
|
||||
StackResource updated = resource("MyGroup");
|
||||
provisioner.provision(updated, mapper.createObjectNode(), ctx(generatedName));
|
||||
|
||||
assertEquals(generatedName, updated.getPhysicalId());
|
||||
verify(schedulerService, times(1)).createScheduleGroup(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesResolvedTagsToCreateScheduleGroup() {
|
||||
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
|
||||
@@ -104,21 +129,36 @@ class SchedulerScheduleGroupCfnProvisionerTest {
|
||||
verify(schedulerService).createScheduleGroup("my-group", Map.of("Env", "prod"), "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGroupDeletedOutOfBandFailsTheUpdate() {
|
||||
// The reuse path reads the group this resource already owns. If it was deleted outside the
|
||||
// stack, the not-found error reaches the caller and the update fails, as CloudFormation
|
||||
// does; the old create-then-adopt path silently recreated it instead.
|
||||
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "ScheduleGroup not found: my-group", 404));
|
||||
StackResource r = resource("MyGroup");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, props, ctx("my-group")));
|
||||
|
||||
assertEquals("ResourceNotFoundException", failure.getErrorCode());
|
||||
verify(schedulerService, never()).createScheduleGroup(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameStackRetryAdoptsExistingGroup() {
|
||||
// The physical id already recorded on this resource (from an earlier attempt) matches the
|
||||
// name this attempt resolves to, so a ConflictException on create means this attempt's own
|
||||
// group already exists - adopt it instead of failing the stack.
|
||||
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
|
||||
.thenThrow(new AwsException("ConflictException", "already exists", 409));
|
||||
// The physical id the previous provision assigned matches the name this one resolves to, so
|
||||
// this logical resource's own group already exists: reconcile it instead of calling create,
|
||||
// which would answer ConflictException and fail the stack.
|
||||
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
|
||||
.thenReturn(group("my-group", Map.of()));
|
||||
StackResource r = resource("MyGroup");
|
||||
r.setPhysicalId("my-group");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
provisioner.provision(r, props, ctx("my-group"));
|
||||
|
||||
verify(schedulerService, never()).createScheduleGroup(anyString(), any(), anyString());
|
||||
assertEquals("my-group", r.getPhysicalId());
|
||||
assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule-group/my-group",
|
||||
r.getAttributes().get("Arn"));
|
||||
@@ -183,17 +223,14 @@ class SchedulerScheduleGroupCfnProvisionerTest {
|
||||
void sameStackRetryRemovesTagsDroppedFromTheTemplate() {
|
||||
// pgermosen review on PR #2796: the retry path only ever added tags on conflict, so a tag
|
||||
// removed from the template stayed on the live resource across every subsequent update.
|
||||
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
|
||||
.thenThrow(new AwsException("ConflictException", "already exists", 409));
|
||||
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
|
||||
.thenReturn(group("my-group", Map.of("Old", "value", "Keep", "same")));
|
||||
StackResource r = resource("MyGroup");
|
||||
r.setPhysicalId("my-group");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
|
||||
ObjectNode tag = mapper.createObjectNode().put("Key", "Keep").put("Value", "same");
|
||||
props.set("Tags", mapper.createArrayNode().add(tag));
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
provisioner.provision(r, props, ctx("my-group"));
|
||||
|
||||
verify(schedulerService).untagScheduleGroup(eq("my-group"), eq("us-east-1"),
|
||||
argThat(keys -> keys.size() == 1 && keys.contains("Old")));
|
||||
@@ -204,15 +241,12 @@ class SchedulerScheduleGroupCfnProvisionerTest {
|
||||
void sameStackRetryWithEmptyTemplateTagsRemovesAllExistingTags() {
|
||||
// The Tags property emptied entirely on the template is the same case as a dropped key,
|
||||
// just for every key at once - the whole existing tag set must come off.
|
||||
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
|
||||
.thenThrow(new AwsException("ConflictException", "already exists", 409));
|
||||
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
|
||||
.thenReturn(group("my-group", Map.of("Old", "value")));
|
||||
StackResource r = resource("MyGroup");
|
||||
r.setPhysicalId("my-group");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
provisioner.provision(r, props, ctx("my-group"));
|
||||
|
||||
verify(schedulerService).untagScheduleGroup(eq("my-group"), eq("us-east-1"),
|
||||
argThat(keys -> keys.size() == 1 && keys.contains("Old")));
|
||||
@@ -226,19 +260,16 @@ class SchedulerScheduleGroupCfnProvisionerTest {
|
||||
// here - props.get("Tags").isArray() is false, same as no Tags at all. Before this test, that
|
||||
// made the retry path's tag-diff see an empty desired set and untag every live key, actively
|
||||
// destroying tags a resolvable Tags property never asked to remove.
|
||||
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
|
||||
.thenThrow(new AwsException("ConflictException", "already exists", 409));
|
||||
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
|
||||
.thenReturn(group("my-group", Map.of("Old", "value")));
|
||||
StackResource r = resource("MyGroup");
|
||||
r.setPhysicalId("my-group");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
|
||||
ObjectNode condition = mapper.createObjectNode();
|
||||
condition.set("Fn::If", mapper.createArrayNode().add("UseProdTags")
|
||||
.add(mapper.createArrayNode()).add(mapper.createArrayNode()));
|
||||
props.set("Tags", condition);
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
provisioner.provision(r, props, ctx("my-group"));
|
||||
|
||||
verify(schedulerService, never()).untagScheduleGroup(anyString(), anyString(), any());
|
||||
verify(schedulerService, never()).tagScheduleGroup(anyString(), anyString(), any());
|
||||
@@ -246,15 +277,12 @@ class SchedulerScheduleGroupCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void sameStackRetryWithNoTagChangesDoesNotCallUntagOrTag() {
|
||||
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
|
||||
.thenThrow(new AwsException("ConflictException", "already exists", 409));
|
||||
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
|
||||
.thenReturn(group("my-group", Map.of()));
|
||||
StackResource r = resource("MyGroup");
|
||||
r.setPhysicalId("my-group");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
provisioner.provision(r, props, ctx("my-group"));
|
||||
|
||||
verify(schedulerService, never()).untagScheduleGroup(anyString(), anyString(), any());
|
||||
verify(schedulerService, never()).tagScheduleGroup(anyString(), anyString(), any());
|
||||
|
||||
+102
@@ -3,6 +3,7 @@ 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.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
@@ -14,12 +15,16 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
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.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -66,6 +71,13 @@ class SqsCfnProvisionerTest {
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
/** The update path: the same engine plus the physical id the previous provision assigned. */
|
||||
private ProvisionContext updateCtx(String priorPhysicalId) {
|
||||
ProvisionContext create = ctx();
|
||||
return new ProvisionContext(create.engine(), create.region(), create.accountId(),
|
||||
create.stackName(), priorPhysicalId);
|
||||
}
|
||||
|
||||
private StackResource resource(String type, String logicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId(logicalId);
|
||||
@@ -196,6 +208,96 @@ class SqsCfnProvisionerTest {
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedQueueKeepsItsNameAcrossUpdates() {
|
||||
// QueueName is createOnly in the registry schema. The physical id is the queue URL, so the
|
||||
// prior name is read from the QueueName attribute recorded at create time, not derived
|
||||
// from the id; generating a fresh name would create a second queue and orphan the first.
|
||||
when(sqs.createQueue(anyString(), any(), eq("us-east-1")))
|
||||
.thenAnswer(inv -> new Queue(inv.getArgument(0), "http://q/" + inv.getArgument(0)));
|
||||
StackResource created = resource("AWS::SQS::Queue", "MyQueue");
|
||||
provisioner.provision(created, mapper.createObjectNode(), ctx());
|
||||
String generatedName = created.getAttributes().get("QueueName");
|
||||
String queueUrl = created.getPhysicalId();
|
||||
|
||||
StackResource updated = resource("AWS::SQS::Queue", "MyQueue");
|
||||
updated.setAttributes(new HashMap<>(created.getAttributes()));
|
||||
provisioner.provision(updated, mapper.createObjectNode(), updateCtx(queueUrl));
|
||||
|
||||
assertEquals(queueUrl, updated.getPhysicalId());
|
||||
assertEquals(generatedName, updated.getAttributes().get("QueueName"));
|
||||
verify(sqs, times(1)).createQueue(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateReconcilesAttributesInsteadOfRecreating() {
|
||||
// SqsService.createQueue on an existing name answers QueueAlreadyExists when any attribute
|
||||
// differs, so a changed VisibilityTimeout must go through SetQueueAttributes, the registry
|
||||
// schema's update handler. FifoQueue is createOnly and must not be sent there.
|
||||
StackResource r = resource("AWS::SQS::Queue", "MyQueue");
|
||||
r.setAttributes(new HashMap<>(Map.of("QueueName", "orders.fifo")));
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("QueueName", "orders.fifo")
|
||||
.put("FifoQueue", true)
|
||||
.put("VisibilityTimeout", 45);
|
||||
|
||||
provisioner.provision(r, props, updateCtx("http://localhost:4566/000000000000/orders.fifo"));
|
||||
|
||||
verify(sqs, never()).createQueue(anyString(), any(), anyString());
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, String>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(sqs).setQueueAttributes(eq("http://localhost:4566/000000000000/orders.fifo"),
|
||||
captor.capture(), eq("us-east-1"));
|
||||
assertEquals("45", captor.getValue().get("VisibilityTimeout"));
|
||||
assertFalse(captor.getValue().containsKey("FifoQueue"), "FifoQueue is createOnly");
|
||||
assertEquals("http://localhost:4566/000000000000/orders.fifo", r.getPhysicalId());
|
||||
assertEquals("arn:aws:sqs:us-east-1:000000000000:orders.fifo", r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void flippingFifoQueueIsAReplacingUpdate() {
|
||||
// FifoQueue is createOnly too: a prior plain name cannot serve a queue that is now FIFO, so
|
||||
// the update derives a fresh .fifo name and creates, as a replacing update should.
|
||||
when(sqs.createQueue(anyString(), any(), eq("us-east-1")))
|
||||
.thenAnswer(inv -> new Queue(inv.getArgument(0), "http://q/" + inv.getArgument(0)));
|
||||
StackResource r = resource("AWS::SQS::Queue", "MyQueue");
|
||||
r.setAttributes(new HashMap<>(Map.of("QueueName", "my-stack-MyQueue-0123456789ab")));
|
||||
ObjectNode props = mapper.createObjectNode().put("FifoQueue", true);
|
||||
|
||||
provisioner.provision(r, props, updateCtx("http://q/my-stack-MyQueue-0123456789ab"));
|
||||
|
||||
String queueName = r.getAttributes().get("QueueName");
|
||||
assertTrue(queueName.endsWith(".fifo"), "expected a fresh FIFO name but was: " + queueName);
|
||||
verify(sqs).createQueue(eq(queueName), any(), eq("us-east-1"));
|
||||
verify(sqs, never()).setQueueAttributes(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void flippingFifoQueueOnANamedQueueIsRefused() {
|
||||
// FifoQueue is createOnly and encoded in the name. An explicitly named queue keeps its name,
|
||||
// so a changed FifoQueue would need a replacement under the same name, which CloudFormation
|
||||
// refuses for a custom-named resource. The update must fail rather than reconcile every
|
||||
// other attribute and report success with the queue still in its old mode.
|
||||
StackResource r = resource("AWS::SQS::Queue", "Orders");
|
||||
r.setAttributes(new HashMap<>(Map.of("QueueName", "orders")));
|
||||
ObjectNode props = mapper.createObjectNode().put("QueueName", "orders").put("FifoQueue", true);
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, props, updateCtx("http://q/orders")));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
verify(sqs, never()).createQueue(anyString(), any(), anyString());
|
||||
verify(sqs, never()).setQueueAttributes(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQueuePolicyKeepsItsIdAcrossUpdates() {
|
||||
StackResource r = resource("AWS::SQS::QueuePolicy", "MyPolicy");
|
||||
provisioner.provision(r, mapper.createObjectNode(), updateCtx("queue-policy-1a2b3c4d"));
|
||||
assertEquals("queue-policy-1a2b3c4d", r.getPhysicalId());
|
||||
verifyNoInteractions(sqs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuePolicyGetsAPhysicalId() {
|
||||
StackResource r = resource("AWS::SQS::QueuePolicy", "MyPolicy");
|
||||
|
||||
Reference in new issue
Block a user