diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 24e3a2eb1b..7e63aa3be5 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -1060,6 +1060,41 @@ A stack that reached `UPDATE_ROLLBACK_FAILED` under an earlier Floci version kep state before the update. `ContinueUpdateRollback` then retries every `UPDATE_FAILED` resource and keeps the template the stack holds. +## Stack status events + +Every status a stack records, root or nested, goes to the default EventBridge bus of the stack's +account and Region, with source `aws.cloudformation` and detail type +`CloudFormation Stack Status Change`, as +[CloudFormation sends it](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/eventbridge-integration.html). +`resources` holds the stack's ID, and the +[detail](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/event-detail-stack-status-change.html) +holds `stack-id`, `client-request-token` where there is one, and `status-details` with `status`, +`detailed-status` and `status-reason`, each of the last two empty where there is nothing to say. A +resource's progress sends nothing, a parent's record of a nested stack included. Each status is sent +once. + +A failed create or update ends as it does on AWS. A root whose nested stack fails goes from +`CREATE_IN_PROGRESS` to `ROLLBACK_IN_PROGRESS` and `ROLLBACK_COMPLETE`, or from `UPDATE_IN_PROGRESS` +through `UPDATE_ROLLBACK_IN_PROGRESS` and `UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS` to +`UPDATE_ROLLBACK_COMPLETE`, with no `CREATE_FAILED` or `UPDATE_FAILED`. A nested stack whose create +fails sends `CREATE_FAILED`, and its rollback shows as `DELETE_IN_PROGRESS` and `DELETE_COMPLETE`. +A failure in a root's own resource with its nested stack healthy, and a delete that fails, send the +statuses CloudFormation documents from the same code; neither was read against AWS. + +The `client-request-token` is the `ClientRequestToken` of the operation that caused the status: +`ExecuteChangeSet`, `CreateStack`, `UpdateStack`, `DeleteStack` or `ContinueUpdateRollback`, called +directly or from a state machine's `aws-sdk:cloudformation` task. A rollback's statuses carry the token +of the create or update that failed. The key is absent, never empty, on +a nested stack's events, on the `REVIEW_IN_PROGRESS` of a new stack, and on the events of an operation +given no token. + +Events are delivered in order by one background worker, apart from the stack operation and outside any +lock on the stack. The status an operation starts with is sent as the operation begins to run, so one +the operation limit refuses sends nothing. A delivery that fails is logged and changes nothing about +the operation, and a slow target delays later events, never a stack. The worker's queue is in memory: an event still in it when +Floci stops is dropped and counted in the log, and is not sent on the next start, even where the stack +is persisted. + ## Deleted Stacks A deleted stack is kept for a short window afterwards rather than being forgotten at diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationEventPublisher.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationEventPublisher.java new file mode 100644 index 0000000000..89167ba3ee --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationEventPublisher.java @@ -0,0 +1,144 @@ +package io.floci.aws.services.cloudformation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.cloudformation.model.Stack; +import io.floci.aws.services.eventbridge.EventBridgeService; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.Objects; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * Publishes AWS-shaped {@code aws.cloudformation} "CloudFormation Stack Status Change" events to the + * default EventBridge bus of the stack's account and Region, one per status recorded for a stack. + * + *

Unlike the other publishers this one only queues, and one daemon worker delivers in order. A + * status can be recorded while the service holds the stack's lock in {@code stacks.compute}, and + * delivery calls a rule's targets before it returns, so delivering in place would hold that lock and + * the operation for as long as the targets take. + * + *

The queue is in memory. An event still in it when Floci stops is dropped, and counted in the log: + * it is not sent on the next start, even where the stack itself is persisted. + */ +@ApplicationScoped +public class CloudFormationEventPublisher { + + private static final Logger LOG = Logger.getLogger(CloudFormationEventPublisher.class); + static final String SOURCE = "aws.cloudformation"; + static final String DETAIL_TYPE = "CloudFormation Stack Status Change"; + private static final long STATUS_WRITE_WAIT_NANOS = TimeUnit.SECONDS.toNanos(1); + + private record StatusChange(Stack stack, String accountId, String statusWhenRecorded, String status, + String reason, String token) { + } + + private final BlockingQueue pending = new LinkedBlockingQueue<>(); + private final EventBridgeService eventBridgeService; + private final ObjectMapper objectMapper; + private Thread worker; + + @Inject + public CloudFormationEventPublisher(EventBridgeService eventBridgeService, ObjectMapper objectMapper) { + this.eventBridgeService = eventBridgeService; + this.objectMapper = objectMapper; + } + + @PostConstruct + void start() { + worker = new Thread(this::deliverInOrder, "cloudformation-event-publisher"); + worker.setDaemon(true); + worker.start(); + } + + @PreDestroy + void stop() { + worker.interrupt(); + } + + /** The worker's state: sleeping in {@link #awaitStatusWrite} is TIMED_WAITING, stopped is TERMINATED. */ + Thread.State workerState() { + return worker.getState(); + } + + /** + * Queues one event for {@code status} and returns at once, so it is safe under the stack's lock. + * The token is the one on the stack now, the operation that caused this status. + */ + public void stackStatusChanged(Stack stack, String accountId, String status, String reason) { + pending.add(new StatusChange(stack, accountId, stack.getStatus(), status, reason, + stack.getClientRequestToken())); + } + + private void deliverInOrder() { + StatusChange held = null; + try { + while (true) { + held = pending.take(); + awaitStatusWrite(held); + if (Thread.interrupted()) { + throw new InterruptedException(); + } + deliver(held); + held = null; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + int dropped = pending.size() + (held != null ? 1 : 0); + if (dropped > 0) { + LOG.warnv("Dropping {0} queued CloudFormation Stack Status Change event(s): Floci is stopping", dropped); + } + } + } + + /** + * A failed path records its event before it writes the status, the volatile publishing write, so + * that a reader who sees the status also sees the event in DescribeStackEvents. A reader the bus + * event wakes must see the status too, so delivery waits out the few statements between the two. + * Bounded, since a status left unwritten must not hold up every later event. + */ + private static void awaitStatusWrite(StatusChange change) throws InterruptedException { + if (Objects.equals(change.statusWhenRecorded(), change.status())) { + return; + } + long deadline = System.nanoTime() + STATUS_WRITE_WAIT_NANOS; + while (Objects.equals(change.statusWhenRecorded(), change.stack().getStatus()) + && System.nanoTime() < deadline) { + Thread.sleep(1); + } + } + + private void deliver(StatusChange change) { + String stackId = change.stack().getStackId(); + String region = change.stack().getRegion(); + try { + String detail = objectMapper.writeValueAsString(buildDetail(change)); + RequestScopes.runAs(change.accountId(), region, + () -> eventBridgeService.publishServiceEvent(SOURCE, DETAIL_TYPE, detail, stackId, region)); + } catch (Exception e) { + LOG.warnv("Failed to emit CloudFormation Stack Status Change for {0}: {1}", stackId, e.getMessage()); + } + } + + // As CloudFormation sent them on 2026-10-30: the key is absent, not empty, where there is no token, + // and detailed-status and status-reason are present and empty where there is nothing to say. + private ObjectNode buildDetail(StatusChange change) { + ObjectNode detail = objectMapper.createObjectNode(); + detail.put("stack-id", change.stack().getStackId()); + if (change.token() != null && !change.token().isEmpty()) { + detail.put("client-request-token", change.token()); + } + ObjectNode statusDetails = detail.putObject("status-details"); + statusDetails.put("status", change.status()); + statusDetails.put("detailed-status", ""); + statusDetails.put("status-reason", change.reason() != null ? change.reason() : ""); + return detail; + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java index ea35ff8fa0..7d03d304fb 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java @@ -125,7 +125,8 @@ public class CloudFormationQueryHandler { templateBody, templateUrl, parameters, capabilities, tags, region, terminationProtection, stackPolicy); try { - cfnService.executeChangeSet(initial.getStackId(), initial.getChangeSetId(), region); + cfnService.executeChangeSetWithToken(initial.getStackId(), initial.getChangeSetId(), region, + params.getFirst("ClientRequestToken")); } catch (AwsException e) { if (terminationProtection) { cfnService.clearProtectionAfterRejectedCreate(stackName, initial, region); @@ -171,7 +172,8 @@ public class CloudFormationQueryHandler { cfnService.deleteChangeSet(stackName, cs.getChangeSetName(), region); return xmlError("ValidationError", "No updates are to be performed.", 400); } - cfnService.executeChangeSet(cs.getStackId(), cs.getChangeSetId(), region); + cfnService.executeChangeSetWithToken(cs.getStackId(), cs.getChangeSetId(), region, + params.getFirst("ClientRequestToken")); String xml = new XmlBuilder() .start("UpdateStackResponse", CF_NS) @@ -190,7 +192,7 @@ public class CloudFormationQueryHandler { String stackName = params.getFirst("StackName"); List retainResources = extractList(params, "RetainResources.member."); try { - cfnService.deleteStack(stackName, retainResources, region); + cfnService.deleteStackForRequest(stackName, retainResources, region, params.getFirst("ClientRequestToken")); String xml = new XmlBuilder() .start("DeleteStackResponse", CF_NS) .raw(AwsQueryResponse.responseMetadata()) @@ -208,10 +210,12 @@ public class CloudFormationQueryHandler { String stackName = params.getFirst("StackName"); List resourcesToSkip = extractList(params, "ResourcesToSkip.member."); boolean forceRollback = Boolean.parseBoolean(params.getFirst("ForceRollback")); - // RoleARN and ClientRequestToken are accepted and have no effect: Floci assumes no role - // for stack operations and does not deduplicate retried requests. + // RoleARN is accepted and has no effect: Floci assumes no role for stack operations. + // ClientRequestToken goes on the status events the operation sends; a repeated one is not + // refused, as Floci does not deduplicate retried requests. try { - cfnService.continueUpdateRollback(stackName, resourcesToSkip, forceRollback, region); + cfnService.continueUpdateRollback(stackName, resourcesToSkip, forceRollback, region, + params.getFirst("ClientRequestToken")); } catch (AwsException e) { return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus()); } @@ -362,7 +366,8 @@ public class CloudFormationQueryHandler { String stackName = params.getFirst("StackName"); String changeSetName = params.getFirst("ChangeSetName"); try { - cfnService.executeChangeSetForRequest(stackName, changeSetName, region); + cfnService.executeChangeSetForRequest(stackName, changeSetName, region, + params.getFirst("ClientRequestToken")); } catch (AwsException e) { return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus()); } diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index c4ff48adfa..973e169a06 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -128,7 +128,10 @@ public class CloudFormationService implements ResourceProvider { // The execution running on a stack, by stack id, completed once it and any delete it deferred end. private final ConcurrentHashMap> runningExecutions = new ConcurrentHashMap<>(); // A delete requested while its stack's execution runs, by stack id, with the resources it retains. - private final ConcurrentHashMap> deferredDeletes = new ConcurrentHashMap<>(); + private final ConcurrentHashMap deferredDeletes = new ConcurrentHashMap<>(); + + /** A DeleteStack accepted while an execution runs: what it retains, and the token its statuses carry. */ + private record DeferredDelete(List retain, String clientRequestToken) {} private final ExecutorService executor = newOperationExecutor(); static ThreadPoolExecutor newOperationExecutor() { @@ -149,6 +152,8 @@ public class CloudFormationService implements ResourceProvider { private final SamTransformProcessor samTransformProcessor; private final AwsIncludeProcessor awsIncludeProcessor; private final Clock clock; + // Null on a service built by hand, as a unit test builds one, which then sends no events. + private final CloudFormationEventPublisher eventPublisher; // Persisted state so stacks survive a restart (criteria #10, #11). The in-memory maps above are // the live working copy; these backends are write-through + loaded on startup. Legacy records @@ -157,13 +162,24 @@ public class CloudFormationService implements ResourceProvider { private final AccountAwareStorageBackend exportBackend; - @Inject public CloudFormationService(CfnResourceDispatcher dispatcher, S3Service s3Service, SsmService ssmService, GetStackOutputRoleAuthorizer stackOutputRoles, CfnDynamicReferences dynamicReferences, ObjectMapper objectMapper, EmulatorConfig config, RegionResolver regionResolver, Clock clock, StorageFactory storageFactory) { + this(dispatcher, s3Service, ssmService, stackOutputRoles, dynamicReferences, objectMapper, config, + regionResolver, clock, storageFactory, null); + } + + @Inject + public CloudFormationService(CfnResourceDispatcher dispatcher, S3Service s3Service, + SsmService ssmService, GetStackOutputRoleAuthorizer stackOutputRoles, + CfnDynamicReferences dynamicReferences, + ObjectMapper objectMapper, EmulatorConfig config, + RegionResolver regionResolver, Clock clock, + StorageFactory storageFactory, + CloudFormationEventPublisher eventPublisher) { this.dispatcher = dispatcher; this.s3Service = s3Service; this.ssmService = ssmService; @@ -175,6 +191,7 @@ public class CloudFormationService implements ResourceProvider { this.samTransformProcessor = new SamTransformProcessor(objectMapper); this.awsIncludeProcessor = new AwsIncludeProcessor(objectMapper, s3Service); this.clock = clock; + this.eventPublisher = eventPublisher; this.stackBackend = storageFactory.create( "cloudformation", "cloudformation-stacks.json", new TypeReference>() {}); this.exportBackend = storageFactory.create( @@ -736,6 +753,9 @@ public class CloudFormationService implements ResourceProvider { cs.setStatus("CREATE_COMPLETE"); cs.setExecutionStatus("AVAILABLE"); } + // No operation runs on a stack that takes a change set, and what this one records carries + // no token: CreateChangeSet's ClientToken is not a ClientRequestToken. + target.setClientRequestToken(null); target.getChangeSets().put(changeSetName, cs); created[0] = cs; return target; @@ -1332,8 +1352,20 @@ public class CloudFormationService implements ResourceProvider { * update equivalent) when their own change set failed - executing it unconditionally is how * that failure surfaces on those paths, and floci must still expose it there. */ - public Future executeChangeSetForRequest(String stackName, String changeSetName, String region) { - return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), true); + public Future executeChangeSetForRequest(String stackName, String changeSetName, String region, + String clientRequestToken) { + return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), true, + clientRequestToken); + } + + /** + * The execute {@code CreateStack} and {@code UpdateStack} run, as + * {@link #executeChangeSet(String, String, String)}, for a request that carries a token. + */ + public Future executeChangeSetWithToken(String stackName, String changeSetName, String region, + String clientRequestToken) { + return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), false, + clientRequestToken); } /** @@ -1351,7 +1383,7 @@ public class CloudFormationService implements ResourceProvider { * refuses one that is already executing or has already executed. */ public Future executeChangeSet(String stackName, String changeSetName, String region, String accountId) { - return claimAndSubmitExecution(stackName, changeSetName, region, accountId, false); + return claimAndSubmitExecution(stackName, changeSetName, region, accountId, false, null); } private record ClaimedExecution(ChangeSet changeSet, boolean isCreate, CompletableFuture done) {} @@ -1366,7 +1398,8 @@ public class CloudFormationService implements ResourceProvider { // compute() holds the stack's per-key lock for the whole claim, so only one racing execution can win. private Future claimAndSubmitExecution(String stackNameOrArn, String changeSetName, String region, - String accountId, boolean requireAvailable) { + String accountId, boolean requireAvailable, + String clientRequestToken) { String canonicalStackName = getStackForChangeSet(stackNameOrArn, changeSetName, region, accountId).getStackName(); @@ -1412,9 +1445,10 @@ public class CloudFormationService implements ResourceProvider { if (isCreate && cs.getStackPolicyBody() != null) { existing.setStackPolicyBody(cs.getStackPolicyBody()); } + existing.setClientRequestToken(clientRequestToken); existing.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS"); existing.setLastUpdatedTime(now()); - addEvent(existing, existing.getStackName(), existing.getStackId(), + recordEvent(existing, existing.getStackName(), existing.getStackId(), "AWS::CloudFormation::Stack", isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null); CompletableFuture done = new CompletableFuture<>(); runningExecutions.put(existing.getStackId(), done); @@ -1453,6 +1487,7 @@ public class CloudFormationService implements ResourceProvider { Map params = cs.getParameters() != null ? cs.getParameters() : Map.of(); return submitOperation(() -> RequestScopes.runAs(accountId, region, () -> { + publishStackStatus(stack, claimed.isCreate() ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null); try { executeTemplate(stack, templateBody, params, cs.getTags(), claimed.isCreate(), region, accountId, cs.getStackPolicyBody()); @@ -1484,14 +1519,17 @@ public class CloudFormationService implements ResourceProvider { if (!runningExecutions.remove(stackId, done)) { return existing; } - List retain = deferredDeletes.remove(stackId); - if (retain != null && existing != null && stackId.equals(existing.getStackId())) { - startDelete(existing, retain); - deferred.add(retain); + DeferredDelete delete = deferredDeletes.remove(stackId); + if (delete != null && existing != null && stackId.equals(existing.getStackId())) { + // The delete's own token, not the execution's, from its first status on. + existing.setClientRequestToken(delete.clientRequestToken()); + startDelete(existing, delete.retain()); + deferred.add(delete.retain()); } return existing; }); if (!deferred.isEmpty()) { + publishStackStatus(stack, "DELETE_IN_PROGRESS", null); deleteStackResources(stack, deferred.getFirst(), region, accountId); } done.complete(null); @@ -1501,10 +1539,11 @@ public class CloudFormationService implements ResourceProvider { } } + /** Moves the stack to DELETE_IN_PROGRESS; the delete sends that status as it begins. */ private void startDelete(Stack stack, List retain) { stack.setRetainResources(retain); stack.setStatus("DELETE_IN_PROGRESS"); - addEvent(stack, stack.getStackName(), stack.getStackId(), + recordEvent(stack, stack.getStackName(), stack.getStackId(), "AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null); } @@ -1552,6 +1591,17 @@ public class CloudFormationService implements ResourceProvider { * removal) can await it. */ public Future deleteStack(String stackName, List retainResources, String region, String accountId) { + return deleteStack(stackName, retainResources, region, accountId, null); + } + + /** The {@code DeleteStack} operation, in the caller's account, for a request that may carry a token. */ + public Future deleteStackForRequest(String stackName, List retainResources, String region, + String clientRequestToken) { + return deleteStack(stackName, retainResources, region, regionResolver.getAccountId(), clientRequestToken); + } + + private Future deleteStack(String stackName, List retainResources, String region, String accountId, + String clientRequestToken) { validateRetainResources(retainResources); purgeExpiredDeletedStacks(); Stack stack = resolveStack(stackName, region, accountId); @@ -1611,15 +1661,18 @@ public class CloudFormationService implements ResourceProvider { if (running != null) { // The execution deletes the stack once it ends: a create stops before its next // resource, an update finishes, and the delete then removes all that was built. - deferredDeletes.putIfAbsent(existing.getStackId(), retain); + deferredDeletes.putIfAbsent(existing.getStackId(), new DeferredDelete(retain, clientRequestToken)); submitted[0] = running; return existing; } StackMutationSnapshot snapshot = snapshot(existing); + existing.setClientRequestToken(clientRequestToken); startDelete(existing, retain); try { - submitted[0] = submitOperation(() -> RequestScopes.runAs(accountId, region, - () -> deleteStackResources(existing, retain, region, accountId))); + submitted[0] = submitOperation(() -> RequestScopes.runAs(accountId, region, () -> { + publishStackStatus(existing, "DELETE_IN_PROGRESS", null); + deleteStackResources(existing, retain, region, accountId); + })); } catch (AwsException e) { restore(existing, snapshot); throw e; @@ -1657,6 +1710,12 @@ public class CloudFormationService implements ResourceProvider { */ public Future continueUpdateRollback( String stackNameOrArn, List resourcesToSkip, boolean forceRollback, String region) { + return continueUpdateRollback(stackNameOrArn, resourcesToSkip, forceRollback, region, null); + } + + public Future continueUpdateRollback( + String stackNameOrArn, List resourcesToSkip, boolean forceRollback, String region, + String clientRequestToken) { validateContinueUpdateRollback(stackNameOrArn, resourcesToSkip); if (forceRollback && !resourcesToSkip.isEmpty()) { throw new AwsException("ValidationError", FORCE_WITH_SKIPS, 400); @@ -1677,15 +1736,18 @@ public class CloudFormationService implements ResourceProvider { throw new AwsException("ValidationError", CONTINUE_ROLLBACK_REFUSED, 400); } snapshot[0] = snapshot(existing); + existing.setClientRequestToken(clientRequestToken); existing.setStatus("UPDATE_ROLLBACK_IN_PROGRESS"); - addEvent(existing, existing.getStackName(), existing.getStackId(), + recordEvent(existing, existing.getStackName(), existing.getStackId(), "AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_IN_PROGRESS", "User Initiated"); return existing; }); try { persistStack(stack); - return submitOperation(() -> RequestScopes.runAs(accountId, region, - () -> resumeUpdateRollback(stack, skips, forceRollback, region))); + return submitOperation(() -> RequestScopes.runAs(accountId, region, () -> { + publishStackStatus(stack, "UPDATE_ROLLBACK_IN_PROGRESS", "User Initiated"); + resumeUpdateRollback(stack, skips, forceRollback, region); + })); } catch (AwsException e) { if ("LimitExceededException".equals(e.getErrorCode())) { Stack restored = restoreStack(accountId, stackName, region, snapshot[0]); @@ -2622,10 +2684,12 @@ public class CloudFormationService implements ResourceProvider { return; } - stack.setStatus("CREATE_COMPLETE"); - stack.setLastUpdatedTime(now()); + // Recorded before the status, as the failed paths do: once the status is terminal another + // operation may take the stack and its token, and this event carries this operation's. addEvent(stack, stack.getStackName(), stack.getStackId(), "AWS::CloudFormation::Stack", "CREATE_COMPLETE", null); + stack.setLastUpdatedTime(now()); + stack.setStatus("CREATE_COMPLETE"); persistStack(stack); LOG.infov("Stack {0} execution complete: CREATE_COMPLETE", stack.getStackName()); @@ -2693,7 +2757,8 @@ public class CloudFormationService implements ResourceProvider { Set attemptedResourceIds) { LOG.warnv("Stack {0} resource {1} failed: {2}", stack.getStackName(), failedResource.getLogicalId(), failedResource.getStatusReason()); - rollbackFailedExecution(stack, region, isCreate, rollbackReason(isCreate, failedResource), previousState, + rollbackFailedExecution(stack, region, isCreate, + rollbackReason(isCreate && stack.getParentId() == null, failedResource), previousState, attemptedResourceIds); } @@ -2707,7 +2772,14 @@ public class CloudFormationService implements ResourceProvider { Set attemptedResourceIds) { stack.setStatusReason(reason); - if (isCreate) { + if (isCreate && stack.getParentId() != null) { + // CloudFormation reports a nested stack's failed create as CREATE_FAILED and its rollback + // as the delete its parent's rollback gives it; the nested stack has no ROLLBACK_* status. + addEvent(stack, stack.getStackName(), stack.getStackId(), + "AWS::CloudFormation::Stack", "CREATE_FAILED", reason); + stack.setLastUpdatedTime(now()); + stack.setStatus("CREATE_FAILED"); + } else if (isCreate) { addEvent(stack, stack.getStackName(), stack.getStackId(), "AWS::CloudFormation::Stack", "ROLLBACK_IN_PROGRESS", reason); stack.setStatus("ROLLBACK_IN_PROGRESS"); @@ -2875,11 +2947,11 @@ public class CloudFormationService implements ResourceProvider { .collect(java.util.stream.Collectors.joining(", ")) + "]."; } - stack.setStatus("UPDATE_COMPLETE"); - stack.setStatusReason(statusReason); - stack.setLastUpdatedTime(now()); addEvent(stack, stack.getStackName(), stack.getStackId(), "AWS::CloudFormation::Stack", "UPDATE_COMPLETE", statusReason); + stack.setStatusReason(statusReason); + stack.setLastUpdatedTime(now()); + stack.setStatus("UPDATE_COMPLETE"); persistStack(stack); LOG.infov("Stack {0} execution complete: UPDATE_COMPLETE", stack.getStackName()); } @@ -2918,11 +2990,14 @@ public class CloudFormationService implements ResourceProvider { "Stack [" + child.getStackId() + "] cannot be deleted while TerminationProtection is enabled", 400); } + // A child in CREATE_FAILED is deleted as the rollback of its create, so what + // RetainExceptOnCreate marks goes with it, as it does when a root rolls back. + boolean createRollback = "CREATE_FAILED".equals(child.getStatus()); child.setRetainResources(List.of()); child.setStatus("DELETE_IN_PROGRESS"); addEvent(child, child.getStackName(), child.getStackId(), "AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null); - deleteStackResources(child, region, accountId); + deleteStackResources(child, List.of(), region, accountId, createRollback); } else { dispatcher.delete(resource, region); } @@ -2986,7 +3061,7 @@ public class CloudFormationService implements ResourceProvider { stack, previousState.resources(), owed, region); stack.setUpdateRollbackResourceIds(List.copyOf(rollbackFailures)); finishUpdateRollback(stack, region, previousState, rollbackFailures, - forceRollback && !skips.isEmpty() ? FORCED_ROLLBACK_COMPLETE_REASON : null); + forceRollback && !skips.isEmpty() ? FORCED_ROLLBACK_COMPLETE_REASON : null, false); } catch (Exception e) { // Nobody reads this worker's future: a stack left UPDATE_ROLLBACK_IN_PROGRESS here could // never be continued. The snapshot and the resources still owed a rollback are kept. @@ -3044,14 +3119,15 @@ public class CloudFormationService implements ResourceProvider { List rollbackFailures = rollbackUpdatedResources( stack, previousState.resources(), attemptedResourceIds, region); - finishUpdateRollback(stack, region, previousState, rollbackFailures, null); + finishUpdateRollback(stack, region, previousState, rollbackFailures, null, true); } /** * Ends an update rollback, the first one and every ContinueUpdateRollback retry alike: restores * the parameters, outputs and exports, and the template once every resource rolled back, then * settles the stack in UPDATE_ROLLBACK_COMPLETE, with {@code completionReason} as its reason, or - * UPDATE_ROLLBACK_FAILED. A rollback that fails keeps the snapshot and the resources still owed + * UPDATE_ROLLBACK_FAILED. The first rollback reports UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS on + * the way, as CloudFormation was read to; a retry was not read. A rollback that fails keeps the snapshot and the resources still owed * a rollback on the stack for a retry. */ private void finishUpdateRollback( @@ -3059,7 +3135,8 @@ public class CloudFormationService implements ResourceProvider { String region, StackUpdateSnapshot previousState, List rollbackFailures, - String completionReason) { + String completionReason, + boolean reportsCleanup) { List owedResourceIds = List.copyOf(rollbackFailures); // Parameters are independent of resource-rollback outcome - always restore them to the last // successfully deployed values, even when resource rollback itself fails and the stack lands @@ -3091,6 +3168,11 @@ public class CloudFormationService implements ResourceProvider { if (rollbackFailures.isEmpty()) { stack.setUpdateRollbackSnapshot(null); stack.setUpdateRollbackResourceIds(null); + if (reportsCleanup) { + addEvent(stack, stack.getStackName(), stack.getStackId(), + "AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", null); + stack.setStatus("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS"); + } // Reason and event before the status, which is the volatile publishing write. stack.setStatusReason(completionReason); addEvent(stack, stack.getStackName(), stack.getStackId(), @@ -3958,6 +4040,15 @@ public class CloudFormationService implements ResourceProvider { /** Deletes the stack's resources, except those {@code retainResources} names or a policy retains. */ void deleteStackResources(Stack stack, List retainResources, String region, String accountId) { + deleteStackResources(stack, retainResources, region, accountId, false); + } + + /** + * As {@link #deleteStackResources(Stack, List, String, String)}; {@code createRollback} says the + * delete rolls back the stack's create, which {@code RetainExceptOnCreate} does not survive. + */ + private void deleteStackResources(Stack stack, List retainResources, String region, String accountId, + boolean createRollback) { try { List resources = resourcesInCreationOrder(stack, region); Collections.reverse(resources); // Dependents go before what they depend on @@ -3981,7 +4072,7 @@ public class CloudFormationService implements ResourceProvider { if (resource.getPhysicalId() == null || !isDeletableOnStackDelete(resource)) { continue; } - if (skipRetainedResource(stack, resource, false)) { + if (skipRetainedResource(stack, resource, createRollback)) { continue; } addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(), @@ -4622,9 +4713,14 @@ public class CloudFormationService implements ResourceProvider { if (childCreate) { childStack = newStack(childStackName, newStackId(childStackName, region, accountId), region, accountId); + childStack.setParentId(parentStack.getStackId()); childStack.setStatus("CREATE_IN_PROGRESS"); stacks.put(stackKey(accountId, childStackName, region), childStack); + } else { + childStack.setStatus("UPDATE_IN_PROGRESS"); } + addEvent(childStack, childStack.getStackName(), childStack.getStackId(), + "AWS::CloudFormation::Stack", childCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null); if (!childCreate) { resource.getAttributes().put(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR, @@ -4786,6 +4882,21 @@ public class CloudFormationService implements ResourceProvider { private void addEvent(Stack stack, String logicalId, String physicalId, String resourceType, String status, String reason) { + recordEvent(stack, logicalId, physicalId, resourceType, status, reason); + // A stack's own record: a parent's record of a nested stack has the resource's logical id. + if (stack.getStackName().equals(logicalId) && stack.getStackId().equals(physicalId)) { + publishStackStatus(stack, status, reason); + } + } + + /** + * Records the event without sending it to the bus. The status an operation starts with is + * recorded under the stack's lock before the operation is submitted, and the executor may refuse + * it; the operation then sends that status as its first act, so a rule never sees a start that + * does not run. + */ + private void recordEvent(Stack stack, String logicalId, String physicalId, + String resourceType, String status, String reason) { StackEvent event = new StackEvent(); event.setStackId(stack.getStackId()); event.setStackName(stack.getStackName()); @@ -4797,6 +4908,12 @@ public class CloudFormationService implements ResourceProvider { stack.getEvents().add(event); } + private void publishStackStatus(Stack stack, String status, String reason) { + if (eventPublisher != null) { + eventPublisher.stackStatusChanged(stack, ownerAccount(stack), status, reason); + } + } + private Stack getStackOrThrow(String stackNameOrArn, String region) { return getStackOrThrow(stackNameOrArn, region, currentAccount()); } diff --git a/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java b/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java index 7889282ecf..ba8ccf29fc 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java +++ b/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java @@ -44,6 +44,13 @@ public class Stack { */ private volatile String status = "CREATE_IN_PROGRESS"; private String statusReason; + /** The stack that nests this one; null for a root stack. */ + private String parentId; + /** + * The ClientRequestToken of this stack's current operation, null when it was given none. A nested + * stack never has one. Set before the operation's first record and read on its worker thread. + */ + private volatile String clientRequestToken; private Instant creationTime = Instant.now(); private Instant lastUpdatedTime; /** Set once the stack reaches DELETE_COMPLETE; null for every stack that is still there. */ @@ -99,6 +106,12 @@ public class Stack { public void setStatus(String status) { this.status = status; } public String getStatusReason() { return statusReason; } public void setStatusReason(String statusReason) { this.statusReason = statusReason; } + public String getParentId() { return parentId; } + public void setParentId(String parentId) { this.parentId = parentId; } + @JsonIgnore + public String getClientRequestToken() { return clientRequestToken; } + @JsonIgnore + public void setClientRequestToken(String clientRequestToken) { this.clientRequestToken = clientRequestToken; } public Instant getCreationTime() { return creationTime; } public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } public Instant getLastUpdatedTime() { return lastUpdatedTime; } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java index b455a56bb6..9d68d9100a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java @@ -837,6 +837,69 @@ class CloudFormationDeletionPolicyIntegrationTest { } } + /** + * A nested stack whose create fails ends in CREATE_FAILED and is deleted by its parent's rollback. + * That delete rolls the child's create back, so a resource marked RetainExceptOnCreate goes, as + * it does when a root rolls back, while Retain keeps its resource. + */ + @Test + void rollingBackAFailedNestedCreateDeletesRetainExceptOnCreateButKeepsRetain() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String keptBucket = "cfn-nested-rollback-retain-" + suffix; + String rolledBackBucket = "cfn-nested-rollback-reoc-" + suffix; + given().when().put("/nested-stack-templates").then().statusCode(200); + String childTemplate = """ + { + "Resources": { + "KeptBucket": { + "Type": "AWS::S3::Bucket", + "DeletionPolicy": "Retain", + "Properties": { "BucketName": "%s" } + }, + "RolledBackBucket": { + "Type": "AWS::S3::Bucket", + "DeletionPolicy": "RetainExceptOnCreate", + "DependsOn": "KeptBucket", + "Properties": { "BucketName": "%s" } + }, + "BadSecret": { + "Type": "AWS::SecretsManager::Secret", + "DependsOn": "RolledBackBucket", + "Properties": { + "Name": "bad-secret-nested-policy-%s", + "SecretString": "explicit", + "GenerateSecretString": { "PasswordLength": 32 } + } + } + } + } + """.formatted(keptBucket, rolledBackBucket, suffix); + given().contentType("application/json").body(childTemplate).when() + .put("/nested-stack-templates/child-policy-" + suffix + ".json"); + + String stackName = "parent-policy-" + suffix; + String template = """ + { + "Resources": { + "ChildStack": { + "Type": "AWS::CloudFormation::Stack", + "Properties": { "TemplateURL": "http://localhost/nested-stack-templates/child-policy-%s.json" } + } + } + } + """.formatted(suffix); + + String parentStackId = createStack(stackName, template); + try { + awaitStackStatus(parentStackId, "ROLLBACK_COMPLETE"); + cfnQuery("DescribeStacks", stackName + "-ChildStack").then().statusCode(400); + assertBucketExists(keptBucket); + assertBucketDeleted(rolledBackBucket); + } finally { + deleteStack(stackName); + } + } + @Test void createChangeSet_nestedStackPreExistingLogGroup_rollsBackParentStack() throws Exception { String suffix = Long.toString(System.nanoTime(), 36); @@ -919,7 +982,7 @@ class CloudFormationDeletionPolicyIntegrationTest { assertThat(events, containsString("CREATE_FAILED")); assertThat(events, containsString("Nested stack " + stackName + "-ChildStack failed: The following resource(s) failed to create: [MyLogGroup]." - + " Rollback requested by user.")); + + "")); } finally { deleteStack(stackName); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventPublisherTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventPublisherTest.java new file mode 100644 index 0000000000..042200c730 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventPublisherTest.java @@ -0,0 +1,115 @@ +package io.floci.aws.services.cloudformation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.cloudformation.model.Stack; +import io.floci.aws.services.eventbridge.EventBridgeService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +class CloudFormationEventPublisherTest { + + private static final String STACK_ID = "arn:aws:cloudformation:us-east-1:000000000000:stack/s/1"; + private static final long DELIVERY_TIMEOUT_MILLIS = 5_000; + + private final EventBridgeService eventBridge = mock(EventBridgeService.class); + private final CloudFormationEventPublisher publisher = + new CloudFormationEventPublisher(eventBridge, new ObjectMapper()); + + @BeforeEach + void start() { + publisher.start(); + } + + @AfterEach + void stop() { + publisher.stop(); + } + + private static Stack stackInStatus(String status) { + Stack stack = new Stack(); + stack.setStackId(STACK_ID); + stack.setRegion("us-east-1"); + stack.setStatus(status); + return stack; + } + + private static String detailWith(String status) { + return contains("\"status\":\"" + status + "\""); + } + + private void awaitWorker(Thread.State state) { + await().atMost(DELIVERY_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).until(() -> publisher.workerState() == state); + } + + @Test + void anEventRecordedBeforeItsStatusWriteWaitsForThatWrite() { + Stack stack = stackInStatus("UPDATE_IN_PROGRESS"); + + publisher.stackStatusChanged(stack, "000000000000", "UPDATE_COMPLETE", null); + + awaitWorker(Thread.State.TIMED_WAITING); // sleeping in awaitStatusWrite + verify(eventBridge, never()).publishServiceEvent(anyString(), anyString(), anyString(), + anyString(), anyString()); + stack.setStatus("UPDATE_COMPLETE"); + verify(eventBridge, timeout(DELIVERY_TIMEOUT_MILLIS)).publishServiceEvent( + eq(CloudFormationEventPublisher.SOURCE), eq(CloudFormationEventPublisher.DETAIL_TYPE), + detailWith("UPDATE_COMPLETE"), eq(STACK_ID), eq("us-east-1")); + } + + @Test + void anEventStillQueuedWhenFlociStopsIsDropped() { + Stack stack = stackInStatus("UPDATE_IN_PROGRESS"); + publisher.stackStatusChanged(stack, "000000000000", "UPDATE_COMPLETE", null); + + publisher.stop(); + stack.setStatus("UPDATE_COMPLETE"); + + awaitWorker(Thread.State.TERMINATED); + verify(eventBridge, never()).publishServiceEvent(anyString(), anyString(), anyString(), + anyString(), anyString()); + } + + @Test + void aStatusLeftUnwrittenDoesNotHoldUpTheEventsBehindIt() { + Stack stack = stackInStatus("UPDATE_IN_PROGRESS"); + + publisher.stackStatusChanged(stack, "000000000000", "UPDATE_COMPLETE", null); + + verify(eventBridge, timeout(DELIVERY_TIMEOUT_MILLIS)).publishServiceEvent(anyString(), anyString(), + detailWith("UPDATE_COMPLETE"), anyString(), anyString()); + } + + @Test + void eventsAreDeliveredInTheOrderRecordedAndAFailureStopsNothing() { + doThrow(new IllegalStateException("bus is down")).when(eventBridge).publishServiceEvent( + anyString(), anyString(), detailWith("CREATE_IN_PROGRESS"), anyString(), anyString()); + Stack stack = stackInStatus("CREATE_IN_PROGRESS"); + + publisher.stackStatusChanged(stack, "000000000000", "CREATE_IN_PROGRESS", null); + stack.setStatus("CREATE_COMPLETE"); + publisher.stackStatusChanged(stack, "000000000000", "CREATE_COMPLETE", null); + + verify(eventBridge, timeout(DELIVERY_TIMEOUT_MILLIS)).publishServiceEvent(anyString(), anyString(), + detailWith("CREATE_COMPLETE"), anyString(), anyString()); + InOrder order = inOrder(eventBridge); + order.verify(eventBridge).publishServiceEvent(anyString(), anyString(), detailWith("CREATE_IN_PROGRESS"), + anyString(), anyString()); + order.verify(eventBridge).publishServiceEvent(anyString(), anyString(), detailWith("CREATE_COMPLETE"), + anyString(), anyString()); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationServiceRollbackTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationServiceRollbackTest.java index f053b81cac..e4e2a37a54 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationServiceRollbackTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationServiceRollbackTest.java @@ -452,8 +452,10 @@ class CloudFormationServiceRollbackTest { service.rollbackFailedExecution(stack, REGION, false, added, previousState, new LinkedHashSet<>(List.of("Dup"))); - assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"), stack.statuses()); - assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"), stackEventStatuses(stack)); + assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", + "UPDATE_ROLLBACK_COMPLETE"), stack.statuses()); + assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", + "UPDATE_ROLLBACK_COMPLETE"), stackEventStatuses(stack)); stack.assertEachStatusFollowsItsEvent(); assertEquals("The following resource(s) failed to create: [Dup].", stack.writes().getFirst().reason()); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackStatusEventsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackStatusEventsIntegrationTest.java new file mode 100644 index 0000000000..7d34f619ef --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackStatusEventsIntegrationTest.java @@ -0,0 +1,596 @@ +package io.floci.aws.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.services.lambda.LambdaService; +import io.floci.aws.testing.CfnRequests; +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.EventRuleQueue; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.StepFunctionsExecutions; +import io.floci.aws.testing.StepFunctionsRequests; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasItems; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * What a rule on the default bus receives as a stack's status changes, against what CloudFormation + * sent a rule on 2026-10-30 for a root nesting one stack, through change sets and DeleteStack, each + * with a token of its own, and through a create and an update that failed in the nested stack: the + * root's events carry their operation's token, its rollback statuses included, but for + * {@code REVIEW_IN_PROGRESS}, which has no key; a nested stack's events have no key at all; and the + * root's {@code CREATE_FAILED} and any {@code UPDATE_FAILED} never reach the bus. A nested stack's + * failed create is {@code CREATE_FAILED} and then a delete. Each status arrives once. + * + *

A failure in the root's own resource with the nested stack healthy, and a delete that fails, were + * not read, and no test here asserts them. + */ +@QuarkusTest +class CloudFormationStackStatusEventsIntegrationTest { + + private static final String DETAIL_TYPE = "CloudFormation Stack Status Change"; + private static final String ALL_STATUS_CHANGES = """ + {"source": ["aws.cloudformation"], "detail-type": ["%s"]} + """.formatted(DETAIL_TYPE); + private static final String BUCKET = "stack-status-events-templates"; + private static final String CHILD_KEY = "child.json"; + private static final String CHILD_TEMPLATE = """ + { + "Parameters": {"Value": {"Type": "String"}}, + "Resources": { + "ChildTopic": { + "Type": "AWS::SNS::Topic", + "Properties": {"DisplayName": {"Ref": "Value"}} + } + } + } + """; + private static final String FAILING_CHILD_KEY = "failing-child.json"; + private static final String FAILING_CHILD_TEMPLATE = """ + { + "Parameters": {"Value": {"Type": "String"}}, + "Resources": { + "Broken": {"Type": "AWS::CloudFormation::Stack", "Properties": {}} + } + } + """; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String HELD_SERVICE_TOKEN = + "arn:aws:lambda:us-east-1:000000000000:function:status-events-held-create"; + + @InjectMock + LambdaService lambdaService; + + /** The Create of {@link #heldTemplate()}'s custom resource, held until the test releases it. */ + private CustomResourceProbe.Hold heldCreate; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void holdTheCustomResourcesCreate() { + heldCreate = CustomResourceProbe.stub(lambdaService, HELD_SERVICE_TOKEN, "status-events-held-probe") + .hold(event -> "Create".equals(event.path("RequestType").asText())); + } + + @AfterEach + void releaseHeldCreate() { + heldCreate.release(); + } + + @BeforeEach + void uploadChildTemplate() { + given().when().put("/" + BUCKET).then().statusCode(200); + given().body(CHILD_TEMPLATE).when().put("/" + BUCKET + "/" + CHILD_KEY).then().statusCode(200); + given().body(FAILING_CHILD_TEMPLATE).when().put("/" + BUCKET + "/" + FAILING_CHILD_KEY).then().statusCode(200); + } + + @Test + void changeSetsAndDeleteCarryEachOperationsTokenOnTheRootAndNoneOnTheNestedStack() throws Exception { + String root = uniqueName("root"); + String rootId; + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) { + rootId = createChangeSet(root, "CREATE", "create", rootTemplate("first")); + executeChangeSet(root, "create", "a"); + CfnStackWaits.awaitStatus(root, "CREATE_COMPLETE"); + + createChangeSet(root, "UPDATE", "update", rootTemplate("second")); + executeChangeSet(root, "update", "b"); + CfnStackWaits.awaitStatus(root, "UPDATE_COMPLETE"); + + CfnRequests.cfn("DeleteStack", root).formParam("ClientRequestToken", "c") + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(rootId, "DELETE_COMPLETE"); + + List events = awaitEvents(queue, rootId, "DELETE_COMPLETE"); + List rootEvents = naming(events, rootId); + Map> tokens = tokensByStatus(rootEvents); + + assertEquals(Set.of(NO_TOKEN), tokens.get("REVIEW_IN_PROGRESS")); + assertEquals(Set.of("a"), tokens.get("CREATE_IN_PROGRESS")); + assertEquals(Set.of("a"), tokens.get("CREATE_COMPLETE")); + assertEquals(Set.of("b"), tokens.get("UPDATE_IN_PROGRESS")); + assertEquals(Set.of("b"), tokens.get("UPDATE_COMPLETE")); + assertEquals(Set.of("c"), tokens.get("DELETE_IN_PROGRESS")); + assertEquals(Set.of("c"), tokens.get("DELETE_COMPLETE")); + assertEachStatusOnce(rootEvents); + + List nested = awaitNested(queue, events, root, "DELETE_COMPLETE"); + assertThat(tokensByStatus(nested).keySet(), hasItems("CREATE_IN_PROGRESS", "CREATE_COMPLETE", + "UPDATE_IN_PROGRESS", "UPDATE_COMPLETE", "DELETE_IN_PROGRESS", "DELETE_COMPLETE")); + assertNoTokenOn(nested); + assertEachStatusOnce(nested); + } + } + + /** + * A DeleteStack that lands while the create still runs waits for it, and its statuses carry the + * delete's token, not the create's, which the stack still held when the delete began. + */ + @Test + void aDeleteLandingMidCreateCarriesItsOwnToken() throws Exception { + String stack = uniqueName("mid-create"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) { + String stackId = createChangeSet(stack, "CREATE", "create", heldTemplate()); + executeChangeSet(stack, "create", "create-token"); + assertTrue(heldCreate.awaitRequest(10, TimeUnit.SECONDS), "the custom resource was never created"); + + CfnRequests.cfn("DeleteStack", stack).formParam("ClientRequestToken", "delete-token") + .when().post("/").then().statusCode(200); + heldCreate.release(); + CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE"); + + List events = naming(awaitEvents(queue, stackId, "DELETE_COMPLETE"), stackId); + Map> tokens = tokensByStatus(events); + assertEquals(Set.of("create-token"), tokens.get("CREATE_IN_PROGRESS")); + assertEquals(Set.of("delete-token"), tokens.get("DELETE_IN_PROGRESS")); + assertEquals(Set.of("delete-token"), tokens.get("DELETE_COMPLETE")); + assertEachStatusOnce(events); + } + } + + @Test + void anEventIsInTheShapeRead() throws Exception { + String stack = uniqueName("shape"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) { + String stackId = createStack(stack, "shape-token", "first"); + + JsonNode complete = withStatus(naming(awaitEvents(queue, stackId, "CREATE_COMPLETE"), stackId), + "CREATE_COMPLETE").get(0); + + assertEquals("aws.cloudformation", complete.path("source").asText()); + assertEquals(DETAIL_TYPE, complete.path("detail-type").asText()); + assertEquals("000000000000", complete.path("account").asText()); + assertEquals("us-east-1", complete.path("region").asText()); + assertEquals(1, complete.path("resources").size()); + assertEquals(stackId, complete.path("resources").get(0).asText()); + JsonNode detail = complete.path("detail"); + assertEquals(stackId, detail.path("stack-id").asText()); + assertEquals("shape-token", detail.path("client-request-token").asText()); + assertEquals("CREATE_COMPLETE", detail.path("status-details").path("status").asText()); + assertEquals("", detail.path("status-details").path("detailed-status").asText("absent")); + assertEquals("", detail.path("status-details").path("status-reason").asText("absent")); + } + } + + /** + * The root's topic and its record of the nested stack both reach CREATE_COMPLETE on the root, so a + * resource's record sent to the bus would show as that status more than once. + */ + @Test + void aResourcesProgressSendsNothing() throws Exception { + String root = uniqueName("resources"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) { + String rootId = createStack(root, "resources-token", "first"); + + List events = awaitEvents(queue, rootId, "CREATE_COMPLETE"); + + assertEquals(1, withStatus(naming(events, rootId), "CREATE_COMPLETE").size(), () -> "events: " + events); + assertEquals(1, withStatus(naming(events, rootId), "CREATE_IN_PROGRESS").size(), () -> "events: " + events); + List stackNames = new ArrayList<>(); + for (JsonNode event : withStatus(events, "CREATE_COMPLETE")) { + assertEquals(event.path("detail").path("stack-id").asText(), event.path("resources").get(0).asText()); + stackNames.add(event.path("detail").path("stack-id").asText().split("/")[1]); + } + assertThat(stackNames, containsInAnyOrder(root + "-Nested", root)); + } + } + + @Test + void createUpdateAndDeleteStackCarryTheirTokens() throws Exception { + String stack = uniqueName("direct"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) { + String stackId = createStack(stack, "direct-create", "first"); + CfnRequests.cfn("UpdateStack", stack) + .formParam("TemplateBody", rootTemplate("second")) + .formParam("ClientRequestToken", "direct-update") + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE"); + CfnRequests.cfn("DeleteStack", stack).formParam("ClientRequestToken", "direct-delete") + .when().post("/").then().statusCode(200); + + Map> tokens = + tokensByStatus(naming(awaitEvents(queue, stackId, "DELETE_COMPLETE"), stackId)); + + assertEquals(Set.of("direct-create"), tokens.get("CREATE_IN_PROGRESS")); + assertEquals(Set.of("direct-create"), tokens.get("CREATE_COMPLETE")); + assertEquals(Set.of("direct-update"), tokens.get("UPDATE_IN_PROGRESS")); + assertEquals(Set.of("direct-update"), tokens.get("UPDATE_COMPLETE")); + assertEquals(Set.of("direct-delete"), tokens.get("DELETE_IN_PROGRESS")); + assertEquals(Set.of("direct-delete"), tokens.get("DELETE_COMPLETE")); + } + } + + @Test + void anOperationGivenNoTokenDoesNotCarryTheLastOnes() throws Exception { + String stack = uniqueName("no-token"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) { + String stackId = createStack(stack, "had-a-token", "first"); + CfnRequests.cfn("UpdateStack", stack) + .formParam("TemplateBody", rootTemplate("second")) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE"); + + Map> tokens = + tokensByStatus(naming(awaitEvents(queue, stackId, "UPDATE_COMPLETE"), stackId)); + + assertEquals(Set.of("had-a-token"), tokens.get("CREATE_COMPLETE")); + assertEquals(Set.of(NO_TOKEN), tokens.get("UPDATE_IN_PROGRESS")); + assertEquals(Set.of(NO_TOKEN), tokens.get("UPDATE_COMPLETE")); + } + } + + @Test + void aPatternOnTheStatusSeesOnlyThatStatus() throws Exception { + String stack = uniqueName("pattern"); + String pattern = """ + {"source": ["aws.cloudformation"], "detail-type": ["%s"], + "detail": {"status-details": {"status": ["UPDATE_COMPLETE"]}}} + """.formatted(DETAIL_TYPE); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, pattern)) { + String stackId = createStack(stack, "pattern-create", "first"); + CfnRequests.cfn("UpdateStack", stack) + .formParam("TemplateBody", rootTemplate("second")) + .formParam("ClientRequestToken", "pattern-update") + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE"); + + List events = awaitEvents(queue, stackId, "UPDATE_COMPLETE"); + + assertEquals(Set.of("UPDATE_COMPLETE"), tokensByStatus(naming(events, stackId)).keySet()); + } + } + + @Test + void aStateMachinesTaskNamesTheDeploy() throws Exception { + String stack = uniqueName("task"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) { + String stackId = createStack(stack, "task-create", "first"); + createChangeSet(stack, "UPDATE", "by-task", rootTemplate("second")); + ObjectNode parameters = MAPPER.createObjectNode().put("StackName", stack) + .put("ChangeSetName", "by-task").put("ClientRequestToken", "swb-d1"); + ObjectNode task = MAPPER.createObjectNode().put("Type", "Task") + .put("Resource", "arn:aws:states:::aws-sdk:cloudformation:executeChangeSet") + .put("End", true); + task.set("Parameters", parameters); + ObjectNode definition = MAPPER.createObjectNode().put("StartAt", "Execute"); + definition.putObject("States").set("Execute", task); + String stateMachineArn = StepFunctionsRequests.sfn("CreateStateMachine", Map.of( + "name", stack, "definition", definition.toString(), + "roleArn", "arn:aws:iam::000000000000:role/test-role")) + .then().statusCode(200).extract().path("stateMachineArn"); + String executionArn = StepFunctionsRequests.sfn("StartExecution", + Map.of("stateMachineArn", stateMachineArn, "input", "{}")) + .then().statusCode(200).extract().path("executionArn"); + assertEquals("SUCCEEDED", + StepFunctionsExecutions.waitForTerminalState(executionArn).jsonPath().getString("status")); + CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE"); + + Map> tokens = + tokensByStatus(naming(awaitEvents(queue, stackId, "UPDATE_COMPLETE"), stackId)); + + assertEquals(Set.of("swb-d1"), tokens.get("UPDATE_COMPLETE")); + } + } + + @Test + void aFailedCreateCarriesItsTokenThroughItsRollback() throws Exception { + String root = uniqueName("failed-create"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) { + String rootId = createChangeSet(root, "CREATE", "create", rootTemplate("first", FAILING_CHILD_KEY)); + executeChangeSet(root, "create", "fc-create"); + CfnStackWaits.awaitStatus(root, "ROLLBACK_COMPLETE"); + + List events = awaitEvents(queue, rootId, "ROLLBACK_COMPLETE"); + List rootEvents = naming(events, rootId); + Map> tokens = tokensByStatus(rootEvents); + + assertEquals(Set.of(NO_TOKEN), tokens.get("REVIEW_IN_PROGRESS")); + assertEquals(Set.of("fc-create"), tokens.get("CREATE_IN_PROGRESS")); + assertEquals(Set.of("fc-create"), tokens.get("ROLLBACK_IN_PROGRESS")); + assertEquals(Set.of("fc-create"), tokens.get("ROLLBACK_COMPLETE")); + assertEquals(Set.of("REVIEW_IN_PROGRESS", "CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"), + tokens.keySet()); + assertEachStatusOnce(rootEvents); + assertFalse(withStatus(rootEvents, "ROLLBACK_IN_PROGRESS").get(0).path("detail").path("status-details") + .path("status-reason").asText().isEmpty()); + List nested = nestedEvents(events, root); + assertNoTokenOn(nested); + assertEquals(Set.of("CREATE_IN_PROGRESS", "CREATE_FAILED", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"), + tokensByStatus(nested).keySet()); + assertEachStatusOnce(nested); + + CfnRequests.cfn("DeleteStack", root).formParam("ClientRequestToken", "fc-delete") + .when().post("/").then().statusCode(200); + assertEquals(Set.of("fc-delete"), tokensByStatus(naming(awaitEvents(queue, rootId, "DELETE_COMPLETE"), rootId)) + .get("DELETE_COMPLETE")); + } + } + + @Test + void aFailedUpdateCarriesItsTokenThroughItsRollback() throws Exception { + String root = uniqueName("failed-update"); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) { + String rootId = createStack(root, "fu-create", "first"); + createChangeSet(root, "UPDATE", "update", rootTemplate("second", FAILING_CHILD_KEY)); + executeChangeSet(root, "update", "fu-update"); + CfnStackWaits.awaitStatus(root, "UPDATE_ROLLBACK_COMPLETE"); + + List events = awaitEvents(queue, rootId, "UPDATE_ROLLBACK_COMPLETE"); + Map> tokens = tokensByStatus(naming(events, rootId)); + + assertEquals(Set.of("fu-create"), tokens.get("CREATE_COMPLETE")); + assertEquals(Set.of("fu-update"), tokens.get("UPDATE_IN_PROGRESS")); + assertEquals(Set.of("fu-update"), tokens.get("UPDATE_ROLLBACK_IN_PROGRESS")); + assertEquals(Set.of("fu-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS")); + assertEquals(Set.of("fu-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE")); + assertEquals(List.of(), withStatus(events, "UPDATE_FAILED")); + assertEachStatusOnce(naming(events, rootId)); + List nested = nestedEvents(events, root); + assertNoTokenOn(nested); + assertThat(tokensByStatus(nested).keySet(), hasItems("UPDATE_IN_PROGRESS", "UPDATE_ROLLBACK_IN_PROGRESS", + "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE")); + assertEachStatusOnce(nested); + } + } + + /** + * A parameter that cannot be fetched fails the update at execute, before any resource: the same + * rollback as a failure in a resource, so the same statuses on the bus. Delivery is in order, so + * an UPDATE_FAILED sent would be on the queue ahead of the rollback's last status. + */ + @Test + void anUpdateFailingOutsideAResourceSendsNoUpdateFailed() throws Exception { + String stack = uniqueName("failed-execute"); + String template = rootTemplate("first").replaceFirst("\\{", """ + { + "Parameters": { + "Missing": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/stack-status-events/no-such-parameter" + } + }, + """); + try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) { + String stackId = createStack(stack, "fe-create", "first"); + createChangeSet(stack, "UPDATE", "update", template); + executeChangeSet(stack, "update", "fe-update"); + CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE"); + + List rootEvents = naming(awaitEvents(queue, stackId, "UPDATE_ROLLBACK_COMPLETE"), stackId); + Map> tokens = tokensByStatus(rootEvents); + + assertEquals(List.of(), withStatus(rootEvents, "UPDATE_FAILED")); + assertEquals(Set.of("fe-update"), tokens.get("UPDATE_IN_PROGRESS")); + assertEquals(Set.of("fe-update"), tokens.get("UPDATE_ROLLBACK_IN_PROGRESS")); + assertEquals(Set.of("fe-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS")); + assertEquals(Set.of("fe-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE")); + assertEachStatusOnce(rootEvents); + } + } + + /** Green with or without the events: it keeps delivery from ever failing the stack. */ + @Test + void aTargetThatCannotBeDeliveredToLeavesTheStackAlone() { + String stack = uniqueName("undeliverable"); + String events = "application/x-amz-json-1.1"; + given().header("X-Amz-Target", "AWSEvents.PutRule").contentType(events) + .body(MAPPER.createObjectNode().put("Name", stack).put("EventPattern", ALL_STATUS_CHANGES).toString()) + .when().post("/").then().statusCode(200); + ObjectNode targets = MAPPER.createObjectNode().put("Rule", stack); + targets.putArray("Targets").addObject().put("Id", "1") + .put("Arn", "arn:aws:sqs:us-east-1:000000000000:no-such-queue-" + stack); + given().header("X-Amz-Target", "AWSEvents.PutTargets").contentType(events).body(targets.toString()) + .when().post("/").then().statusCode(200); + try { + createStack(stack, "undeliverable-token", "first"); + } finally { + ObjectNode remove = MAPPER.createObjectNode().put("Rule", stack); + remove.putArray("Ids").add("1"); + given().header("X-Amz-Target", "AWSEvents.RemoveTargets").contentType(events).body(remove.toString()) + .when().post("/").then().statusCode(200); + given().header("X-Amz-Target", "AWSEvents.DeleteRule").contentType(events) + .body(MAPPER.createObjectNode().put("Name", stack).toString()) + .when().post("/").then().statusCode(200); + } + } + + private static final String NO_TOKEN = "(no key)"; + + private static String uniqueName(String prefix) { + return "status-" + prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + private static String rootTemplate(String childValue) { + return rootTemplate(childValue, CHILD_KEY); + } + + private static String rootTemplate(String childValue, String childKey) { + return """ + { + "Resources": { + "RootTopic": { + "Type": "AWS::SNS::Topic", + "Properties": {"DisplayName": "root"} + }, + "Nested": { + "Type": "AWS::CloudFormation::Stack", + "Properties": { + "TemplateURL": "https://s3.amazonaws.com/%2$s/%3$s", + "Parameters": {"Value": "%1$s"} + } + } + } + } + """.formatted(childValue, BUCKET, childKey); + } + + private static String createStack(String name, String token, String childValue) { + String xml = CfnRequests.cfn("CreateStack", name) + .formParam("TemplateBody", rootTemplate(childValue)) + .formParam("ClientRequestToken", token) + .when().post("/").then().statusCode(200).extract().asString(); + CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE"); + return XmlPath.from(xml).getString("**.find { it.name() == 'StackId' }"); + } + + /** A stack whose create holds at its custom resource until {@link #heldCreate} is released. */ + private static String heldTemplate() { + return """ + { + "Resources": { + "Probe": {"Type": "Custom::HeldCreate", "Properties": {"ServiceToken": "%s"}} + } + } + """.formatted(HELD_SERVICE_TOKEN); + } + + private static String createChangeSet(String stack, String type, String changeSet, String template) { + String xml = CfnRequests.cfn("CreateChangeSet", stack) + .formParam("ChangeSetName", changeSet) + .formParam("ChangeSetType", type) + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200).extract().asString(); + return XmlPath.from(xml).getString("**.find { it.name() == 'StackId' }"); + } + + private static void executeChangeSet(String stack, String changeSet, String token) { + CfnRequests.cfn("ExecuteChangeSet", stack) + .formParam("ChangeSetName", changeSet) + .formParam("ClientRequestToken", token) + .when().post("/").then().statusCode(200); + } + + /** + * The events on the queue once {@code stackId} has sent {@code lastStatus}; the bus delivers apart + * from the stack operation, so the status DescribeStacks answers can be ahead of the queue. Every + * event the queue has held by then is returned, whichever stack it names. + */ + private static List awaitEvents(EventRuleQueue queue, String stackId, String lastStatus) + throws Exception { + List events = new ArrayList<>(); + awaitEvents(queue, events, event -> stackId.equals(stackId(event)), stackId, lastStatus); + return events; + } + + /** The nested stack's events, waiting for {@code lastStatus} since delivery runs in order behind the root's. */ + private static List awaitNested(EventRuleQueue queue, List events, String root, + String lastStatus) throws Exception { + return awaitEvents(queue, events, event -> isNested(event, root), "the nested stack of " + root, lastStatus); + } + + /** + * Drains the queue into {@code events} until one of {@code those} carries {@code lastStatus}, and + * returns the events that are {@code those}. + */ + private static List awaitEvents(EventRuleQueue queue, List events, Predicate those, + String whose, String lastStatus) throws Exception { + long deadline = System.currentTimeMillis() + 10_000; + while (System.currentTimeMillis() < deadline) { + events.addAll(queue.drain()); + List matching = events.stream().filter(those).toList(); + if (matching.stream().anyMatch(event -> lastStatus.equals(status(event)))) { + return matching; + } + Thread.sleep(50); + } + fail("No " + DETAIL_TYPE + " event with status " + lastStatus + " for " + whose + " within ten seconds; " + + "the queue held: " + events); + return List.of(); + } + + private static List nestedEvents(List events, String root) { + return events.stream().filter(event -> isNested(event, root)).toList(); + } + + private static boolean isNested(JsonNode event, String root) { + return stackId(event).contains("/" + root + "-Nested/"); + } + + private static String stackId(JsonNode event) { + return event.path("detail").path("stack-id").asText(); + } + + private static void assertNoTokenOn(List nested) { + assertFalse(nested.isEmpty(), "no event named the nested stack"); + for (JsonNode event : nested) { + assertFalse(event.path("detail").has("client-request-token"), () -> "nested event: " + event); + } + } + + private static List naming(List events, String stackId) { + return events.stream() + .filter(event -> stackId.equals(event.path("detail").path("stack-id").asText())) + .toList(); + } + + private static void assertEachStatusOnce(List events) { + List statuses = events.stream().map(CloudFormationStackStatusEventsIntegrationTest::status).toList(); + assertEquals(new LinkedHashSet<>(statuses).size(), statuses.size(), () -> "statuses: " + statuses); + } + + private static List withStatus(List events, String status) { + return events.stream().filter(event -> status.equals(status(event))).toList(); + } + + private static String status(JsonNode event) { + return event.path("detail").path("status-details").path("status").asText(); + } + + /** Each status seen, with the tokens its events carried, an event with no key counting as {@link #NO_TOKEN}. */ + private static Map> tokensByStatus(List events) { + Map> tokens = new LinkedHashMap<>(); + for (JsonNode event : events) { + JsonNode detail = event.path("detail"); + tokens.computeIfAbsent(status(event), key -> new LinkedHashSet<>()) + .add(detail.has("client-request-token") ? detail.path("client-request-token").asText() : NO_TOKEN); + } + return tokens; + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/CustomResourceProbe.java b/src/test/java/io/floci/aws/services/cloudformation/CustomResourceProbe.java index 6c4d8f811e..4bc84bcc02 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CustomResourceProbe.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CustomResourceProbe.java @@ -12,6 +12,8 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Predicate; @@ -24,10 +26,33 @@ import static org.mockito.Mockito.when; * The handler of a custom resource in a stack test. It stands in for the ServiceToken Lambda on a * mocked {@link LambdaService}, keeps every request it is sent, and answers each the way a handler * does: a PUT of its result to the event's {@code ResponseURL}, SUCCESS unless {@link #failOn} names - * the request. + * the request, and only once {@link #hold} lets it, where one is set. */ final class CustomResourceProbe { + /** A request {@link #hold} keeps from its answer until the test releases it. */ + static final class Hold { + private final CountDownLatch received = new CountDownLatch(1); + private final CountDownLatch released = new CountDownLatch(1); + + /** Whether a held request has arrived within {@code timeout}. */ + boolean awaitRequest(long timeout, TimeUnit unit) throws InterruptedException { + return received.await(timeout, unit); + } + + /** Lets the held request answer. Idempotent, so an {@code @AfterEach} can call it. */ + void release() { + released.countDown(); + } + + private void keep() throws InterruptedException { + received.countDown(); + if (!released.await(10, TimeUnit.SECONDS)) { + throw new AssertionError("the test never released the held custom resource request"); + } + } + } + private static final ObjectMapper MAPPER = new ObjectMapper(); private final List events = new CopyOnWriteArrayList<>(); @@ -35,6 +60,8 @@ final class CustomResourceProbe { private volatile Function> data; private volatile Predicate failing = event -> false; private volatile String failureReason; + private volatile Predicate holding = event -> false; + private volatile Hold hold; private CustomResourceProbe(String physicalId) { this.physicalId = physicalId; @@ -64,6 +91,16 @@ final class CustomResourceProbe { failing = request; } + /** + * Holds the requests {@code request} matches before they are answered, until the returned hold is + * released, so a test can act while a stack operation waits on its custom resource. + */ + Hold hold(Predicate request) { + hold = new Hold(); + holding = request; + return hold; + } + /** Every request so far, in the order it was sent. */ List events() { return events; @@ -75,7 +112,10 @@ final class CustomResourceProbe { .findFirst().orElseThrow(() -> new AssertionError("No " + requestType + " request in " + events)); } - private void answer(JsonNode event) { + private void answer(JsonNode event) throws InterruptedException { + if (holding.test(event)) { + hold.keep(); + } ObjectNode response = MAPPER.createObjectNode(); if (failing.test(event)) { response.put("Status", "FAILED").put("Reason", failureReason);