refactor(cloudformation): move Kinesis and CloudWatch to their own provisioners (#2758)

Migrates AWS::Kinesis::Stream and AWS::CloudWatch::Alarm out of the switch.
Two unrelated services in one slice because each is a single service call
with property mapping and no shared state; splitting them would cost two
review cycles for one mechanical change.

Kinesis carries an update path: an unchanged name reconciles stream mode,
retention and tags rather than calling createStream again, which the service
rejects with ResourceInUseException. It uses ctx.priorPhysicalId() for the
same reason the log group slice does, since the body assigns the new id
before it returns.

sameNameExistingResource, deleteRenamedResource and parseIntProp are copied
rather than shared: each still has callers in the monolith. addAlarmActions
moves, since all three of its call sites are inside the alarm body. Both
service fields leave the monolith; their constructor parameters stay until
the endgame.

The existing Kinesis and CloudWatch alarm integration tests are QuarkusTests
resolved through CDI, so they exercise the new provisioners with no edit,
which is the regression evidence for this slice.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-08-30 21:47:44 -05:00
1 parent 8765cde6dd
commit 2d724d15aa
6 files changed
+678 -167

No files matched your search

@@ -225,7 +225,6 @@ public class CloudFormationResourceProvisioner {
"AWS::Batch::JobQueue",
"AWS::CloudFormation::CustomResource",
"AWS::CloudFront::Distribution",
"AWS::CloudWatch::Alarm",
"AWS::Cognito::UserPool",
"AWS::Cognito::UserPoolClient",
"AWS::DynamoDB::GlobalTable",
@@ -256,7 +255,6 @@ public class CloudFormationResourceProvisioner {
"AWS::IAM::ManagedPolicy",
"AWS::IAM::Policy",
"AWS::IAM::User",
"AWS::Kinesis::Stream",
"AWS::Lambda::EventSourceMapping",
"AWS::Lambda::Function",
"AWS::Lambda::LayerVersion",
@@ -307,8 +305,6 @@ public class CloudFormationResourceProvisioner {
private final Ec2Service ec2Service;
private final RdsService rdsService;
private final EksService eksService;
private final KinesisService kinesisService;
private final CloudWatchMetricsService cloudWatchMetricsService;
private final AutoScalingService autoScalingService;
private final DocDbService docDbService;
private final CloudFrontService cloudFrontService;
@@ -374,8 +370,6 @@ public class CloudFormationResourceProvisioner {
this.ec2Service = ec2Service;
this.rdsService = rdsService;
this.eksService = eksService;
this.kinesisService = kinesisService;
this.cloudWatchMetricsService = cloudWatchMetricsService;
this.autoScalingService = autoScalingService;
this.docDbService = docDbService;
this.cloudFrontService = cloudFrontService;
@@ -513,10 +507,6 @@ public class CloudFormationResourceProvisioner {
provisionDbProxyTargetGroup(resource, properties, engine, region);
case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName);
case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName);
case "AWS::Kinesis::Stream" ->
provisionKinesisStream(resource, properties, engine, region, stackName);
case "AWS::CloudWatch::Alarm" ->
provisionCloudWatchAlarm(resource, properties, engine, region, stackName);
case "AWS::AutoScaling::LaunchConfiguration" ->
provisionLaunchConfiguration(resource, properties, engine, region, stackName);
case "AWS::AutoScaling::AutoScalingGroup" ->
@@ -750,9 +740,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::RDS::DBClusterParameterGroup" ->
rdsService.deleteDbClusterParameterGroup(physicalId, region);
case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);
case "AWS::Kinesis::Stream" -> kinesisService.deleteStream(physicalId, region);
case "AWS::CloudWatch::Alarm" ->
cloudWatchMetricsService.deleteAlarms(List.of(physicalId), region);
case "AWS::AutoScaling::LaunchConfiguration" ->
autoScalingService.deleteLaunchConfiguration(region, physicalId);
case "AWS::AutoScaling::AutoScalingGroup" ->
@@ -930,160 +917,8 @@ public class CloudFormationResourceProvisioner {
// ── Kinesis ─────────────────────────────────────────────────────────────────
private void provisionKinesisStream(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region, String stackName) {
String explicitName = resolveOptional(props, "Name", engine);
String priorPhysicalId = r.getPhysicalId();
String name;
if (explicitName != null && !explicitName.isBlank()) {
name = explicitName;
} else if (priorPhysicalId != null) {
name = priorPhysicalId;
} else {
name = generatePhysicalName(stackName, r.getLogicalId(), 128, false);
}
String streamMode = null;
if (props != null && props.has("StreamModeDetails")) {
streamMode = engine.resolve(props.get("StreamModeDetails").path("StreamMode"));
if (streamMode != null && streamMode.isBlank()) {
streamMode = null;
}
}
// ShardCount is required for PROVISIONED streams; default to 1 when unset (ON_DEMAND ignores it).
int shardCount = 1;
String shards = resolveOptional(props, "ShardCount", engine);
if (shards != null && !shards.isBlank()) {
try {
shardCount = Integer.parseInt(shards.trim());
} catch (NumberFormatException ignored) {
// keep default
}
}
Integer retention = null;
String retentionProp = resolveOptional(props, "RetentionPeriodHours", engine);
if (retentionProp != null && !retentionProp.isBlank()) {
try {
retention = Integer.parseInt(retentionProp.trim());
} catch (NumberFormatException ignored) {
// leave default
}
}
Map<String, String> tags = new LinkedHashMap<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
String key = engine.resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, engine.resolve(tag.path("Value")));
}
}
}
// provision() re-runs on every UpdateStack, so a same-named stream already on file must be
// reconciled instead of re-created (createStream throws ResourceInUseException). ShardCount
// changes aren't reconciled here: KinesisService has no UpdateShardCount support to call into.
KinesisStream stream =
sameNameExistingResource(priorPhysicalId, name, n -> kinesisService.describeStream(n, region));
if (stream != null) {
kinesisService.updateStreamMode(name, streamMode != null ? streamMode : "PROVISIONED", region);
if (retention != null) {
if (retention > stream.getRetentionPeriodHours()) {
kinesisService.increaseStreamRetentionPeriod(name, retention, region);
} else if (retention < stream.getRetentionPeriodHours()) {
kinesisService.decreaseStreamRetentionPeriod(name, retention, region);
}
}
Map<String, String> existingTags = kinesisService.listTagsForStream(name, region);
List<String> tagsToRemove = existingTags.keySet().stream()
.filter(key -> !tags.containsKey(key))
.toList();
if (!tagsToRemove.isEmpty()) {
kinesisService.removeTagsFromStream(name, tagsToRemove, region);
}
if (!tags.isEmpty()) {
kinesisService.addTagsToStream(name, tags, region);
}
stream = kinesisService.describeStream(name, region);
} else {
stream = kinesisService.createStream(name, shardCount, streamMode, region);
if (retention != null) {
stream.setRetentionPeriodHours(retention);
}
if (!tags.isEmpty()) {
stream.getTags().putAll(tags);
}
deleteRenamedResource(priorPhysicalId, name, id -> kinesisService.deleteStream(id, region),
"Kinesis stream");
}
// Ref returns the stream name; Fn::GetAtt Arn returns the stream ARN.
r.setPhysicalId(name);
r.getAttributes().put("Arn", stream.getStreamArn());
}
// ── CloudWatch ──────────────────────────────────────────────────────────────
private void provisionCloudWatchAlarm(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region, String stackName) {
String name = resolveOptional(props, "AlarmName", engine);
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 255, false);
}
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName(name);
alarm.setAlarmDescription(resolveOptional(props, "AlarmDescription", engine));
alarm.setMetricName(resolveOptional(props, "MetricName", engine));
alarm.setNamespace(resolveOptional(props, "Namespace", engine));
alarm.setStatistic(resolveOptional(props, "Statistic", engine));
alarm.setUnit(resolveOptional(props, "Unit", engine));
alarm.setComparisonOperator(resolveOptional(props, "ComparisonOperator", engine));
alarm.setPeriod(parseIntProp(props, "Period", engine, 60));
alarm.setEvaluationPeriods(parseIntProp(props, "EvaluationPeriods", engine, 1));
alarm.setDatapointsToAlarm(parseIntProp(props, "DatapointsToAlarm", engine, alarm.getEvaluationPeriods()));
String threshold = resolveOptional(props, "Threshold", engine);
if (threshold != null && !threshold.isBlank()) {
try {
alarm.setThreshold(Double.parseDouble(threshold.trim()));
} catch (NumberFormatException ignored) {
// leave default
}
}
String treatMissing = resolveOptional(props, "TreatMissingData", engine);
if (treatMissing != null && !treatMissing.isBlank()) {
alarm.setTreatMissingData(treatMissing);
}
String actionsEnabled = resolveOptional(props, "ActionsEnabled", engine);
alarm.setActionsEnabled(actionsEnabled == null || Boolean.parseBoolean(actionsEnabled));
if (props != null && props.has("Dimensions") && props.get("Dimensions").isArray()) {
List<Dimension> dimensions = new ArrayList<>();
for (JsonNode dim : props.get("Dimensions")) {
dimensions.add(new Dimension(engine.resolve(dim.path("Name")), engine.resolve(dim.path("Value"))));
}
alarm.setDimensions(dimensions);
}
addAlarmActions(props, "AlarmActions", engine, alarm.getAlarmActions());
addAlarmActions(props, "OKActions", engine, alarm.getOkActions());
addAlarmActions(props, "InsufficientDataActions", engine, alarm.getInsufficientDataActions());
cloudWatchMetricsService.putMetricAlarm(alarm, region);
// Ref returns the alarm name; Fn::GetAtt Arn returns the alarm ARN.
r.setPhysicalId(name);
r.getAttributes().put("Arn", alarm.getAlarmArn());
}
private void addAlarmActions(JsonNode props, String field, CloudFormationTemplateEngine engine,
List<String> target) {
if (props != null && props.has(field) && props.get(field).isArray()) {
for (JsonNode action : props.get(field)) {
String resolved = engine.resolve(action);
if (resolved != null && !resolved.isBlank()) {
target.add(resolved);
}
}
}
}
// ── Auto Scaling ────────────────────────────────────────────────────────────
private void provisionLaunchConfiguration(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
@@ -0,0 +1,113 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/** Provisions {@code AWS::CloudWatch::Alarm}. */
@ApplicationScoped
public class CloudWatchCfnProvisioner implements CfnResourceProvisioner {
private static final int ALARM_NAME_MAX_LENGTH = 255;
private static final int DEFAULT_PERIOD_SECONDS = 60;
private static final int DEFAULT_EVALUATION_PERIODS = 1;
private final CloudWatchMetricsService cloudWatchMetricsService;
public CloudWatchCfnProvisioner(CloudWatchMetricsService cloudWatchMetricsService) {
this.cloudWatchMetricsService = cloudWatchMetricsService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::CloudWatch::Alarm");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String name = ctx.resolveOptional(props, "AlarmName");
if (name == null || name.isBlank()) {
name = ctx.generatePhysicalName(r.getLogicalId(), ALARM_NAME_MAX_LENGTH, false);
}
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName(name);
alarm.setAlarmDescription(ctx.resolveOptional(props, "AlarmDescription"));
alarm.setMetricName(ctx.resolveOptional(props, "MetricName"));
alarm.setNamespace(ctx.resolveOptional(props, "Namespace"));
alarm.setStatistic(ctx.resolveOptional(props, "Statistic"));
alarm.setUnit(ctx.resolveOptional(props, "Unit"));
alarm.setComparisonOperator(ctx.resolveOptional(props, "ComparisonOperator"));
alarm.setPeriod(parseIntProp(props, "Period", ctx, DEFAULT_PERIOD_SECONDS));
alarm.setEvaluationPeriods(parseIntProp(props, "EvaluationPeriods", ctx, DEFAULT_EVALUATION_PERIODS));
alarm.setDatapointsToAlarm(
parseIntProp(props, "DatapointsToAlarm", ctx, alarm.getEvaluationPeriods()));
String threshold = ctx.resolveOptional(props, "Threshold");
if (threshold != null && !threshold.isBlank()) {
try {
alarm.setThreshold(Double.parseDouble(threshold.trim()));
} catch (NumberFormatException ignored) {
// leave default
}
}
String treatMissing = ctx.resolveOptional(props, "TreatMissingData");
if (treatMissing != null && !treatMissing.isBlank()) {
alarm.setTreatMissingData(treatMissing);
}
String actionsEnabled = ctx.resolveOptional(props, "ActionsEnabled");
alarm.setActionsEnabled(actionsEnabled == null || Boolean.parseBoolean(actionsEnabled));
if (props != null && props.has("Dimensions") && props.get("Dimensions").isArray()) {
List<Dimension> dimensions = new ArrayList<>();
for (JsonNode dim : props.get("Dimensions")) {
dimensions.add(new Dimension(ctx.engine().resolve(dim.path("Name")),
ctx.engine().resolve(dim.path("Value"))));
}
alarm.setDimensions(dimensions);
}
addAlarmActions(props, "AlarmActions", ctx, alarm.getAlarmActions());
addAlarmActions(props, "OKActions", ctx, alarm.getOkActions());
addAlarmActions(props, "InsufficientDataActions", ctx, alarm.getInsufficientDataActions());
cloudWatchMetricsService.putMetricAlarm(alarm, ctx.region());
// Ref returns the alarm name; Fn::GetAtt Arn returns the alarm ARN.
r.setPhysicalId(name);
r.getAttributes().put("Arn", alarm.getAlarmArn());
}
private void addAlarmActions(JsonNode props, String field, ProvisionContext ctx, List<String> target) {
if (props != null && props.has(field) && props.get(field).isArray()) {
for (JsonNode action : props.get(field)) {
String resolved = ctx.engine().resolve(action);
if (resolved != null && !resolved.isBlank()) {
target.add(resolved);
}
}
}
}
/** Copied from the monolith, which still has callers for it. */
private int parseIntProp(JsonNode props, String name, ProvisionContext ctx, int fallback) {
String value = ctx.resolveOptional(props, name);
if (value == null || value.isBlank()) {
return fallback;
}
try {
return Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
return fallback;
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
cloudWatchMetricsService.deleteAlarms(List.of(physicalId), region);
}
}
@@ -0,0 +1,167 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
/** Provisions {@code AWS::Kinesis::Stream}. */
@ApplicationScoped
public class KinesisCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(KinesisCfnProvisioner.class);
private static final int STREAM_NAME_MAX_LENGTH = 128;
private static final int DEFAULT_SHARD_COUNT = 1;
private static final String DEFAULT_STREAM_MODE = "PROVISIONED";
private final KinesisService kinesisService;
public KinesisCfnProvisioner(KinesisService kinesisService) {
this.kinesisService = kinesisService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::Kinesis::Stream");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String explicitName = ctx.resolveOptional(props, "Name");
String priorPhysicalId = ctx.priorPhysicalId();
String name;
if (explicitName != null && !explicitName.isBlank()) {
name = explicitName;
} else if (priorPhysicalId != null) {
name = priorPhysicalId;
} else {
name = ctx.generatePhysicalName(r.getLogicalId(), STREAM_NAME_MAX_LENGTH, false);
}
String streamMode = null;
if (props != null && props.has("StreamModeDetails")) {
streamMode = ctx.engine().resolve(props.get("StreamModeDetails").path("StreamMode"));
if (streamMode != null && streamMode.isBlank()) {
streamMode = null;
}
}
// ShardCount is required for PROVISIONED streams; default to 1 when unset (ON_DEMAND ignores it).
int shardCount = DEFAULT_SHARD_COUNT;
String shards = ctx.resolveOptional(props, "ShardCount");
if (shards != null && !shards.isBlank()) {
try {
shardCount = Integer.parseInt(shards.trim());
} catch (NumberFormatException ignored) {
// keep default
}
}
Integer retention = null;
String retentionProp = ctx.resolveOptional(props, "RetentionPeriodHours");
if (retentionProp != null && !retentionProp.isBlank()) {
try {
retention = Integer.parseInt(retentionProp.trim());
} catch (NumberFormatException ignored) {
// leave default
}
}
Map<String, String> tags = new LinkedHashMap<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
String key = ctx.engine().resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, ctx.engine().resolve(tag.path("Value")));
}
}
}
// provision() re-runs on every UpdateStack, so a same-named stream already on file must be
// reconciled instead of re-created (createStream throws ResourceInUseException). ShardCount
// changes aren't reconciled here: KinesisService has no UpdateShardCount support to call into.
KinesisStream stream = sameNameExistingResource(priorPhysicalId, name,
n -> kinesisService.describeStream(n, ctx.region()));
if (stream != null) {
kinesisService.updateStreamMode(name,
streamMode != null ? streamMode : DEFAULT_STREAM_MODE, ctx.region());
if (retention != null) {
if (retention > stream.getRetentionPeriodHours()) {
kinesisService.increaseStreamRetentionPeriod(name, retention, ctx.region());
} else if (retention < stream.getRetentionPeriodHours()) {
kinesisService.decreaseStreamRetentionPeriod(name, retention, ctx.region());
}
}
Map<String, String> existingTags = kinesisService.listTagsForStream(name, ctx.region());
List<String> tagsToRemove = existingTags.keySet().stream()
.filter(key -> !tags.containsKey(key))
.toList();
if (!tagsToRemove.isEmpty()) {
kinesisService.removeTagsFromStream(name, tagsToRemove, ctx.region());
}
if (!tags.isEmpty()) {
kinesisService.addTagsToStream(name, tags, ctx.region());
}
stream = kinesisService.describeStream(name, ctx.region());
} else {
stream = kinesisService.createStream(name, shardCount, streamMode, ctx.region());
if (retention != null) {
stream.setRetentionPeriodHours(retention);
}
if (!tags.isEmpty()) {
stream.getTags().putAll(tags);
}
deleteRenamedResource(priorPhysicalId, name,
id -> kinesisService.deleteStream(id, ctx.region()), "Kinesis stream");
}
// Ref returns the stream name; Fn::GetAtt Arn returns the stream ARN.
r.setPhysicalId(name);
r.getAttributes().put("Arn", stream.getStreamArn());
}
/**
* The resource already on file under this same name, or null when this is a create or a rename.
* Copied from the monolith, which still has callers for it.
*/
private <T> T sameNameExistingResource(String priorPhysicalId, String name, Function<String, T> lookup) {
if (priorPhysicalId == null || !priorPhysicalId.equals(name)) {
return null;
}
try {
return lookup.apply(name);
} catch (AwsException notFound) {
// Expected when the resource was deleted out of band since the prior update; the
// caller falls back to creating it fresh under the same name.
LOG.debugv(notFound, "No existing {0} found on file, falling back to create", name);
return null;
}
}
/** Best-effort removal of the old resource after a rename. Copied, as above. */
private void deleteRenamedResource(String priorPhysicalId, String newName, Consumer<String> delete,
String resourceKind) {
if (priorPhysicalId == null || priorPhysicalId.equals(newName)) {
return;
}
try {
delete.accept(priorPhysicalId);
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to delete renamed {0} {1} after replacement by {2}",
resourceKind, priorPhysicalId, newName);
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
kinesisService.deleteStream(physicalId, region);
}
}