feat(cloudformation): CDK Provider-framework custom resources and changeset/SSM param fidelity (#2688)

* feat(cloudformation): changeset diffs, stack params, SSM attributes

CDK's deploy loop reads all three: DescribeChangeSet now returns
computed Add/Modify/Remove resource changes instead of an empty list
(an empty list makes CDK skip ExecuteChangeSet on updates),
DescribeStacks echoes the stack's merged parameters, and
AWS::SSM::Parameter resources expose Value/Type/Name attributes so
Fn::GetAtt resolves the bootstrap version

(cherry picked from commit 80ac80063e84ef1be977fe625334e722cc1ed8bb)

* feat(cloudformation): resolve SSM-typed stack parameters

AWS::SSM::Parameter::Value<String> template parameters resolve through
SSM for the stack's account and region; missing parameters fail with the
real ValidationError message. Landing Zone Accelerator's security and
logging stacks depend on this typed-parameter resolution.

The IAM password-policy and S3 replication-config changes from the same
source commit ship separately in the iam and s3 branches.

(cherry picked from commit 10dbabbf5e31d763a398fc1fff16ab0484958af0)

* feat(cloudformation): drive CDK Provider framework custom resources

The CDK Provider framework defers its ResponseURL callback to a Step
Functions waiter that polls framework.isComplete on a Retry cadence until
the resource is ready. The custom-resource provisioner only waited the
synchronous single-lambda budget for a ResponseURL PUT, so the
waiter-driven PUT never landed. A framework.onEvent ServiceToken is now
awaited on a bounded async budget so that PUT is captured; onEvent-only
and single-lambda resources are unchanged.

The engine-side half of the original commit -- a Task-only Retry
implementation for the ASL executor (ErrorEquals/IntervalSeconds/
MaxAttempts/BackoffRate/MaxDelaySeconds) -- is dropped here: upstream
#2455 ("feat(sfn): support Retry policies in Task, Parallel, and Map
states") landed a broader Retry implementation independently (Task,
Parallel, and Map states; JitterStrategy; $$.State.RetryCount;
Retry-before-Catch ordering), a strict superset of what this commit
needed. The full stepfunctions suite (411 tests) is green against it
on this branch, and CustomResourceProviderFrameworkTest (a hermetic
test of the provisioner's own detect-and-wait logic, no Step Functions
involved) is unaffected by the drop.

(cherry picked from commit 5b3502d8c9dddf3766ca3f94fe7f146042dc00fd)

* docs(cloudformation): document CDK provisioning

Documents the CDK Provider-framework custom-resource support and folds
its cross-reference into upstream's existing "Retry policies" section
in step-functions.md rather than duplicating it with a separate
"State Retry" section (upstream #2455 already documents the Retry
engine itself).

* feat(cloudformation): budget custom-resource waits by idleness, not total time

The async custom-resource wait was a fixed 3-minute total budget. That is a
property of the emulator, but the time a CDK provider-framework resource needs
is a property of the work: Custom::CreateOrganizationAccounts creates exactly
one account per 15s waiter poll, so a 3-account org finishes in ~45s while a
15-account org needs ~195s. Past the budget the Lambda is guillotined mid-
success -- the accounts all exist, but the resource reports CREATE_FAILED, the
stack rolls back, and CDK's readback then surfaces the misleading "NoStack:
CloudFormationStack object does not hold a stack".

Measure idleness instead. The provisioner already embeds its callback token in
the ResponseURL it puts on every event, and the framework echoes that event into
each framework.isComplete poll, so a poll arriving at LambdaService is proof of
progress for a specific pending resource. Each poll resets the budget, which
makes the wait proportional to the work without CloudFormation needing to know
what the work is -- and a genuinely hung resource still fails after 3 idle
minutes exactly as before.

CustomResourceLiveness lives in core.common so the Lambda service can report
progress without depending on CloudFormation; the dependency already runs the
other way.

(cherry picked from commit 14087c992ebb75d109999153a9e8af7e3c2d79f4)
(cherry picked from commit 51349e4e017ed08d90e6e71212414e2f306c826b)

* fix(cloudformation): call the caller-scoped getStackOrThrow overload that exists

The changeset-diff commit re-derived onto main carried a call to a
three-arg getStackOrThrow(name, region, accountId) overload that only
existed on the account-scoping commit deliberately skipped as superseded
by upstream. Upstream's resolveStack already scopes to the caller's
account, so the two-arg form is equivalent and compiles.

* fix(cloudformation): honour an arrived custom-resource response past its budget

A synchronous custom-resource handler PUTs to the ResponseURL from inside the
invoke the provisioner is blocked on, so its response can already be delivered
by the time await() is entered. Two independent flaws then threw it away.

The idle clock started at register(), before the invoke. A provider-framework
onEvent-only handler that took 75s to return -- two nested cold container
starts -- had spent its 10s CR_RESPONSE_TIMEOUT six times over before await
was reached, so the very first deadline check was already negative. Idleness
of the wait cannot include time the handler spent working; the clock now
starts when the caller starts waiting.

The deadline guard also threw without ever consulting the future, so a
response that had completed it was discarded as a timeout. Observed on
AccessAnalyzerServiceLinkedRoleCreateServiceLinkedRoleResource: the handler
logged its response at 15:52:11.768 and the resource was failed 24ms later.
An arrived response outranks the clock.

Both are pinned by red-first tests. The existing idle-timeout guarantees are
unchanged: nothing arriving still times out, and a resource that stops
reporting liveness still dies on schedule from its last touch.

(cherry picked from commit 7dc8bbca7d47b2a029b5656a89421a556b8296be)
(cherry picked from commit 77b71b31a634ae27d7460a078b52dac250d67dc7)

* refactor(cloudformation): extract Provider-framework detection from the provisioner

The CDK Provider-framework `framework.onEvent` detection and the longer idle
budget it earns lived in CloudFormationResourceProvisioner, adding ~55 lines to a
class that is being dismantled rather than grown.

Move the concern to ProviderFrameworkDetector: it owns the two waiter marker env
vars, the best-effort environment probe, the 3-minute async budget and the test
seam that shortens it. CustomResourceResponseStore — which already owns the
idle-timeout concept via touch/await — gains an await overload that resolves the
budget for a ServiceToken and delegates to the existing one, so the provisioner
only passes the token through and appends the store's timeout detail to its
error. Behaviour is unchanged.

(cherry picked from commit 5f93439f409a32012a01b996c5edd0c29d23b260)

* fix(stepfunctions): report custom-resource liveness on waiter polls

A CDK provider-framework waiter's framework.isComplete poll is itself a
Lambda Task the state machine invokes, so it goes through
AslExecutor.invokeResource -> LambdaExecutorService directly, bypassing
LambdaService.invoke() and the liveness hook it carries. A long-but-
progressing custom resource's idle budget in CustomResourceResponseStore
ticked down as if no polls were arriving, even while they kept landing.

AslExecutor now reports liveness the same way LambdaService does: extract
the callback token from the invoke payload and touch() it before invoking.

* perf(core): avoid materializing the full payload string in tokenIn

CustomResourceLiveness.tokenIn() ran on every Lambda invoke once liveness
reporting is wired in, decoding the whole invoke payload as a UTF-8 String
even though the overwhelming majority of invokes carry no callback URL at
all. Scan the raw bytes for the ASCII "/cfn-response/" marker instead, and
only allocate a String for the small token substring when one is found.

* fix(cloudformation): compute accurate changeset resource diffs

computeChangeSetChanges never read cs.getParameters(), so an update that
only changed parameter values reported an empty diff and CDK skipped
execution, leaving the old parameter-derived config deployed. It also
diffed a SAM change set's raw template against the stack's expanded
deployed template, reporting spurious Modify/Remove on every SAM-generated
resource for a no-op update, and hardcoded Replacement=False even when a
resource's Type changed.

Now the diff expands a SAM change set's template before comparing, marks a
resource Modify when it references a changed parameter, and reports
Replacement=True when a resource's Type changes.

* fix(cloudformation): restore last-successful parameters on update rollback

executeTemplate overwrote the stack's live parameter map with an update's
attempted values before resolving SSM-typed parameters, which can fail. A
failed resolution rolled the stack back, but the update snapshot never
captured parameters, so DescribeStacks reported the failed update's
attempted values instead of the last successfully deployed ones.

StackUpdateSnapshot now captures the stack's parameters alongside its
template body, and rollbackFailedUpdate restores them together.

* fix(cloudformation): log tolerated wait-slice timeouts in custom-resource poll loop

Each slice of the custom-resource poll loop below the outer idle budget
hit an intentionally-tolerated TimeoutException that was swallowed with
only a comment, against the repo's convention of logging deliberately
caught exceptions.

* fix(cloudformation): honor Parameters.member.N.UsePreviousValue

extractParameters never read UsePreviousValue, so submitting it without a
ParameterValue stored an empty string for that key. The new parameter-diff
logic in computeChangeSetChanges (9fb02c6a9) then treated that empty
string as different from the deployed value, reporting a spurious Modify
for every resource referencing an otherwise-unchanged parameter.

extractParameters now takes the stack's current parameters and resolves
UsePreviousValue against them; CloudFormationService.currentParameters
looks those up (empty map if the stack doesn't exist yet, e.g. a CREATE
change set).

* fix(cloudformation): resolve UsePreviousValue against deployed StackSet parameters

UpdateStackSet extracted parameters with the previous-value-unaware
extractParameters() overload, so a member with UsePreviousValue=true and no
ParameterValue stored an empty string and clobbered the StackSet's deployed
value instead of preserving it.

* fix(cloudformation): resolve template defaults for omitted parameters in changeset diff

computeChangeSetChanges compared only explicitly submitted parameters against
the deployed stack, so an update that omits a parameter (falling back to its
template Default) was never flagged as a change even when that default
differs from the deployed value. ExecuteChangeSet applies the default when it
actually runs, so the preview under-reported what would change. Resolve
defaults for the change set's parameters the same way execution does before
diffing.

* fix(cloudformation): resolve SSM parameter drift and no-default omissions in changeset diff

computeChangeSetChanges compared raw submitted parameter values against the
deployed stack, so it missed two cases ExecuteChangeSet actually handles
differently: an omitted parameter with no template Default disappears
entirely from the resolved map (previously undetected since the diff only
walked the new parameter set), and AWS::SSM::Parameter::Value<String>
parameters are resolved against the live SSM store at execution time but
compared as raw parameter names in the preview, masking a changed SSM value
behind an unchanged parameter name.

Stack now tracks resolvedParameters (the SSM-resolved map executeTemplate
last applied, restored on rollback like parameters already was) so the diff
can compare resolved values on both sides. The diff falls back to unresolved
values if SSM resolution fails, since a preview must not fail harder than
the operation it previews - ExecuteChangeSet still raises the real
ValidationError when it resolves for real.

* fix(stepfunctions): pass CustomResourceLiveness to AslExecutor in error-termination test

Upstream's issue #2666 regression test predates this branch's addition
of CustomResourceLiveness to AslExecutor's constructor. The merge from
upstream/main brought the file in as new content with no line overlap,
so it auto-merged cleanly but left the constructor call one argument
short.

* fix(cloudformation): evaluate Conditions in changeset diff, always restore params on rollback

computeChangeSetChanges never evaluated template Conditions, so a resource
whose Condition depends on a changed parameter but whose own definition text
is unchanged was invisible to the diff even though ExecuteChangeSet would
Add or Remove it once the condition flips (see
deleteRemovedOrConditionFalseResources). The diff now resolves Conditions
against the new resolved parameters and compares against whether the
resource is actually present in stack.getResources() - the same ground
truth execution already uses to decide whether a resource was created -
falling back to the existing text-based Modify detection when the condition
doesn't change.

rollbackFailedUpdate only restored the last-successful parameter maps when
resource rollback itself also succeeded, so a stack that lands in
UPDATE_ROLLBACK_FAILED (resource rollback failed too) kept serving the
failed update's attempted parameter values via DescribeStacks and later
change-set previews. Parameters are independent of resource-rollback
outcome and are now restored unconditionally; templateBody restoration
stays gated on rollback success since a partially-rolled-back resource set
doesn't correspond to either template.

* fix(stepfunctions): pass EventBridgeHandler/SchedulerService/SchedulerController mocks in AslExecutor test

Merging upstream/main (55acdec6e) added these three constructor
parameters to AslExecutor without updating this test's call site,
breaking test-compile.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-29 15:01:00 -04:00
1 parent 54dacfc56f
commit 08e532ab1a
37 files changed
+2759 -56

No files matched your search

@@ -0,0 +1,74 @@
package io.github.hectorvent.floci.core.common;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
/**
* Sink for "this custom resource is still making progress" signals.
*
* <p>Lives here rather than in the cloudformation package so the Lambda service can report liveness
* without depending on CloudFormation: the dependency already runs the other way (the provisioner
* invokes Lambdas), and pointing it back would make the two packages mutually dependent.
*
* <p>The signal is observable generically because the provisioner embeds its correlation token in
* the {@code ResponseURL} it puts on every event, and the CDK provider framework echoes that same
* event into each {@code framework.isComplete} poll. So a poll arriving at the Lambda service is
* proof of progress on a specific pending resource, with nothing here needing to know what the
* resource does.
*/
public interface CustomResourceLiveness {
/** Path segment the provisioner uses for its callback URL; the token follows it. */
String RESPONSE_PATH = "/cfn-response/";
/** Records progress for {@code token}. Unknown tokens are ignored. */
void touch(String token);
/**
* Extracts the callback token from an invoke payload, if it carries one.
*
* @return the token, or empty for the overwhelming majority of invokes, which are ordinary
* Lambda calls with no custom-resource event in them
*/
byte[] RESPONSE_PATH_ASCII = RESPONSE_PATH.getBytes(StandardCharsets.US_ASCII);
static Optional<String> tokenIn(byte[] payload) {
if (payload == null || payload.length == 0) {
return Optional.empty();
}
// Scans the raw bytes for the ASCII marker instead of materializing the whole payload as a
// String: this runs on every Lambda invoke once liveness is wired in, and the overwhelming
// majority of invokes carry no callback URL at all, so the common case should cost nothing
// beyond the scan itself.
int start = indexOfMarker(payload);
if (start < 0) {
return Optional.empty();
}
start += RESPONSE_PATH_ASCII.length;
int end = start;
// The token is a UUID; stop at whatever JSON punctuation closes the URL.
while (end < payload.length && isTokenByte(payload[end])) {
end++;
}
return end > start ? Optional.of(new String(payload, start, end - start, StandardCharsets.US_ASCII))
: Optional.empty();
}
private static int indexOfMarker(byte[] payload) {
byte[] marker = RESPONSE_PATH_ASCII;
outer:
for (int i = 0; i <= payload.length - marker.length; i++) {
for (int j = 0; j < marker.length; j++) {
if (payload[i + j] != marker[j]) {
continue outer;
}
}
return i;
}
return -1;
}
private static boolean isTokenByte(byte b) {
return (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '-';
}
}
@@ -141,7 +141,8 @@ public class CloudFormationQueryHandler {
String stackName = params.getFirst("StackName");
String templateBody = params.getFirst("TemplateBody");
String templateUrl = params.getFirst("TemplateURL");
Map<String, String> parameters = extractParameters(params);
Map<String, String> parameters =
extractParameters(params, cfnService.currentParameters(stackName, region));
List<String> capabilities = extractList(params, "Capabilities.member.");
ChangeSet cs = cfnService.createChangeSet(stackName, "update-" + UUID.randomUUID().toString().substring(0, 8),
@@ -206,7 +207,8 @@ public class CloudFormationQueryHandler {
String changeSetType = params.getFirst("ChangeSetType");
String templateBody = params.getFirst("TemplateBody");
String templateUrl = params.getFirst("TemplateURL");
Map<String, String> parameters = extractParameters(params);
Map<String, String> parameters =
extractParameters(params, cfnService.currentParameters(stackName, region));
List<String> capabilities = extractList(params, "Capabilities.member.");
Map<String, String> tags = extractTags(params);
@@ -234,7 +236,8 @@ public class CloudFormationQueryHandler {
String changeSetName = params.getFirst("ChangeSetName");
try {
ChangeSet cs = cfnService.describeChangeSet(stackName, changeSetName, region);
String xml = new XmlBuilder()
List<CloudFormationService.ResourceChange> changes = cfnService.computeChangeSetChanges(cs, region);
XmlBuilder xml = new XmlBuilder()
.start("DescribeChangeSetResponse", CF_NS)
.start("DescribeChangeSetResult")
.elem("ChangeSetId", cs.getChangeSetId())
@@ -243,13 +246,26 @@ public class CloudFormationQueryHandler {
.elem("StackName", cs.getStackName())
.elem("Status", cs.getStatus())
.elem("ExecutionStatus", cs.getExecutionStatus())
.raw("<Changes/>")
.elem("CreationTime", ISO.format(cs.getCreationTime()))
.end("DescribeChangeSetResult")
.raw(AwsQueryResponse.responseMetadata())
.end("DescribeChangeSetResponse")
.build();
return Response.ok(xml).type("text/xml").build();
.start("Changes");
for (CloudFormationService.ResourceChange change : changes) {
xml.start("member")
.elem("Type", "Resource")
.start("ResourceChange")
.elem("Action", change.action())
.elem("LogicalResourceId", change.logicalResourceId())
.elem("PhysicalResourceId", change.physicalResourceId())
.elem("ResourceType", change.resourceType())
.elem("Replacement", change.replacement())
.raw("<Scope/><Details/>")
.end("ResourceChange")
.end("member");
}
xml.end("Changes")
.elem("CreationTime", ISO.format(cs.getCreationTime()))
.end("DescribeChangeSetResult")
.raw(AwsQueryResponse.responseMetadata())
.end("DescribeChangeSetResponse");
return Response.ok(xml.build()).type("text/xml").build();
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
@@ -581,6 +597,13 @@ public class CloudFormationQueryHandler {
xml.elem("member", cap);
}
xml.end("Capabilities");
xml.start("Parameters");
s.getParameters().forEach((k, v) ->
xml.start("member")
.elem("ParameterKey", k)
.elem("ParameterValue", v)
.end("member"));
xml.end("Parameters");
xml.start("Outputs");
s.getOutputs().forEach((k, v) -> {
xml.start("member")
@@ -626,14 +649,28 @@ public class CloudFormationQueryHandler {
}
private Map<String, String> extractParameters(MultivaluedMap<String, String> params) {
return extractParameters(params, Map.of());
}
/**
* @param previousParameters the stack's currently deployed parameters, consulted when a member
* sets {@code UsePreviousValue=true} instead of a {@code ParameterValue}
*/
private Map<String, String> extractParameters(
MultivaluedMap<String, String> params, Map<String, String> previousParameters) {
Map<String, String> result = new HashMap<>();
int i = 1;
while (true) {
String key = params.getFirst("Parameters.member." + i + ".ParameterKey");
String value = params.getFirst("Parameters.member." + i + ".ParameterValue");
if (key == null) {
break;
}
String value;
if (Boolean.parseBoolean(params.getFirst("Parameters.member." + i + ".UsePreviousValue"))) {
value = previousParameters.get(key);
} else {
value = params.getFirst("Parameters.member." + i + ".ParameterValue");
}
result.put(key, value != null ? value : "");
i++;
}
@@ -747,10 +784,12 @@ public class CloudFormationQueryHandler {
private Response updateStackSet(MultivaluedMap<String, String> params) {
try {
String stackSetName = params.getFirst("StackSetName");
Map<String, String> previousParameters = stackSetService.describeStackSet(stackSetName).getParameters();
StackSetOperation op = stackSetService.updateStackSet(
params.getFirst("StackSetName"),
stackSetName,
cfnService.resolveTemplateBody(params.getFirst("TemplateBody"), params.getFirst("TemplateURL")),
extractParameters(params),
extractParameters(params, previousParameters),
extractList(params, "Capabilities.member."),
extractTags(params),
params.getFirst("Description"));
@@ -3157,6 +3157,9 @@ public class CloudFormationResourceProvisioner {
}
ssmService.putParameter(name, value, type, null, true, region);
r.setPhysicalId(name);
r.getAttributes().put("Name", name);
r.getAttributes().put("Type", type);
r.getAttributes().put("Value", value);
}
// ── KMS ───────────────────────────────────────────────────────────────────
@@ -6404,13 +6407,13 @@ public class CloudFormationResourceProvisioner {
"Custom resource handler errored (" + result.getFunctionError() + "): " + body, 400);
}
return customResourceResponseStore.await(token, CR_RESPONSE_TIMEOUT);
return customResourceResponseStore.await(token, CR_RESPONSE_TIMEOUT, serviceToken, region);
} catch (AwsException e) {
throw e;
} catch (TimeoutException e) {
throw new AwsException("CustomResourceTimeout",
"Timed out waiting for custom resource " + logicalId
+ " to PUT its response to ResponseURL", 504);
+ " to PUT its response to ResponseURL: " + e.getMessage(), 504);
} catch (Exception e) {
throw new AwsException("CustomResourceFailed",
"Failed to invoke custom resource " + logicalId + ": " + e.getMessage(), 500);
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.model.TemplateSummary;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -62,6 +63,7 @@ public class CloudFormationService implements ResourceProvider {
private final CloudFormationResourceProvisioner provisioner;
private final S3Service s3Service;
private final SsmService ssmService;
private final ObjectMapper objectMapper;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@@ -78,11 +80,12 @@ public class CloudFormationService implements ResourceProvider {
@Inject
public CloudFormationService(CloudFormationResourceProvisioner provisioner, S3Service s3Service,
ObjectMapper objectMapper, EmulatorConfig config,
SsmService ssmService, ObjectMapper objectMapper, EmulatorConfig config,
RegionResolver regionResolver, Clock clock,
StorageFactory storageFactory) {
this.provisioner = provisioner;
this.s3Service = s3Service;
this.ssmService = ssmService;
this.objectMapper = objectMapper;
this.config = config;
this.regionResolver = regionResolver;
@@ -151,6 +154,16 @@ public class CloudFormationService implements ResourceProvider {
.toList();
}
/**
* The stack's current parameter values, or an empty map if it does not exist (yet). Used to
* resolve {@code UsePreviousValue} on an update before the stack lookup that
* {@code createChangeSet}/{@code executeChangeSet} would otherwise perform.
*/
public Map<String, String> currentParameters(String stackName, String region) {
Stack stack = resolveStack(stackName, region);
return stack != null ? stack.getParameters() : Map.of();
}
// ── CreateChangeSet ───────────────────────────────────────────────────────
public ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
@@ -300,6 +313,152 @@ public class CloudFormationService implements ResourceProvider {
return cs;
}
/**
* Computes the per-resource changes a change set would apply, by diffing its template against
* the stack's currently deployed template. CREATE-type change sets (and stacks that have never
* executed a template) report every resource with a truthy {@code Condition} as an Add.
*/
public List<ResourceChange> computeChangeSetChanges(ChangeSet cs, String region) {
Stack stack = getStackOrThrow(cs.getStackName(), region);
try {
JsonNode newTemplate = parseTemplate(cs.getTemplateBody());
if (samTransformProcessor.hasSamTransform(newTemplate)) {
// The deployed stack's template is always the SAM-expanded form (see
// executeTemplate); comparing the change set's raw SAM source against it would
// report every SAM-generated resource as Add/Remove even on a no-op update.
newTemplate = samTransformProcessor.expandSamTemplate(newTemplate);
}
JsonNode newResources = newTemplate.path("Resources");
boolean createType = "CREATE".equalsIgnoreCase(cs.getChangeSetType())
|| stack.getTemplateBody() == null;
JsonNode oldResources = createType
? objectMapper.createObjectNode()
: parseTemplate(stack.getTemplateBody()).path("Resources");
Map<String, String> oldParams = stack.getParameters() != null
? stack.getParameters() : Map.of();
// Prefer the SSM-resolved values captured by the last executeTemplate run; fall back to
// the raw parameters for stacks persisted before resolvedParameters existed.
Map<String, String> oldResolvedParams = stack.getResolvedParameters() != null
&& !stack.getResolvedParameters().isEmpty()
? stack.getResolvedParameters() : oldParams;
// A parameter omitted from the update falls back to the template's Default when
// ExecuteChangeSet actually runs it, so the preview must resolve the same defaults or
// it will under-report changes to resources that depend on that fallback value.
Map<String, String> newParams = resolveDefaultParameters(newTemplate,
cs.getParameters() != null ? cs.getParameters() : Map.of());
// ExecuteChangeSet also resolves AWS::SSM::Parameter::Value<String> parameters against
// the live Parameter Store before applying resource changes, and the stored SSM value
// can drift between deploys even when the referencing parameter name is unchanged. Diff
// on the resolved values, like execution does, so the preview agrees with what actually
// gets applied. A preview must not fail harder than the operation it previews though: if
// the referenced SSM parameter is missing, fall back to the unresolved values here and
// let ExecuteChangeSet raise that ValidationError when it actually resolves them.
Map<String, String> ssmResolvedNewParams;
try {
ssmResolvedNewParams = resolveSsmParameters(newTemplate, newParams, region);
} catch (AwsException e) {
ssmResolvedNewParams = newParams;
}
final Map<String, String> newResolvedParams = ssmResolvedNewParams;
Set<String> changedParams = new HashSet<>();
newResolvedParams.forEach((k, v) -> {
if (!Objects.equals(v, oldResolvedParams.get(k))) {
changedParams.add(k);
}
});
// A parameter that was deployed but is omitted from this update with no template
// Default is dropped entirely by resolveDefaultParameters (matching what
// ExecuteChangeSet does); flag its disappearance too, not just a value change.
oldResolvedParams.keySet().forEach(k -> {
if (!newResolvedParams.containsKey(k)) {
changedParams.add(k);
}
});
// A resource whose Condition depends on a changed parameter can flip from excluded to
// included (or back) even when its own definition text is unchanged; ExecuteChangeSet
// applies that as an Add or Remove (see hasRemovedOrConditionFalseResources /
// deleteRemovedOrConditionFalseResources), so the preview must evaluate Conditions too
// rather than only scanning each resource's own Ref/Sub usage. A resource is "active" in
// the deployed stack precisely when it's present in stack.getResources() - the same
// ground truth execution uses - so no separate old-conditions evaluation is needed.
Map<String, Boolean> newConditions = resolveConditions(
newTemplate, newResolvedParams, null, region, regionResolver.getAccountId());
Set<String> deployedIds = stack.getResources().keySet();
List<ResourceChange> changes = new ArrayList<>();
newResources.fields().forEachRemaining(e -> {
String logicalId = e.getKey();
JsonNode newDef = e.getValue();
String resourceType = newDef.path("Type").asText();
JsonNode oldDef = oldResources.get(logicalId);
String newConditionName = newDef.path("Condition").asText(null);
boolean newActive = newConditionName == null
|| newConditions.getOrDefault(newConditionName, false);
if (oldDef == null) {
if (newActive) {
changes.add(new ResourceChange("Add", logicalId, null, resourceType, null));
}
return;
}
boolean wasDeployed = deployedIds.contains(logicalId);
if (wasDeployed && !newActive) {
// Condition flipped true -> false: the definition text is unchanged, but
// ExecuteChangeSet deletes the resource (see deleteRemovedOrConditionFalseResources).
changes.add(new ResourceChange("Remove", logicalId,
resourcePhysicalId(stack, logicalId), oldDef.path("Type").asText(), null));
} else if (!wasDeployed && newActive) {
// Condition flipped false -> true: never created before, ExecuteChangeSet creates
// it now.
changes.add(new ResourceChange("Add", logicalId, null, resourceType, null));
} else if (newActive
&& (!oldDef.equals(newDef) || referencesAnyParameter(newDef, changedParams))) {
boolean typeChanged = !oldDef.path("Type").asText().equals(resourceType);
changes.add(new ResourceChange("Modify", logicalId,
resourcePhysicalId(stack, logicalId), resourceType,
typeChanged ? "True" : "False"));
}
});
oldResources.fields().forEachRemaining(e -> {
if (!newResources.has(e.getKey())) {
changes.add(new ResourceChange("Remove", e.getKey(),
resourcePhysicalId(stack, e.getKey()),
e.getValue().path("Type").asText(), null));
}
});
return changes;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("ValidationError",
"Unable to compute changes for change set " + cs.getChangeSetName()
+ ": " + e.getMessage(), 400);
}
}
/** True if a resource's definition references any of the given (changed) parameter names. */
private boolean referencesAnyParameter(JsonNode resourceDef, Set<String> parameterNames) {
if (parameterNames.isEmpty()) {
return false;
}
String json = resourceDef.toString();
for (String name : parameterNames) {
if (json.contains("\"Ref\":\"" + name + "\"") || json.contains("${" + name + "}")) {
return true;
}
}
return false;
}
public record ResourceChange(String action, String logicalResourceId, String physicalResourceId,
String resourceType, String replacement) {}
private String resourcePhysicalId(Stack stack, String logicalId) {
StackResource resource = stack.getResources().get(logicalId);
return resource != null ? resource.getPhysicalId() : null;
}
// ── ExecuteChangeSet ──────────────────────────────────────────────────────
public Future<?> executeChangeSet(String stackName, String changeSetName, String region) {
@@ -629,6 +788,43 @@ public class CloudFormationService implements ResourceProvider {
return resolved;
}
/**
* Substitutes {@code AWS::SSM::Parameter::Value<String>}-typed parameter values — which carry
* an SSM parameter <em>name</em> — with the value stored in Parameter Store for the stack's
* account and region, as real CloudFormation does before template processing. Missing
* parameters fail the stack operation with the real AWS ValidationError. The related types
* {@code AWS::SSM::Parameter::Value<List<String>>} and {@code AWS::SSM::Parameter::Name} are
* not resolved and pass through verbatim.
*/
private Map<String, String> resolveSsmParameters(JsonNode template, Map<String, String> params, String region) {
JsonNode paramDefs = template.path("Parameters");
if (!paramDefs.isObject()) {
return params;
}
Map<String, String> resolved = new HashMap<>(params);
List<String> missing = new ArrayList<>();
paramDefs.fields().forEachRemaining(e -> {
if (!"AWS::SSM::Parameter::Value<String>".equals(e.getValue().path("Type").asText())) {
return;
}
String parameterName = resolved.get(e.getKey());
if (parameterName == null || parameterName.isBlank()) {
return;
}
try {
resolved.put(e.getKey(), ssmService.getParameter(parameterName, region).getValue());
} catch (AwsException ex) {
missing.add(parameterName);
}
});
if (!missing.isEmpty()) {
throw new AwsException("ValidationError",
"Unable to fetch parameters [" + String.join(",", missing)
+ "] from parameter store for this account", 400);
}
return resolved;
}
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
boolean isCreate, String region, String accountId) {
StackUpdateSnapshot previousState = snapshotForUpdate(stack);
@@ -649,7 +845,11 @@ public class CloudFormationService implements ResourceProvider {
stack.setTemplateBody(templateBody);
// Merge default parameter values from the template with caller-supplied params
Map<String, String> resolvedParams = resolveDefaultParameters(template, params);
Map<String, String> givenParams = resolveDefaultParameters(template, params);
stack.getParameters().clear();
stack.getParameters().putAll(givenParams);
Map<String, String> resolvedParams = resolveSsmParameters(template, givenParams, region);
stack.setResolvedParameters(new LinkedHashMap<>(resolvedParams));
// Resolve conditions first
Map<String, Boolean> conditions = resolveConditions(template, resolvedParams, stack, region, accountId);
@@ -1069,6 +1269,14 @@ public class CloudFormationService implements ResourceProvider {
List<String> rollbackFailures = rollbackUpdatedResources(
stack, previousState.resources(), attemptedResourceIds, region);
// 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
// in UPDATE_ROLLBACK_FAILED, so DescribeStacks and later change-set previews don't keep
// serving the failed update's attempted values.
stack.getParameters().clear();
stack.getParameters().putAll(previousState.parameters());
stack.getResolvedParameters().clear();
stack.getResolvedParameters().putAll(previousState.resolvedParameters());
if (rollbackFailures.isEmpty()) {
stack.setTemplateBody(previousState.templateBody());
}
@@ -1214,6 +1422,8 @@ public class CloudFormationService implements ResourceProvider {
private StackUpdateSnapshot snapshotForUpdate(Stack stack) {
return new StackUpdateSnapshot(
stack.getTemplateBody(),
new LinkedHashMap<>(stack.getParameters()),
new LinkedHashMap<>(stack.getResolvedParameters()),
new LinkedHashMap<>(stack.getOutputs()),
new LinkedHashMap<>(stack.getExports()),
new LinkedHashMap<>(stack.getOutputExportNames()),
@@ -1244,6 +1454,8 @@ public class CloudFormationService implements ResourceProvider {
private record StackUpdateSnapshot(
String templateBody,
Map<String, String> parameters,
Map<String, String> resolvedParameters,
Map<String, String> outputs,
Map<String, String> exports,
Map<String, String> outputExportNames,
@@ -1,7 +1,9 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Duration;
@@ -10,56 +12,126 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
/**
* Correlates a CloudFormation custom-resource Lambda invocation with the response the
* Lambda PUTs back to its {@code ResponseURL}.
* Holds the futures that custom-resource ResponseURL callbacks complete.
*
* <p>The AWS custom-resource protocol is callback-based: the backing Lambda does not return
* its result, it HTTP PUTs a response document to a pre-signed {@code ResponseURL}. Floci hands
* the Lambda a {@code ResponseURL} pointing at {@link CfnResponseController}, which feeds the
* body back here keyed by a per-invocation token.
*
* <p>Because Floci invokes the Lambda synchronously (RequestResponse) and the handler PUTs
* before returning, the future is normally already completed by the time the provisioner awaits
* it — the timeout only guards a PUT that lands just after the container returns.
* <p>The wait budget is an <em>idle</em> timeout, not a total one. A CDK provider-framework waiter
* drives {@code framework.isComplete} on a fixed cadence and PUTs only once the work is done, so the
* total time is a property of the work rather than of the emulator — {@code
* Custom::CreateOrganizationAccounts} creates one account per poll, meaning a 15-account org takes
* five times as long as a 3-account one. Budgeting total time therefore needs re-tuning per config
* set, and overshooting guillotines a Lambda that was succeeding. Budgeting idleness needs no
* knowledge of the work at all: each poll is liveness, so progress buys unbounded wall-clock while a
* resource that has genuinely stopped still fails on schedule.
*/
@ApplicationScoped
public class CustomResourceResponseStore {
public class CustomResourceResponseStore implements CustomResourceLiveness {
private static final Logger LOG = Logger.getLogger(CustomResourceResponseStore.class);
private final ConcurrentHashMap<String, Pending> pending = new ConcurrentHashMap<>();
private final ProviderFrameworkDetector providerFrameworkDetector;
private final ConcurrentHashMap<String, CompletableFuture<JsonNode>> pending = new ConcurrentHashMap<>();
@Inject
CustomResourceResponseStore(ProviderFrameworkDetector providerFrameworkDetector) {
this.providerFrameworkDetector = providerFrameworkDetector;
}
/** A waiting caller: the future its callback completes, and when it last saw progress. */
private static final class Pending {
private final CompletableFuture<JsonNode> future = new CompletableFuture<>();
// nanoTime, not wall-clock: this measures an elapsed interval and must not jump with NTP.
private final AtomicLong lastActivity = new AtomicLong(System.nanoTime());
}
/** Registers a fresh token and returns it. Call before invoking the Lambda. */
public String register() {
String token = UUID.randomUUID().toString();
pending.put(token, new CompletableFuture<>());
pending.put(token, new Pending());
return token;
}
/** Completes the future for {@code token} with the PUT body. No-op for unknown/expired tokens. */
public void complete(String token, JsonNode response) {
CompletableFuture<JsonNode> future = pending.get(token);
if (future != null) {
future.complete(response);
Pending entry = pending.get(token);
if (entry != null) {
entry.future.complete(response);
} else {
LOG.debugv("Received custom-resource response for unknown token {0}", token);
}
}
/**
* Waits up to {@code timeout} for the Lambda's response, then discards the token.
* Records liveness for {@code token}, resetting its idle budget.
*
* @throws TimeoutException if no response arrives in time
* <p>Unknown tokens are ignored by design: polls routinely outlive the await that registered
* them (after a timeout or a rollback), and that tail is normal rather than an error.
*/
public JsonNode await(String token, Duration timeout) throws TimeoutException {
CompletableFuture<JsonNode> future = pending.get(token);
if (future == null) {
@Override
public void touch(String token) {
Pending entry = pending.get(token);
if (entry != null) {
entry.lastActivity.set(System.nanoTime());
}
}
/**
* Waits for the Lambda's response on the budget that suits the handler behind {@code serviceToken},
* then discards the token.
*
* <p>A CDK Provider-framework {@code framework.onEvent} handler PUTs asynchronously via its waiter
* state machine and gets a longer idle budget than {@code synchronousIdleTimeout}; see {@link
* ProviderFrameworkDetector#responseTimeout}.
*
* @param synchronousIdleTimeout the budget for a handler that PUTs during its own invocation
* @throws TimeoutException if no response and no liveness arrive within the chosen budget
*/
public JsonNode await(String token, Duration synchronousIdleTimeout, String serviceToken, String region)
throws TimeoutException {
return await(token,
providerFrameworkDetector.responseTimeout(serviceToken, region, synchronousIdleTimeout));
}
/**
* Waits for the Lambda's response, then discards the token.
*
* @param idleTimeout how long to tolerate <em>no</em> progress; each {@link #touch} restarts it,
* so a resource that keeps polling is never cut off
* @throws TimeoutException if no response and no liveness arrive within {@code idleTimeout}
*/
public JsonNode await(String token, Duration idleTimeout) throws TimeoutException {
Pending entry = pending.get(token);
if (entry == null) {
throw new IllegalStateException("No pending custom-resource token: " + token);
}
long idleNanos = idleTimeout.toNanos();
// The budget measures idleness of the WAIT, so it starts when the caller begins waiting rather
// than when the token was registered. Registration happens before the invoke, and a synchronous
// handler PUTs from inside the invoke the caller is blocked on: charging that execution time
// here would leave a slow handler — a cold container start, or two of them nested — with a
// budget already spent by the time await was entered. A handler that just returned is not idle.
entry.lastActivity.set(System.nanoTime());
try {
return future.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
while (true) {
long remaining = idleNanos - (System.nanoTime() - entry.lastActivity.get());
if (remaining <= 0) {
// A response that has already arrived is a response, whatever the clock says. The
// future outranks the budget: complete() can land before await is ever entered, and
// discarding a delivered response as a timeout fails a resource that succeeded.
if (entry.future.isDone()) {
return entry.future.get();
}
throw new TimeoutException("No custom-resource activity for " + idleTimeout);
}
try {
return entry.future.get(remaining, TimeUnit.NANOSECONDS);
} catch (TimeoutException e) {
// This slice elapsed. A concurrent touch may have pushed lastActivity forward,
// in which case the next slice is positive again and the wait continues; if
// nothing touched, the guard above fails on the very next pass.
LOG.tracev("Custom-resource wait slice elapsed for token {0}; rechecking liveness", token);
}
}
} catch (TimeoutException e) {
throw e;
} catch (Exception e) {
@@ -0,0 +1,98 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Duration;
import java.util.Map;
/**
* Decides how long a custom-resource ResponseURL callback may stay idle, by recognising the CDK
* Provider framework's {@code framework.onEvent} Lambda from its environment.
*/
@ApplicationScoped
public class ProviderFrameworkDetector {
private static final Logger LOG = Logger.getLogger(ProviderFrameworkDetector.class);
/**
* Environment variables the CDK Provider framework sets on {@code framework.onEvent} only when an
* {@code isComplete} handler is configured — i.e. when the two-phase async waiter is in play. Their
* presence distinguishes a Provider-framework onEvent (which PUTs asynchronously via the waiter)
* from an onEvent-only provider or a plain single-Lambda handler (which PUT synchronously).
*/
private static final String CR_USER_IS_COMPLETE_ENV = "USER_IS_COMPLETE_FUNCTION_ARN";
private static final String CR_WAITER_STATE_MACHINE_ENV = "WAITER_STATE_MACHINE_ARN";
/**
* How long to wait when the ServiceToken is a CDK Provider-framework {@code framework.onEvent}
* Lambda: it does not PUT itself but returns after starting the waiter state machine, so the
* ResponseURL callback arrives asynchronously once {@code framework.isComplete} reports done (or
* {@code framework.onTimeout} reports failure).
*
* <p>This is an <em>idle</em> budget, not a total one: every waiter poll resets it (see {@link
* CustomResourceResponseStore#touch}). Total time here is a property of the work rather than of
* the emulator — {@code Custom::CreateOrganizationAccounts} creates one account per poll, so 15
* accounts take five times as long as three — and a total budget would need re-tuning for every
* config set while guillotining Lambdas that were succeeding. Measuring idleness still fails a
* genuinely hung resource cleanly instead of hanging. Non-final so tests can shorten it.
*/
private Duration asyncCustomResourceTimeout = Duration.ofMinutes(3);
private final LambdaService lambdaService;
@Inject
ProviderFrameworkDetector(LambdaService lambdaService) {
this.lambdaService = lambdaService;
}
/**
* The idle budget to allow the handler behind {@code serviceToken}.
*
* <p>{@code framework.onEvent} returns without PUTting (it starts the waiter state machine, which
* drives {@code framework.isComplete} on a Retry cadence until it PUTs). So the callback lands
* asynchronously and needs a longer wait than the synchronous single-Lambda pattern. onEvent-only
* providers and plain handlers PUT during the invoke, so their await returns immediately
* regardless of this budget.
*
* @param synchronousTimeout the budget for a handler that PUTs during its own invocation
*/
Duration responseTimeout(String serviceToken, String region, Duration synchronousTimeout) {
return isProviderFrameworkOnEvent(serviceToken, region)
? asyncCustomResourceTimeout : synchronousTimeout;
}
/**
* True when the ServiceToken resolves to a CDK Provider-framework {@code framework.onEvent} Lambda,
* i.e. one whose environment carries both {@code USER_IS_COMPLETE_FUNCTION_ARN} and
* {@code WAITER_STATE_MACHINE_ARN}. The framework sets these only when a two-phase async waiter is
* configured, so their presence means the ResponseURL callback will arrive asynchronously via the
* waiter rather than synchronously during the invoke. Best-effort: an unresolvable function (or one
* with no environment) is treated as a synchronous handler.
*/
boolean isProviderFrameworkOnEvent(String serviceToken, String region) {
try {
LambdaFunction fn = lambdaService.getFunction(region, serviceToken);
Map<String, String> env = fn != null ? fn.getEnvironment() : null;
if (env == null) {
return false;
}
String isComplete = env.get(CR_USER_IS_COMPLETE_ENV);
String waiter = env.get(CR_WAITER_STATE_MACHINE_ENV);
return isComplete != null && !isComplete.isBlank()
&& waiter != null && !waiter.isBlank();
} catch (RuntimeException e) {
LOG.debugv("Could not read environment for custom-resource handler {0}: {1}",
serviceToken, e.getMessage());
return false;
}
}
/** Test hook: shortens the async-callback wait so the timeout bound can be exercised quickly. */
void setAsyncCustomResourceTimeoutForTesting(Duration timeout) {
this.asyncCustomResourceTimeout = timeout;
}
}
@@ -20,6 +20,10 @@ public class Stack {
private String originalTemplateBody;
private List<String> capabilities = new ArrayList<>();
private Map<String, String> parameters = new LinkedHashMap<>();
// Parameters after AWS::SSM::Parameter::Value<String> resolution, as last applied by
// executeTemplate — used to detect drift in the live SSM value between deploys even when the
// referencing parameter (name) is unchanged, so change-set previews agree with execution.
private Map<String, String> resolvedParameters = new LinkedHashMap<>();
private Map<String, String> outputs = new LinkedHashMap<>();
private Map<String, String> exports = new LinkedHashMap<>();
// Maps output key to its export name (when Export.Name is defined on an output)
@@ -52,6 +56,8 @@ public class Stack {
public void setCapabilities(List<String> capabilities) { this.capabilities = capabilities; }
public Map<String, String> getParameters() { return parameters; }
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
public Map<String, String> getResolvedParameters() { return resolvedParameters; }
public void setResolvedParameters(Map<String, String> resolvedParameters) { this.resolvedParameters = resolvedParameters; }
public Map<String, String> getOutputs() { return outputs; }
public void setOutputs(Map<String, String> outputs) { this.outputs = outputs; }
public Map<String, String> getExports() { return exports; }
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -85,6 +86,8 @@ public class LambdaService implements ResourceProvider {
private final StorageFactory storageFactory;
private final LambdaLayerService layerService;
private final Ec2Service ec2Service;
/** Null in the constructors tests use, exactly as the other optional collaborators above are. */
private final CustomResourceLiveness customResourceLiveness;
private Map<String, Integer> versionCounters = new ConcurrentHashMap<>();
private Map<String, FunctionEventInvokeConfig> eventInvokeConfigs = new ConcurrentHashMap<>();
/**
@@ -155,6 +158,7 @@ public class LambdaService implements ResourceProvider {
this.storageFactory = storageFactory;
this.layerService = null;
this.ec2Service = null;
this.customResourceLiveness = null;
}
@Inject
@@ -175,7 +179,9 @@ public class LambdaService implements ResourceProvider {
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,
StorageFactory storageFactory,
LambdaLayerService layerService,
Ec2Service ec2Service) {
Ec2Service ec2Service,
CustomResourceLiveness customResourceLiveness) {
this.customResourceLiveness = customResourceLiveness;
this.functionStore = functionStore;
this.executorService = executorService;
this.concurrencyLimiter = concurrencyLimiter;
@@ -766,6 +772,7 @@ public class LambdaService implements ResourceProvider {
} else {
fn = resolveInvokeTarget(region, name, qualifier);
}
reportCustomResourceLiveness(payload);
InvokeResult result = executorService.invoke(fn, payload, type);
result.setExecutedVersion(fn.getVersion());
return result;
@@ -782,6 +789,21 @@ public class LambdaService implements ResourceProvider {
return result;
}
/**
* Reports that a pending custom resource is still making progress, if this payload belongs to
* one. A CDK provider-framework waiter re-invokes {@code framework.isComplete} on a cadence and
* echoes the original event -- including its ResponseURL -- into every poll, so a poll landing
* here is proof of liveness for that resource's callback token. Resetting the idle budget on it
* keeps a long-but-progressing resource (12 org accounts at one per poll) from being cut off
* mid-success, without CloudFormation needing to know how much work is left.
*/
private void reportCustomResourceLiveness(byte[] payload) {
if (customResourceLiveness == null) {
return;
}
CustomResourceLiveness.tokenIn(payload).ifPresent(customResourceLiveness::touch);
}
private LambdaFunction resolveInvokeTarget(String region, String name, String qualifier) {
if (qualifier == null || qualifier.equals("$LATEST")) {
return functionStore.get(region, name)
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
@@ -180,6 +181,7 @@ public class AslExecutor {
private final Instance<StepFunctionsService> sfnService;
private final WebClient webClient;
private final EmulatorConfig config;
private final CustomResourceLiveness customResourceLiveness;
private final Map<String, MockedTestCase> activeMocks = new ConcurrentHashMap<>();
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "sfn-executor");
@@ -196,7 +198,9 @@ public class AslExecutor {
EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,
SchedulerController schedulerController,
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx) {
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness) {
this.customResourceLiveness = customResourceLiveness;
this.lambdaExecutor = lambdaExecutor;
this.functionStore = functionStore;
this.dynamoDbService = dynamoDbService;
@@ -726,6 +730,21 @@ public class AslExecutor {
return fn;
}
/**
* Reports that a pending custom resource is still making progress, if this payload belongs to
* one. The Step Functions Task path drives a CDK provider-framework waiter's {@code
* framework.isComplete} polls straight through {@link LambdaExecutorService}, bypassing {@link
* io.github.hectorvent.floci.services.lambda.LambdaService#invoke} and the liveness hook it
* carries -- so this poll would otherwise never reset the resource's idle budget in {@link
* io.github.hectorvent.floci.services.cloudformation.CustomResourceResponseStore}.
*/
private void reportCustomResourceLiveness(byte[] payload) {
if (customResourceLiveness == null) {
return;
}
CustomResourceLiveness.tokenIn(payload).ifPresent(customResourceLiveness::touch);
}
private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken) throws Exception {
// Support Lambda resources: direct ARN or optimized integration
String functionName = null;
@@ -759,8 +778,9 @@ public class AslExecutor {
"Lambda function not found: " + functionName);
}
String payloadStr = objectMapper.writeValueAsString(lambdaPayload);
InvokeResult result = lambdaExecutor.invoke(fn, payloadStr.getBytes(), InvocationType.RequestResponse);
byte[] payloadBytes = objectMapper.writeValueAsString(lambdaPayload).getBytes();
reportCustomResourceLiveness(payloadBytes);
InvokeResult result = lambdaExecutor.invoke(fn, payloadBytes, InvocationType.RequestResponse);
if (result.getFunctionError() != null) {
throw new FailStateException("Lambda.AWSLambdaException", result.getFunctionError());