mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
refactor(cloudformation): move the Events types into EventsCfnProvisioner (#3286)
* refactor(cloudformation): move the Events types into a per-service provisioner AWS::Events::Rule, EventBus and EventBusPolicy move out of the legacy monolith into EventsCfnProvisioner, continuing the decomposition. The block was already contiguous and self-contained: 18 methods and five constants, none of them referenced from outside, and EventBridgeService was the monolith's only user, so the field, its constructor parameter and both imports go too. Behaviour preserving. The event bus arm in particular already carried real logic worth keeping intact: rollback ownership, the created-time check that refuses to delete a bus recreated out of band, managed tag and policy tracking, and the rejection of an unsupported mutable update. All of it moves unchanged. Rule and EventBus were listed in DELETE_NEEDS_STACK_RESOURCE because deleting them needs stored attributes rather than the physical id alone: a rule remembers the custom bus it lives on, and a bus remembers the creation time proving the stack still owns it. That logic moves into the provisioner's delete(StackResource, String) override and both entries leave the set, which is what CfnDeletePrecedenceTest gates. EventBusPolicy keeps the id-only form, its composite busName|statementId id being enough. The four existing Events test classes needed no changes: they build the provisioner through CfnProvisionerFixture, so wiring the new provisioner there is all it took for them to exercise it. 40 tests across them still pass, and the schema-coverage gate finds no new attribute gaps. Monolith 6,457 to 5,954 lines, legacy types 47 to 44. * fix(cloudformation): keep an Events rule's identity and targets across an update provision runs again on every UpdateStack, and the rule arm got both halves of that wrong. An unnamed rule generated a fresh physical name each time, so the second update created a second rule and left the first behind, still matching events and still delivering to its targets. Name is createOnly and a rule's physical id is its name, so ctx.stablePhysicalName applies directly here, unlike the Batch types whose physical id is an ARN and which need the name read from a stored attribute. Targets were never driven to the template's desired state. PutTargets upserts by id and removes nothing, so a target dropped from the template stayed on the rule and kept receiving events indefinitely. The desired set is now reconciled after the put, which also covers a template that declares no Targets at all: that means no targets, so the sweep runs either way. The Targets property is checked for being an array before it is iterated. Five unit tests: an unnamed rule keeping its name, an explicit name still winning, a dropped target being removed, a cleared Targets list removing all of them, and an unchanged set removing nothing. * fix(cloudformation): surface a failed Events policy removal instead of hiding it Deleting an AWS::Events::EventBusPolicy wrapped the whole removal in a bare catch (Exception) that logged at debug and returned. Every failure was hidden: the statement stayed on the bus while the stack reported DELETE_COMPLETE, which is the outcome AGENTS.md rules out for deletes, since a real failure has to reach the stack as DELETE_FAILED. RemovePermission distinguishes its failures, unlike the Batch services where a single ClientException covers everything. It raises ResourceNotFoundException both when the bus is gone and when the statement is not on it, and those are the two cases that genuinely mean "already deleted". So the removal now goes through the shared CfnDeletes.safeDelete tolerating only that code, and anything else, a malformed statement id for instance, propagates. Two unit tests: an already-gone statement counting as deleted, and a ValidationException reaching the caller rather than being swallowed. * fix(cloudformation): drop the em dash from the moved Events javadoc The javadoc came across from CloudFormationResourceProvisioner verbatim. That file holds 30 em dashes but is an existing file, and the doc-style gate only scans the files a PR adds, so moving the prose into a new file is what surfaced a violation that was always there. * fix(cloudformation): read the prior event bus id from the provision context provision serves create and update, and it assigns the new physical id as it runs, so a resource-derived identity check can flip mid-method. The moved code read the prior bus name off the resource. It was captured before the assignment so the behaviour was right, but the convention exists precisely so the next edit cannot quietly break it. * fix(cloudformation): validate the Events policy StatementId The registry schema for AWS::Events::EventBusPolicy and the botocore model agree that StatementId is [a-zA-Z0-9-_]+, 1 to 64 characters, but nothing checked it, so an AWS-invalid value was accepted. It also made the physical id ambiguous. This provisioner keys a policy statement as "<bus name>|<statement id>" and the delete splits on the last separator. Neither the modeled bus-name pattern nor the statement-id one admits a pipe, so holding the value to the model closes that at source rather than by guessing at the split. * fix(cloudformation): restore rule targets when a stack update rolls back The reconciliation sweep this branch added can delete a live target, which nothing could put back: without a rollbackUpdate hook the resource fell to "Rollback is not implemented for AWS::Events::Rule", so a failed stack update left the rule no longer delivering to it and the stack reported UPDATE_ROLLBACK_FAILED. Before the sweep, targets were only ever upserted and there was nothing to restore. Snapshot the rule's targets before the first target call of an update and put them back on failure, following PipesCfnProvisioner: the snapshot is spent by whichever end the update reaches, restoring inside provision when this rule's own reconciliation failed and through rollbackUpdate when a later resource did. The restore is exact rather than additive, so a target the failed update added does not survive it. A restore that fails itself is recorded on the resource instead of thrown, so the stack reports the original failure. The snapshot carries the rule name, its bus and the region because the rollback hook is handed the stack resource alone, and a rule on a custom bus is keyed by that bus. This restores targets, not the rule's own properties, which putRule overwrites on the same path. That gap predates this branch. * refactor(cloudformation): hold the Events provisioner to a single injected service AGENTS.md requires a CloudFormation provisioner to inject only the service it wraps. This one also took an ObjectMapper, carried over from PipesCfnProvisioner when its rollback snapshot was modelled on that class. The package already has a second convention for exactly this job, and it is the one that satisfies the rule: LambdaEventInvokeConfigCfnProvisioner, the other snapshot-based rollback provisioner, holds a private static mapper and injects only its service, as do LambdaEventSourceMappingCfnProvisioner, Ec2NetworkCfnProvisioner and ReplacementCleanup. The configured mapper adds a 100 MB string limit and lenient empty-bean serialization. Neither reaches this code: EventBridge caps a bus policy near 10 KB and a target's Input at 8192 characters, both far under Jackson's default, and every type serialized here has real properties. No behaviour changes, so the existing tests are what prove the swap is inert.
This commit is contained in:
1 parent
ca435aeb50
commit
3218d2404e
6 files changed
+1138
-507
No files matched your search
+4
-1
@@ -30,6 +30,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.EventsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
|
||||
@@ -298,6 +299,9 @@ final class CfnProvisionerFixture {
|
||||
if (backupService != null) {
|
||||
discovered.add(new BackupVaultCfnProvisioner(backupService));
|
||||
}
|
||||
if (eventBridgeService != null) {
|
||||
discovered.add(new EventsCfnProvisioner(eventBridgeService));
|
||||
}
|
||||
if (wafV2Service != null) {
|
||||
discovered.add(new WafV2CfnProvisioner(wafV2Service));
|
||||
}
|
||||
@@ -590,7 +594,6 @@ final class CfnProvisionerFixture {
|
||||
ssmService,
|
||||
kmsService,
|
||||
secretsManagerService,
|
||||
eventBridgeService,
|
||||
apiGatewayService,
|
||||
apiGatewayV2Service,
|
||||
ecrService,
|
||||
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
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.ArrayNode;
|
||||
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.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
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.doThrow;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The Events CFN provisioner in isolation, with only {@link EventBridgeService} mocked. */
|
||||
class EventsCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String RULE_ARN = "arn:aws:events:us-east-1:000000000000:rule/my-stack-Rule-ab12cd";
|
||||
|
||||
private final EventBridgeService events = mock(EventBridgeService.class);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final EventsCfnProvisioner provisioner = new EventsCfnProvisioner(events);
|
||||
|
||||
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();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private StackResource resource(String type, String logicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType(type);
|
||||
r.setLogicalId(logicalId);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private void stubPutRule() {
|
||||
Rule rule = new Rule();
|
||||
rule.setArn(RULE_ARN);
|
||||
when(events.putRule(anyString(), any(), any(), any(), any(), any(), any(), any(), anyString()))
|
||||
.thenReturn(rule);
|
||||
}
|
||||
|
||||
private ObjectNode target(String id, String arn) {
|
||||
return mapper.createObjectNode().put("Id", id).put("Arn", arn);
|
||||
}
|
||||
|
||||
private static Target storedTarget(String id) {
|
||||
return new Target(id, "arn:aws:sqs:us-east-1:000000000000:q-" + id, null, null);
|
||||
}
|
||||
|
||||
// ── the rule keeps its identity across an update ──────────────────────────
|
||||
|
||||
@Test
|
||||
void anUnnamedRuleKeepsItsGeneratedNameAcrossUpdates() {
|
||||
// The defect: generating unconditionally gave an unnamed rule a fresh random name on every
|
||||
// UpdateStack, creating a second rule and leaving the first behind still matching events.
|
||||
stubPutRule();
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode(), ctx("my-stack-Rule-ab12cd"));
|
||||
|
||||
assertEquals("my-stack-Rule-ab12cd", r.getPhysicalId());
|
||||
verify(events).putRule(eq("my-stack-Rule-ab12cd"), any(), any(), any(), any(), any(), any(),
|
||||
any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitlyNamedRuleStillUsesTheTemplateName() {
|
||||
stubPutRule();
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("Name", "orders"), ctx(null));
|
||||
|
||||
assertEquals("orders", r.getPhysicalId());
|
||||
assertEquals(RULE_ARN, r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
// ── targets are driven to the template's desired state ───────────────────
|
||||
|
||||
@Test
|
||||
void aTargetDroppedFromTheTemplateIsRemovedFromTheRule() {
|
||||
// PutTargets only upserts by id, so without the sweep a dropped target stayed on the rule
|
||||
// and kept receiving events after the template stopped declaring it.
|
||||
stubPutRule();
|
||||
when(events.listTargetsByRule(anyString(), any(), anyString()))
|
||||
.thenReturn(List.of(storedTarget("keep"), storedTarget("gone")));
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "orders");
|
||||
props.putArray("Targets").add(target("keep", "arn:aws:sqs:us-east-1:000000000000:q-keep"));
|
||||
|
||||
provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx("orders"));
|
||||
|
||||
ArgumentCaptor<List<String>> removed = ArgumentCaptor.forClass(List.class);
|
||||
verify(events).removeTargets(eq("orders"), any(), removed.capture(), anyString());
|
||||
assertEquals(List.of("gone"), removed.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTemplateThatDeclaresNoTargetsClearsThem() {
|
||||
stubPutRule();
|
||||
when(events.listTargetsByRule(anyString(), any(), anyString()))
|
||||
.thenReturn(List.of(storedTarget("stale")));
|
||||
|
||||
provisioner.provision(resource("AWS::Events::Rule", "Rule"),
|
||||
mapper.createObjectNode().put("Name", "orders"), ctx("orders"));
|
||||
|
||||
ArgumentCaptor<List<String>> removed = ArgumentCaptor.forClass(List.class);
|
||||
verify(events).removeTargets(eq("orders"), any(), removed.capture(), anyString());
|
||||
assertEquals(List.of("stale"), removed.getValue());
|
||||
verify(events, never()).putTargets(anyString(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnchangedTargetSetRemovesNothing() {
|
||||
stubPutRule();
|
||||
when(events.listTargetsByRule(anyString(), any(), anyString()))
|
||||
.thenReturn(List.of(storedTarget("keep")));
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "orders");
|
||||
props.putArray("Targets").add(target("keep", "arn:aws:sqs:us-east-1:000000000000:q-keep"));
|
||||
|
||||
provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx("orders"));
|
||||
|
||||
verify(events).putTargets(eq("orders"), any(), any(), anyString());
|
||||
verify(events, never()).removeTargets(anyString(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
// ── a failed policy removal is not swallowed ─────────────────────────────
|
||||
|
||||
@Test
|
||||
void anAlreadyGonePolicyStatementCountsAsDeleted() {
|
||||
doThrowOnRemovePermission(new AwsException("ResourceNotFoundException",
|
||||
"Statement not found: sid-1", 400));
|
||||
|
||||
provisioner.delete("AWS::Events::EventBusPolicy", "orders-bus|sid-1", REGION);
|
||||
|
||||
verify(events).removePermission("orders-bus", "sid-1", false, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedPolicyRemovalReachesTheStack() {
|
||||
// The previous catch-all logged every failure at debug and returned, so the statement
|
||||
// stayed on the bus while the stack still reported DELETE_COMPLETE.
|
||||
doThrowOnRemovePermission(new AwsException("ValidationException", "StatementId is required.", 400));
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete("AWS::Events::EventBusPolicy", "orders-bus|sid-1", REGION));
|
||||
|
||||
assertEquals("ValidationException", thrown.getErrorCode());
|
||||
assertTrue(thrown.getMessage().contains("StatementId"));
|
||||
}
|
||||
|
||||
// ── the event bus reads its prior identity from the provision context ─────
|
||||
|
||||
@Test
|
||||
void anEventBusUpdateComparesAgainstThePriorIdFromTheContext() {
|
||||
// provision assigns the new id as it runs, so the prior name has to come from the context.
|
||||
// Reading it off the resource made a rename look like a create and silently switched buses.
|
||||
StackResource r = resource("AWS::Events::EventBus", "Bus");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
r, mapper.createObjectNode().put("Name", "renamed"), ctx("orders-bus")));
|
||||
|
||||
assertTrue(thrown.getMessage().contains("requires resource replacement"));
|
||||
}
|
||||
|
||||
// ── the policy statement id is held to the modeled pattern ────────────────
|
||||
|
||||
@Test
|
||||
void aStatementIdCarryingTheIdSeparatorIsRejected() {
|
||||
// AWS models StatementId as [a-zA-Z0-9-_]+, so a pipe cannot reach the service. Refusing it
|
||||
// is parity first, and it also keeps "<bus>|<sid>" splittable back into the pair.
|
||||
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
resource("AWS::Events::EventBusPolicy", "Policy"),
|
||||
policyProps("orders-bus|sid"), ctx(null)));
|
||||
|
||||
assertEquals("ValidationException", thrown.getErrorCode());
|
||||
assertTrue(thrown.getMessage().contains("StatementId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStatementIdBeyondTheModeledLengthIsRejected() {
|
||||
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
resource("AWS::Events::EventBusPolicy", "Policy"),
|
||||
policyProps("s".repeat(65)), ctx(null)));
|
||||
|
||||
assertEquals("ValidationException", thrown.getErrorCode());
|
||||
verify(events, never()).putPermission(anyString(), any(), any(), anyString(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
private ObjectNode policyProps(String statementId) {
|
||||
return mapper.createObjectNode()
|
||||
.put("EventBusName", "orders-bus")
|
||||
.put("StatementId", statementId)
|
||||
.put("Action", "events:PutEvents")
|
||||
.put("Principal", "111122223333");
|
||||
}
|
||||
|
||||
private void doThrowOnRemovePermission(AwsException e) {
|
||||
org.mockito.Mockito.doThrow(e).when(events)
|
||||
.removePermission(anyString(), anyString(), org.mockito.ArgumentMatchers.anyBoolean(), anyString());
|
||||
}
|
||||
|
||||
// ── a failed stack update puts the rule's targets back ────────────────────
|
||||
|
||||
private static final String RULE_TARGETS_SNAPSHOT_ATTR = CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR;
|
||||
|
||||
@Test
|
||||
void aRollbackPutsBackATargetTheUpdateDropped() {
|
||||
// Before the snapshot, the reconciliation sweep could delete a live target and a later
|
||||
// resource's failure left it deleted: the rule stopped delivering to it for good.
|
||||
stubPutRule();
|
||||
stubTargetSequence(List.of(storedTarget("keep"), storedTarget("gone")),
|
||||
List.of(storedTarget("keep"), storedTarget("gone")),
|
||||
List.of(storedTarget("keep")));
|
||||
StackResource r = updatedRuleWithTargets("keep");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
assertEquals(List.of("keep", "gone"), idsOfPutTargets(2).get(1));
|
||||
assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackRemovesATargetTheUpdateAdded() {
|
||||
// The restore is exact, not additive: what the failed update added does not survive it.
|
||||
stubPutRule();
|
||||
stubTargetSequence(List.of(storedTarget("keep")),
|
||||
List.of(storedTarget("keep"), storedTarget("added")),
|
||||
List.of(storedTarget("keep"), storedTarget("added")));
|
||||
StackResource r = updatedRuleWithTargets("keep", "added");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<List<String>> removed = ArgumentCaptor.forClass(List.class);
|
||||
verify(events).removeTargets(eq("orders"), any(), removed.capture(), anyString());
|
||||
assertEquals(List.of("added"), removed.getValue());
|
||||
assertEquals(List.of("keep"), idsOfPutTargets(2).get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleThisRunNeverTouchedIsNotRolledBack() {
|
||||
// Answering true here would clear the targets of a rule the update never reconciled. False
|
||||
// is what makes the stack keep reporting that rollback is not implemented for it.
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
r.setPhysicalId("orders");
|
||||
|
||||
assertFalse(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(events, never()).putTargets(anyString(), any(), any(), anyString());
|
||||
verify(events, never()).removeTargets(anyString(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedReconciliationRestoresTheTargetsAndRethrowsTheFailure() {
|
||||
stubPutRule();
|
||||
stubTargetSequence(List.of(storedTarget("keep"), storedTarget("gone")),
|
||||
List.of(storedTarget("keep"), storedTarget("gone")));
|
||||
AwsException putFailure = new AwsException("ValidationException", "Too many targets", 400);
|
||||
when(events.putTargets(anyString(), any(), any(), anyString())).thenThrow(putFailure).thenReturn(1);
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, ruleProps("keep"), ctx("orders")));
|
||||
|
||||
assertSame(putFailure, thrown);
|
||||
assertEquals(List.of("keep", "gone"), idsOfPutTargets(2).get(1));
|
||||
assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
|
||||
assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreThatAlsoFailsIsRecordedOnTheResource() {
|
||||
// The stack has to report UPDATE_ROLLBACK_FAILED naming this rule rather than claiming the
|
||||
// prior targets are live, so the restore failure goes on the resource instead of being
|
||||
// thrown over the failure that is already on its way out.
|
||||
stubPutRule();
|
||||
stubTargetSequence(List.of(storedTarget("keep"), storedTarget("gone")),
|
||||
List.of(storedTarget("keep"), storedTarget("gone")));
|
||||
AwsException putFailure = new AwsException("ValidationException", "Too many targets", 400);
|
||||
doThrow(putFailure).when(events).putTargets(anyString(), any(), any(), anyString());
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r, ruleProps("keep"), ctx("orders")));
|
||||
|
||||
assertEquals("Too many targets", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreateTakesNoSnapshotToRollBack() {
|
||||
stubPutRule();
|
||||
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
provisioner.provision(r, ruleProps("keep"), ctx(null));
|
||||
|
||||
assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR));
|
||||
assertFalse(provisioner.rollbackUpdate(r));
|
||||
}
|
||||
|
||||
/** Runs an update that reconciles the rule down to {@code desiredIds}, and returns the resource. */
|
||||
private StackResource updatedRuleWithTargets(String... desiredIds) {
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
provisioner.provision(r, ruleProps(desiredIds), ctx("orders"));
|
||||
return r;
|
||||
}
|
||||
|
||||
private ObjectNode ruleProps(String... targetIds) {
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "orders");
|
||||
ArrayNode declared = props.putArray("Targets");
|
||||
for (String id : targetIds) {
|
||||
declared.add(target(id, "arn:aws:sqs:us-east-1:000000000000:q-" + id));
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
/** Successive answers from ListTargetsByRule, in the order the run asks for them. */
|
||||
@SafeVarargs
|
||||
private void stubTargetSequence(List<Target> first, List<Target>... rest) {
|
||||
var stub = when(events.listTargetsByRule(anyString(), any(), anyString())).thenReturn(first);
|
||||
for (List<Target> answer : rest) {
|
||||
stub = stub.thenReturn(answer);
|
||||
}
|
||||
}
|
||||
|
||||
/** The target ids of each PutTargets call, in order, asserting there were exactly {@code n}. */
|
||||
private List<List<String>> idsOfPutTargets(int n) {
|
||||
ArgumentCaptor<List<Target>> put = ArgumentCaptor.forClass(List.class);
|
||||
verify(events, times(n)).putTargets(eq("orders"), any(), put.capture(), anyString());
|
||||
return put.getAllValues().stream().map(call -> call.stream().map(Target::getId).toList()).toList();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user