Light, fluffy, and always free - The AWS Local Emulator alternative
feat(applicationautoscaling): add Application Auto Scaling control plane (#2159)
Priamo Germosen1795e131a20b
diff --git a/README.md b/README.mdindex c03aeb23ff..f4cb2cd47a 100644--- a/README.md+++ b/README.md@@ -222,7 +222,7 @@ Floci supports local emulation for application services, data services, eventing| Core app services | S3, SQS, SNS, DynamoDB, Lambda, IAM, KMS, Secrets Manager, SSM || Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, CloudWatch Logs, CloudWatch Metrics || API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, ACM, Route53, Cloud Map |-| Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Elastic Beanstalk, ELB v2 |+| Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2 || Data, analytics, and AI | Athena, Glue, EMR, Firehose, OpenSearch, S3 Vectors, Textract, Transcribe, Bedrock Runtime || Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache || Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core |@@ -290,6 +290,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/| CodePipeline | In-process orchestration | Pipelines, executions, S3 artifacts, approvals, local providers, custom workers || AWS Batch | In-process | Compute environments, job queues, job definitions, job submission and lifecycle || Auto Scaling | In-process with reconciler | Launch configs, ASGs, desired capacity reconciliation, lifecycle hooks |+| Application Auto Scaling | In-process | Scalable targets, target-tracking and step scaling policies, CloudWatch alarm creation, tagging (policies are stored but inert) || Elastic Beanstalk | In-process | Applications, application versions, environments, configuration templates, platform and solution stack metadata || AWS Backup | In-process | Vaults, backup plans, selections, simulated job lifecycle, recovery points || AWS Config | In-process | Config rules, configuration recorders, delivery channels, conformance packs, tagging |diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tfindex 8f20d7410c..b9e5e9eecc 100644--- a/compatibility-tests/compat-terraform/main.tf+++ b/compatibility-tests/compat-terraform/main.tf@@ -365,3 +365,60 @@ resource "aws_kinesis_firehose_delivery_stream" "events" {output "firehose_stream_arn" {value = aws_kinesis_firehose_delivery_stream.events.arn}++# -- Application Auto Scaling (scalable target + target-tracking policies) -----+resource "aws_appautoscaling_target" "ecs_service" {+ max_capacity = 20+ min_capacity = 2+ resource_id = "service/floci-compat-cluster/floci-compat-service"+ scalable_dimension = "ecs:service:DesiredCount"+ service_namespace = "ecs"++ tags = {+ Environment = "compat-test"+ }+}++resource "aws_appautoscaling_policy" "ecs_cpu" {+ name = "floci-compat-cpu-tracking"+ policy_type = "TargetTrackingScaling"+ resource_id = aws_appautoscaling_target.ecs_service.resource_id+ scalable_dimension = aws_appautoscaling_target.ecs_service.scalable_dimension+ service_namespace = aws_appautoscaling_target.ecs_service.service_namespace++ target_tracking_scaling_policy_configuration {+ predefined_metric_specification {+ predefined_metric_type = "ECSServiceAverageCPUUtilization"+ }+ target_value = 65+ }+}++# resource_label round-trips only if every nested field is echoed back, so this+# resource is the canary for target-tracking drift.+resource "aws_appautoscaling_policy" "ecs_alb_requests" {+ name = "floci-compat-alb-request-count"+ policy_type = "TargetTrackingScaling"+ resource_id = aws_appautoscaling_target.ecs_service.resource_id+ scalable_dimension = aws_appautoscaling_target.ecs_service.scalable_dimension+ service_namespace = aws_appautoscaling_target.ecs_service.service_namespace++ target_tracking_scaling_policy_configuration {+ target_value = 1000+ scale_in_cooldown = 240+ scale_out_cooldown = 60++ predefined_metric_specification {+ predefined_metric_type = "ALBRequestCountPerTarget"+ resource_label = "app/floci-compat-alb/abc123/targetgroup/floci-compat-tg/def456"+ }+ }+}++output "appautoscaling_target_arn" {+ value = aws_appautoscaling_target.ecs_service.arn+}++output "appautoscaling_alb_policy_arn" {+ value = aws_appautoscaling_policy.ecs_alb_requests.arn+}diff --git a/compatibility-tests/compat-terraform/provider.tf b/compatibility-tests/compat-terraform/provider.tfindex df29f496ba..ee78c1f248 100644--- a/compatibility-tests/compat-terraform/provider.tf+++ b/compatibility-tests/compat-terraform/provider.tf@@ -39,5 +39,6 @@ provider "aws" {cloudwatch = var.endpointec2 = var.endpointroute53 = var.endpoint+ appautoscaling = var.endpoint}}diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.batsindex 5be9906bb9..d3de701ff7 100644--- a/compatibility-tests/compat-terraform/test/terraform.bats+++ b/compatibility-tests/compat-terraform/test/terraform.bats@@ -211,3 +211,60 @@ setup() {assert_successassert_output "GZIP"}++@test "Terraform: Application Auto Scaling scalable target created with tags" {+ run aws_cmd application-autoscaling describe-scalable-targets --service-namespace ecs \+ --resource-ids service/floci-compat-cluster/floci-compat-service \+ --query "ScalableTargets[0].MaxCapacity" --output text+ assert_success+ assert_output "20"++ run aws_cmd application-autoscaling describe-scalable-targets --service-namespace ecs \+ --resource-ids service/floci-compat-cluster/floci-compat-service \+ --query "ScalableTargets[0].ScalableTargetARN" --output text+ assert_success+ [[ "$output" == arn:aws:application-autoscaling:* ]]++ run aws_cmd application-autoscaling list-tags-for-resource --resource-arn "$output" \+ --query "Tags.Environment" --output text+ assert_success+ assert_output "compat-test"+}++@test "Terraform: Application Auto Scaling target-tracking policy round-trips resource_label" {+ run aws_cmd application-autoscaling describe-scaling-policies --service-namespace ecs \+ --resource-id service/floci-compat-cluster/floci-compat-service \+ --query "ScalingPolicies[?PolicyName=='floci-compat-alb-request-count'].TargetTrackingScalingPolicyConfiguration.PredefinedMetricSpecification.ResourceLabel | [0]" \+ --output text+ assert_success+ assert_output "app/floci-compat-alb/abc123/targetgroup/floci-compat-tg/def456"++ run aws_cmd application-autoscaling describe-scaling-policies --service-namespace ecs \+ --resource-id service/floci-compat-cluster/floci-compat-service \+ --query "ScalingPolicies[?PolicyName=='floci-compat-alb-request-count'].TargetTrackingScalingPolicyConfiguration.ScaleInCooldown | [0]" \+ --output text+ assert_success+ assert_output "240"+}++# A successful apply proves very little on its own: a response that silently drops a+# field still applies cleanly, and only shows up later as perpetual drift. Asserting an+# empty second plan is what actually catches that class of bug.+#+# Scoped to the Application Auto Scaling resources deliberately. A whole-config re-plan+# currently reports drift on aws_cognito_user_pool, aws_db_instance+# (auto_minor_version_upgrade) and aws_kinesis_firehose_delivery_stream+# (s3_backup_mode) — pre-existing and unrelated to these resources. Widen this to the+# full configuration once those are fixed.+@test "Terraform: re-planning Application Auto Scaling reports no changes" {+ cd "$TF_DIR"+ run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode \+ -target=aws_appautoscaling_target.ecs_service \+ -target=aws_appautoscaling_policy.ecs_cpu \+ -target=aws_appautoscaling_policy.ecs_alb_requests+ if [ "$status" -eq 2 ]; then+ echo "# drift detected on re-plan:" >&3+ echo "$output" >&3+ fi+ [ "$status" -eq 0 ]+}diff --git a/docs/services/applicationautoscaling.md b/docs/services/applicationautoscaling.mdnew file mode 100644index 0000000000..c20dc05a29--- /dev/null+++ b/docs/services/applicationautoscaling.md@@ -0,0 +1,105 @@+# Application Auto Scaling++**Protocol:** JSON 1.1 (`X-Amz-Target: AnyScaleFrontendService.*`)+**Endpoint:** `POST http://localhost:4566/`+**Signing name:** `application-autoscaling`++Application Auto Scaling is the API behind `aws_appautoscaling_target` and+`aws_appautoscaling_policy`, and is what scales ECS services, MSK broker storage,+DynamoDB capacity, Lambda provisioned concurrency, and similar resources.++It is **not** the same service as [Auto Scaling](autoscaling.md), which scales EC2+Auto Scaling groups over the Query protocol under the `autoscaling` signing name.++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `RegisterScalableTarget` | Registers or updates a scalable target and returns its ARN |+| `DescribeScalableTargets` | Lists scalable targets in a namespace, optionally filtered |+| `DeregisterScalableTarget` | Deregisters a target and deletes its policies and alarms |+| `PutScalingPolicy` | Creates or updates a scaling policy and its CloudWatch alarms |+| `DescribeScalingPolicies` | Lists scaling policies in a namespace, optionally filtered |+| `DeleteScalingPolicy` | Deletes a scaling policy and its CloudWatch alarms |+| `ListTagsForResource` | Returns the tags on a scalable target |+| `TagResource` | Adds or overwrites tags on a scalable target |+| `UntagResource` | Removes tags from a scalable target |+<!-- floci:actions:end -->++## Identity++A scalable target is keyed by the triple **(ServiceNamespace, ResourceId,+ScalableDimension)** — there is no separate identifier. `RegisterScalableTarget` is an+upsert on that triple: parameters you omit are left unchanged, matching AWS.++A scaling policy is keyed by that same triple plus `PolicyName`.++Both `ServiceNamespace` and `ScalableDimension` are validated against the AWS enums; an+unknown value returns `ValidationException`.++## ARN formats++The two ARN families deliberately use different service names, mirroring AWS:++```+ScalableTargetARN arn:aws:application-autoscaling:<region>:<account>:scalable-target/<id>+PolicyARN arn:aws:autoscaling:<region>:<account>:scalingPolicy:<uuid>:resource/<namespace>/<resourceId>:policyName/<name>+```++`ScalableTargetARN` is the tagging identifier. The Terraform AWS provider reads it from+`DescribeScalableTargets` into the resource's `arn` attribute and then passes it to+`ListTagsForResource` on every read, so it is always populated.++## CloudWatch alarms++A `TargetTrackingScaling` policy creates a real pair of CloudWatch alarms, exactly as AWS+does on your behalf:++```+TargetTracking-<resourceId>-AlarmHigh-<uuid>+TargetTracking-<resourceId>-AlarmLow-<uuid>+```++They are visible through `DescribeAlarms` and are deleted when the policy is deleted or+its scalable target is deregistered.++## Service-linked roles++When `RoleARN` is omitted, Floci synthesizes and returns a service-linked role ARN in the+AWS shape, since the provider treats the attribute as computed:++```+arn:aws:iam::<account>:role/aws-service-role/<namespace>.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_<Suffix>+```++## Limitations++- **Scaling policies are stored but inert.** Nothing evaluates them, no alarm ever fires,+ and no capacity is ever adjusted — an ECS service's desired count will not change, and+ MSK broker storage will not grow. This matches the existing behavior of EC2 Auto+ Scaling's `PutScalingPolicy` in Floci. The control plane is faithful; the control loop+ is not emulated.+- `PutScheduledAction`, `DescribeScheduledActions`, and `DeleteScheduledAction` are not+ implemented.+- `DescribeScalingActivities` is not implemented; there are no scaling activities to+ report because policies never fire.+- `PredictiveScalingPolicyConfiguration` is accepted only insofar as `PolicyType` is+ validated; the configuration block is not stored.+- Pagination is not implemented — `DescribeScalableTargets` and `DescribeScalingPolicies`+ return all matching results and never emit a `NextToken`.++## Terraform++Point the `appautoscaling` endpoint at Floci:++```hcl+provider "aws" {+ endpoints {+ appautoscaling = "http://localhost:4566"+ }+}+```++`aws_appautoscaling_target` and `aws_appautoscaling_policy` support create, read, update,+and delete, and converge to a clean plan.diff --git a/docs/services/index.md b/docs/services/index.mdindex 9abd5c26c9..f8b6969bfc 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -1,6 +1,6 @@# Services Overview-Floci emulates 69 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.+Floci emulates 70 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.@@ -63,6 +63,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [ELB v2](elb.md) | `POST /` with `Action=` param | Query | 34 || [WAF v2](wafv2.md) | `POST /` + `X-Amz-Target: AWSWAF_20190729.*` | JSON 1.1 | 35 || [Auto Scaling](autoscaling.md) | `POST /` with `Action=` param | Query | 33 |+| [Application Auto Scaling](applicationautoscaling.md) | `POST /` + `X-Amz-Target: AnyScaleFrontendService.*` | JSON 1.1 | 9 || [Elastic Beanstalk](elastic-beanstalk.md) | `POST /` with `Action=` or `Operation=` param | Query | 14 || [CodeBuild](codebuild.md) | `POST /` + `X-Amz-Target: CodeBuild_20161006.*` | JSON 1.1 | 20 || [AWS Batch](batch.md) | `/v1/...` | REST JSON | 10 |diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 7cc50c1f9f..d1c7771781 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -570,6 +570,7 @@ public interface EmulatorConfig {CodeDeployServiceConfig codedeploy();CodePipelineServiceConfig codepipeline();AutoScalingServiceConfig autoscaling();+ ApplicationAutoScalingServiceConfig applicationautoscaling();ElasticBeanstalkServiceConfig elasticbeanstalk();BackupServiceConfig backup();NeptuneServiceConfig neptune();@@ -693,6 +694,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface ApplicationAutoScalingServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface ElasticBeanstalkServiceConfig {@WithDefault("true")boolean enabled();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.javaindex 6a048759b6..2bc6ffbcb5 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTimport io.github.hectorvent.floci.services.bcmdataexports.BcmDataExportsJsonHandler;import io.github.hectorvent.floci.services.ce.CostExplorerJsonHandler;import io.github.hectorvent.floci.services.cloudtrail.CloudTrailJsonHandler;+import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingJsonHandler;import io.github.hectorvent.floci.services.cloudcontrol.CloudControlJsonHandler;import io.github.hectorvent.floci.services.configservice.ConfigServiceJsonHandler;import io.github.hectorvent.floci.services.cur.CurJsonHandler;@@ -99,6 +100,7 @@ public class AwsJson11Controller {private final CloudTrailJsonHandler cloudTrailJsonHandler;private final LightsailJsonHandler lightsailJsonHandler;private final CloudControlJsonHandler cloudControlJsonHandler;+ private final ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler;@Injectpublic AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,@@ -132,7 +134,8 @@ public class AwsJson11Controller {ConfigServiceJsonHandler configServiceJsonHandler,CloudTrailJsonHandler cloudTrailJsonHandler,LightsailJsonHandler lightsailJsonHandler,- CloudControlJsonHandler cloudControlJsonHandler) {+ CloudControlJsonHandler cloudControlJsonHandler,+ ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler) {this.objectMapper = objectMapper;this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);this.catalog = catalog;@@ -171,6 +174,7 @@ public class AwsJson11Controller {this.cloudTrailJsonHandler = cloudTrailJsonHandler;this.lightsailJsonHandler = lightsailJsonHandler;this.cloudControlJsonHandler = cloudControlJsonHandler;+ this.applicationAutoScalingJsonHandler = applicationAutoScalingJsonHandler;}@POST@@ -238,6 +242,7 @@ public class AwsJson11Controller {case "bcm-data-exports" -> bcmDataExportsJsonHandler.handle(action, request, region);case "config" -> configServiceJsonHandler.handle(action, request, region);case "cloudtrail" -> cloudTrailJsonHandler.handle(action, request, region);+ case "application-autoscaling" -> applicationAutoScalingJsonHandler.handle(action, request, region);case "lightsail" -> lightsailJsonHandler.handle(action, request, region);case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);default -> null;diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex c1a0e1f882..0bf6858f9b 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -330,6 +330,12 @@ public class ResolvedServiceCatalog {"autoscaling", config.storage().mode(), 5000L, AwsNamespaces.AUTOSCALING, ServiceProtocol.QUERY,protocols(ServiceProtocol.QUERY),Set.of(), Set.of("autoscaling"), Set.of(), Set.of()),+ descriptor("application-autoscaling", "applicationautoscaling",+ config.services().applicationautoscaling().enabled(), true,+ "applicationautoscaling", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,+ protocols(ServiceProtocol.JSON),+ Set.of("AnyScaleFrontendService."), Set.of("application-autoscaling"),+ Set.of(), Set.of()),descriptor("elasticbeanstalk", "elasticbeanstalk",config.services().elasticbeanstalk().enabled(), true,"elasticbeanstalk",diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.javanew file mode 100644index 0000000000..b75f5d9e90--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.java@@ -0,0 +1,395 @@+package io.github.hectorvent.floci.services.applicationautoscaling;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.services.applicationautoscaling.model.Alarm;+import io.github.hectorvent.floci.services.applicationautoscaling.model.PredefinedMetricSpecification;+import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget;+import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;+import io.github.hectorvent.floci.services.applicationautoscaling.model.StepAdjustment;+import io.github.hectorvent.floci.services.applicationautoscaling.model.StepScalingConfiguration;+import io.github.hectorvent.floci.services.applicationautoscaling.model.SuspendedState;+import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import jakarta.ws.rs.core.Response;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.Iterator;+import java.util.List;+import java.util.Map;++/**+ * JSON 1.1 handler for the Application Auto Scaling API.+ *+ * <p>Requests arrive with the {@code AnyScaleFrontendService.} target prefix and are signed+ * with the {@code application-autoscaling} credential scope.</p>+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/Welcome.html">Application Auto Scaling API Reference</a>+ */+@ApplicationScoped+public class ApplicationAutoScalingJsonHandler {++ private static final Logger LOG = Logger.getLogger(ApplicationAutoScalingJsonHandler.class);++ private final ApplicationAutoScalingService service;+ private final ObjectMapper objectMapper;++ @Inject+ public ApplicationAutoScalingJsonHandler(ApplicationAutoScalingService service, ObjectMapper objectMapper) {+ this.service = service;+ this.objectMapper = objectMapper;+ }++ public Response handle(String action, JsonNode request, String region) {+ return switch (action) {+ case "RegisterScalableTarget" -> handleRegisterScalableTarget(request, region);+ case "DescribeScalableTargets" -> handleDescribeScalableTargets(request, region);+ case "DeregisterScalableTarget" -> handleDeregisterScalableTarget(request, region);+ case "PutScalingPolicy" -> handlePutScalingPolicy(request, region);+ case "DescribeScalingPolicies" -> handleDescribeScalingPolicies(request, region);+ case "DeleteScalingPolicy" -> handleDeleteScalingPolicy(request, region);+ case "ListTagsForResource" -> handleListTagsForResource(request, region);+ case "TagResource" -> handleTagResource(request, region);+ case "UntagResource" -> handleUntagResource(request, region);+ default -> Response.status(400)+ .entity(new AwsErrorResponse("UnsupportedOperation",+ "Operation " + action + " is not supported."))+ .build();+ };+ }++ // ---------------------------------------------------------------- scalable targets++ private Response handleRegisterScalableTarget(JsonNode request, String region) {+ ScalableTarget target = service.registerScalableTarget(+ text(request, "ServiceNamespace"),+ text(request, "ResourceId"),+ text(request, "ScalableDimension"),+ integer(request, "MinCapacity"),+ integer(request, "MaxCapacity"),+ text(request, "RoleARN"),+ parseSuspendedState(request.path("SuspendedState")),+ parseTags(request.path("Tags")),+ region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("ScalableTargetARN", target.getScalableTargetArn());+ return Response.ok(response).build();+ }++ private Response handleDescribeScalableTargets(JsonNode request, String region) {+ List<ScalableTarget> found = service.describeScalableTargets(+ text(request, "ServiceNamespace"),+ stringList(request.path("ResourceIds")),+ text(request, "ScalableDimension"),+ region);++ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode array = response.putArray("ScalableTargets");+ found.forEach(t -> array.add(scalableTargetJson(t)));+ return Response.ok(response).build();+ }++ private Response handleDeregisterScalableTarget(JsonNode request, String region) {+ service.deregisterScalableTarget(+ text(request, "ServiceNamespace"),+ text(request, "ResourceId"),+ text(request, "ScalableDimension"),+ region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ // ---------------------------------------------------------------- scaling policies++ private Response handlePutScalingPolicy(JsonNode request, String region) {+ ScalingPolicy policy = service.putScalingPolicy(+ text(request, "PolicyName"),+ text(request, "PolicyType"),+ text(request, "ServiceNamespace"),+ text(request, "ResourceId"),+ text(request, "ScalableDimension"),+ parseTargetTracking(request.path("TargetTrackingScalingPolicyConfiguration")),+ parseStepScaling(request.path("StepScalingPolicyConfiguration")),+ region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("PolicyARN", policy.getPolicyArn());+ ArrayNode alarms = response.putArray("Alarms");+ policy.getAlarms().forEach(a -> alarms.add(alarmJson(a)));+ return Response.ok(response).build();+ }++ private Response handleDescribeScalingPolicies(JsonNode request, String region) {+ List<ScalingPolicy> found = service.describeScalingPolicies(+ text(request, "ServiceNamespace"),+ text(request, "ResourceId"),+ text(request, "ScalableDimension"),+ stringList(request.path("PolicyNames")),+ region);++ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode array = response.putArray("ScalingPolicies");+ found.forEach(p -> array.add(scalingPolicyJson(p)));+ return Response.ok(response).build();+ }++ private Response handleDeleteScalingPolicy(JsonNode request, String region) {+ service.deleteScalingPolicy(+ text(request, "PolicyName"),+ text(request, "ServiceNamespace"),+ text(request, "ResourceId"),+ text(request, "ScalableDimension"),+ region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ // ---------------------------------------------------------------- tagging++ private Response handleListTagsForResource(JsonNode request, String region) {+ Map<String, String> tags = service.listTagsForResource(text(request, "ResourceARN"), region);+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode node = response.putObject("Tags");+ tags.forEach(node::put);+ return Response.ok(response).build();+ }++ private Response handleTagResource(JsonNode request, String region) {+ service.tagResource(text(request, "ResourceARN"), parseTags(request.path("Tags")), region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleUntagResource(JsonNode request, String region) {+ service.untagResource(text(request, "ResourceARN"), stringList(request.path("TagKeys")), region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ // ---------------------------------------------------------------- serialization++ private ObjectNode scalableTargetJson(ScalableTarget t) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("ServiceNamespace", t.getServiceNamespace());+ node.put("ResourceId", t.getResourceId());+ node.put("ScalableDimension", t.getScalableDimension());+ node.put("MinCapacity", t.getMinCapacity());+ node.put("MaxCapacity", t.getMaxCapacity());+ node.put("RoleARN", t.getRoleArn());+ node.put("ScalableTargetARN", t.getScalableTargetArn());+ node.put("CreationTime", t.getCreationTime());++ SuspendedState state = t.getSuspendedState();+ ObjectNode suspended = node.putObject("SuspendedState");+ suspended.put("DynamicScalingInSuspended", state.isDynamicScalingInSuspended());+ suspended.put("DynamicScalingOutSuspended", state.isDynamicScalingOutSuspended());+ suspended.put("ScheduledScalingSuspended", state.isScheduledScalingSuspended());+ return node;+ }++ private ObjectNode scalingPolicyJson(ScalingPolicy p) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("PolicyARN", p.getPolicyArn());+ node.put("PolicyName", p.getPolicyName());+ node.put("PolicyType", p.getPolicyType());+ node.put("ServiceNamespace", p.getServiceNamespace());+ node.put("ResourceId", p.getResourceId());+ node.put("ScalableDimension", p.getScalableDimension());+ node.put("CreationTime", p.getCreationTime());++ ArrayNode alarms = node.putArray("Alarms");+ p.getAlarms().forEach(a -> alarms.add(alarmJson(a)));++ if (p.getTargetTrackingConfiguration() != null) {+ node.set("TargetTrackingScalingPolicyConfiguration",+ targetTrackingJson(p.getTargetTrackingConfiguration()));+ }+ if (p.getStepScalingConfiguration() != null) {+ node.set("StepScalingPolicyConfiguration", stepScalingJson(p.getStepScalingConfiguration()));+ }+ return node;+ }++ /**+ * Emits only the fields that were supplied. Defaulting absent optionals here would make+ * Terraform see a value it never configured and report perpetual drift.+ */+ private ObjectNode targetTrackingJson(TargetTrackingConfiguration config) {+ ObjectNode node = objectMapper.createObjectNode();+ if (config.getTargetValue() != null) {+ node.put("TargetValue", config.getTargetValue());+ }+ if (config.getPredefinedMetricSpecification() != null) {+ PredefinedMetricSpecification spec = config.getPredefinedMetricSpecification();+ ObjectNode specNode = node.putObject("PredefinedMetricSpecification");+ specNode.put("PredefinedMetricType", spec.getPredefinedMetricType());+ if (spec.getResourceLabel() != null) {+ specNode.put("ResourceLabel", spec.getResourceLabel());+ }+ }+ if (config.getCustomizedMetricSpecification() != null) {+ node.set("CustomizedMetricSpecification",+ objectMapper.valueToTree(config.getCustomizedMetricSpecification()));+ }+ if (config.getDisableScaleIn() != null) {+ node.put("DisableScaleIn", config.getDisableScaleIn());+ }+ if (config.getScaleInCooldown() != null) {+ node.put("ScaleInCooldown", config.getScaleInCooldown());+ }+ if (config.getScaleOutCooldown() != null) {+ node.put("ScaleOutCooldown", config.getScaleOutCooldown());+ }+ return node;+ }++ private ObjectNode stepScalingJson(StepScalingConfiguration config) {+ ObjectNode node = objectMapper.createObjectNode();+ if (config.getAdjustmentType() != null) {+ node.put("AdjustmentType", config.getAdjustmentType());+ }+ if (config.getCooldown() != null) {+ node.put("Cooldown", config.getCooldown());+ }+ if (config.getMetricAggregationType() != null) {+ node.put("MetricAggregationType", config.getMetricAggregationType());+ }+ if (config.getMinAdjustmentMagnitude() != null) {+ node.put("MinAdjustmentMagnitude", config.getMinAdjustmentMagnitude());+ }+ if (!config.getStepAdjustments().isEmpty()) {+ ArrayNode steps = node.putArray("StepAdjustments");+ for (StepAdjustment step : config.getStepAdjustments()) {+ ObjectNode stepNode = steps.addObject();+ if (step.getMetricIntervalLowerBound() != null) {+ stepNode.put("MetricIntervalLowerBound", step.getMetricIntervalLowerBound());+ }+ if (step.getMetricIntervalUpperBound() != null) {+ stepNode.put("MetricIntervalUpperBound", step.getMetricIntervalUpperBound());+ }+ if (step.getScalingAdjustment() != null) {+ stepNode.put("ScalingAdjustment", step.getScalingAdjustment());+ }+ }+ }+ return node;+ }++ private ObjectNode alarmJson(Alarm alarm) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("AlarmName", alarm.getAlarmName());+ node.put("AlarmARN", alarm.getAlarmArn());+ return node;+ }++ // ---------------------------------------------------------------- parsing++ private SuspendedState parseSuspendedState(JsonNode node) {+ if (node == null || node.isMissingNode() || node.isNull()) {+ return null;+ }+ SuspendedState state = new SuspendedState();+ state.setDynamicScalingInSuspended(node.path("DynamicScalingInSuspended").asBoolean(false));+ state.setDynamicScalingOutSuspended(node.path("DynamicScalingOutSuspended").asBoolean(false));+ state.setScheduledScalingSuspended(node.path("ScheduledScalingSuspended").asBoolean(false));+ return state;+ }++ private TargetTrackingConfiguration parseTargetTracking(JsonNode node) {+ if (node == null || node.isMissingNode() || node.isNull()) {+ return null;+ }+ TargetTrackingConfiguration config = new TargetTrackingConfiguration();+ if (node.hasNonNull("TargetValue")) {+ config.setTargetValue(node.get("TargetValue").asDouble());+ }+ JsonNode predefined = node.path("PredefinedMetricSpecification");+ if (predefined.isObject()) {+ PredefinedMetricSpecification spec = new PredefinedMetricSpecification();+ spec.setPredefinedMetricType(text(predefined, "PredefinedMetricType"));+ spec.setResourceLabel(text(predefined, "ResourceLabel"));+ config.setPredefinedMetricSpecification(spec);+ }+ JsonNode customized = node.path("CustomizedMetricSpecification");+ if (customized.isObject()) {+ config.setCustomizedMetricSpecification(+ objectMapper.convertValue(customized, new com.fasterxml.jackson.core.type.TypeReference<>() {}));+ }+ if (node.hasNonNull("DisableScaleIn")) {+ config.setDisableScaleIn(node.get("DisableScaleIn").asBoolean());+ }+ if (node.hasNonNull("ScaleInCooldown")) {+ config.setScaleInCooldown(node.get("ScaleInCooldown").asInt());+ }+ if (node.hasNonNull("ScaleOutCooldown")) {+ config.setScaleOutCooldown(node.get("ScaleOutCooldown").asInt());+ }+ return config;+ }++ private StepScalingConfiguration parseStepScaling(JsonNode node) {+ if (node == null || node.isMissingNode() || node.isNull()) {+ return null;+ }+ StepScalingConfiguration config = new StepScalingConfiguration();+ config.setAdjustmentType(text(node, "AdjustmentType"));+ config.setMetricAggregationType(text(node, "MetricAggregationType"));+ if (node.hasNonNull("Cooldown")) {+ config.setCooldown(node.get("Cooldown").asInt());+ }+ if (node.hasNonNull("MinAdjustmentMagnitude")) {+ config.setMinAdjustmentMagnitude(node.get("MinAdjustmentMagnitude").asInt());+ }+ List<StepAdjustment> steps = new ArrayList<>();+ for (JsonNode stepNode : node.path("StepAdjustments")) {+ StepAdjustment step = new StepAdjustment();+ if (stepNode.hasNonNull("MetricIntervalLowerBound")) {+ step.setMetricIntervalLowerBound(stepNode.get("MetricIntervalLowerBound").asDouble());+ }+ if (stepNode.hasNonNull("MetricIntervalUpperBound")) {+ step.setMetricIntervalUpperBound(stepNode.get("MetricIntervalUpperBound").asDouble());+ }+ if (stepNode.hasNonNull("ScalingAdjustment")) {+ step.setScalingAdjustment(stepNode.get("ScalingAdjustment").asInt());+ }+ steps.add(step);+ }+ config.setStepAdjustments(steps);+ return config;+ }++ private Map<String, String> parseTags(JsonNode node) {+ if (node == null || !node.isObject()) {+ return null;+ }+ Map<String, String> tags = new HashMap<>();+ Iterator<Map.Entry<String, JsonNode>> fields = node.fields();+ while (fields.hasNext()) {+ Map.Entry<String, JsonNode> entry = fields.next();+ tags.put(entry.getKey(), entry.getValue().asText());+ }+ return tags;+ }++ private static List<String> stringList(JsonNode node) {+ if (node == null || !node.isArray()) {+ return List.of();+ }+ List<String> values = new ArrayList<>();+ node.forEach(item -> values.add(item.asText()));+ return values;+ }++ private static String text(JsonNode node, String field) {+ JsonNode value = node.path(field);+ return value.isMissingNode() || value.isNull() ? null : value.asText();+ }++ private static Integer integer(JsonNode node, String field) {+ JsonNode value = node.path(field);+ return value.isMissingNode() || value.isNull() ? null : value.asInt();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.javanew file mode 100644index 0000000000..96a17b201f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java@@ -0,0 +1,493 @@+package io.github.hectorvent.floci.services.applicationautoscaling;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.applicationautoscaling.model.Alarm;+import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget;+import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;+import io.github.hectorvent.floci.services.applicationautoscaling.model.StepScalingConfiguration;+import io.github.hectorvent.floci.services.applicationautoscaling.model.SuspendedState;+import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.ArrayList;+import java.util.Comparator;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.UUID;++/**+ * Application Auto Scaling control plane.+ *+ * <p>Scalable targets and scaling policies are stored and described faithfully, but+ * policies are <strong>inert</strong>: nothing evaluates them and no capacity is ever+ * adjusted. This mirrors the existing EC2 Auto Scaling {@code PutScalingPolicy} behaviour+ * and is documented in {@code docs/services/applicationautoscaling.md}.</p>+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/Welcome.html">Application Auto Scaling API Reference</a>+ */+@ApplicationScoped+public class ApplicationAutoScalingService {++ private static final Logger LOG = Logger.getLogger(ApplicationAutoScalingService.class);++ static final Set<String> SERVICE_NAMESPACES = Set.of(+ "ecs", "elasticmapreduce", "ec2", "appstream", "dynamodb", "rds", "sagemaker",+ "custom-resource", "comprehend", "lambda", "cassandra", "kafka", "elasticache",+ "neptune", "workspaces");++ static final Set<String> SCALABLE_DIMENSIONS = Set.of(+ "ecs:service:DesiredCount",+ "ec2:spot-fleet-request:TargetCapacity",+ "elasticmapreduce:instancegroup:InstanceCount",+ "appstream:fleet:DesiredCapacity",+ "dynamodb:table:ReadCapacityUnits",+ "dynamodb:table:WriteCapacityUnits",+ "dynamodb:index:ReadCapacityUnits",+ "dynamodb:index:WriteCapacityUnits",+ "rds:cluster:ReadReplicaCount",+ "sagemaker:variant:DesiredInstanceCount",+ "custom-resource:ResourceType:Property",+ "comprehend:document-classifier-endpoint:DesiredInferenceUnits",+ "comprehend:entity-recognizer-endpoint:DesiredInferenceUnits",+ "lambda:function:ProvisionedConcurrency",+ "cassandra:table:ReadCapacityUnits",+ "cassandra:table:WriteCapacityUnits",+ "kafka:broker-storage:VolumeSize",+ "elasticache:cache-cluster:Nodes",+ "elasticache:replication-group:NodeGroups",+ "elasticache:replication-group:Replicas",+ "neptune:cluster:ReadReplicaCount",+ "sagemaker:variant:DesiredProvisionedConcurrency",+ "sagemaker:inference-component:DesiredCopyCount",+ "workspaces:workspacespool:DesiredUserSessions");++ private static final Set<String> POLICY_TYPES =+ Set.of("StepScaling", "TargetTrackingScaling", "PredictiveScaling");++ private final StorageBackend<String, ScalableTarget> targets;+ private final StorageBackend<String, ScalingPolicy> policies;+ private final RegionResolver regionResolver;+ private final CloudWatchMetricsService cloudWatchMetricsService;++ @Inject+ public ApplicationAutoScalingService(StorageFactory factory,+ RegionResolver regionResolver,+ CloudWatchMetricsService cloudWatchMetricsService) {+ this(factory.create("applicationautoscaling", "application-autoscaling-targets.json",+ new TypeReference<Map<String, ScalableTarget>>() {}),+ factory.create("applicationautoscaling", "application-autoscaling-policies.json",+ new TypeReference<Map<String, ScalingPolicy>>() {}),+ regionResolver,+ cloudWatchMetricsService);+ }++ ApplicationAutoScalingService(StorageBackend<String, ScalableTarget> targets,+ StorageBackend<String, ScalingPolicy> policies,+ RegionResolver regionResolver,+ CloudWatchMetricsService cloudWatchMetricsService) {+ this.targets = targets;+ this.policies = policies;+ this.regionResolver = regionResolver;+ this.cloudWatchMetricsService = cloudWatchMetricsService;+ }++ // ---------------------------------------------------------------- scalable targets++ public ScalableTarget registerScalableTarget(String serviceNamespace, String resourceId,+ String scalableDimension, Integer minCapacity,+ Integer maxCapacity, String roleArn,+ SuspendedState suspendedState,+ Map<String, String> tags, String region) {+ validateTriple(serviceNamespace, resourceId, scalableDimension);++ String key = targetKey(region, serviceNamespace, resourceId, scalableDimension);+ ScalableTarget existing = targets.get(key).orElse(null);++ if (existing == null) {+ if (minCapacity == null || maxCapacity == null) {+ throw new AwsException("ValidationException",+ "Min and max capacity are required when registering a new scalable target.", 400);+ }+ ScalableTarget target = new ScalableTarget();+ target.setServiceNamespace(serviceNamespace);+ target.setResourceId(resourceId);+ target.setScalableDimension(scalableDimension);+ target.setMinCapacity(minCapacity);+ target.setMaxCapacity(maxCapacity);+ target.setRoleArn(roleArn != null ? roleArn : serviceLinkedRoleArn(serviceNamespace));+ target.setScalableTargetArn(buildScalableTargetArn(region));+ target.setCreationTime(nowEpochSeconds());+ target.setSuspendedState(suspendedState != null ? suspendedState : new SuspendedState());+ if (tags != null) {+ target.setTags(tags);+ }+ targets.put(key, target);+ LOG.infov("RegisterScalableTarget: {0} {1} {2} in {3}",+ serviceNamespace, resourceId, scalableDimension, region);+ return target;+ }++ // Update semantics: only supplied parameters change.+ if (minCapacity != null) {+ existing.setMinCapacity(minCapacity);+ }+ if (maxCapacity != null) {+ existing.setMaxCapacity(maxCapacity);+ }+ if (roleArn != null) {+ existing.setRoleArn(roleArn);+ }+ if (suspendedState != null) {+ existing.setSuspendedState(suspendedState);+ }+ if (tags != null && !tags.isEmpty()) {+ existing.putTags(tags);+ }+ targets.put(key, existing);+ LOG.infov("RegisterScalableTarget (update): {0} {1} {2} in {3}",+ serviceNamespace, resourceId, scalableDimension, region);+ return existing;+ }++ public List<ScalableTarget> describeScalableTargets(String serviceNamespace, List<String> resourceIds,+ String scalableDimension, String region) {+ requireNamespace(serviceNamespace);+ if (scalableDimension != null && (resourceIds == null || resourceIds.isEmpty())) {+ throw new AwsException("ValidationException",+ "A resource ID must be specified when a scalable dimension is specified.", 400);+ }+ String prefix = region + "::" + serviceNamespace + "::";+ return targets.scan(k -> k.startsWith(prefix)).stream()+ .filter(t -> resourceIds == null || resourceIds.isEmpty() || resourceIds.contains(t.getResourceId()))+ .filter(t -> scalableDimension == null || scalableDimension.equals(t.getScalableDimension()))+ .sorted(Comparator.comparing(ScalableTarget::getResourceId)+ .thenComparing(ScalableTarget::getScalableDimension))+ .toList();+ }++ /**+ * Deregisters a scalable target and, per AWS semantics, deletes every scaling policy+ * attached to it along with the CloudWatch alarms those policies own.+ */+ public void deregisterScalableTarget(String serviceNamespace, String resourceId,+ String scalableDimension, String region) {+ validateTriple(serviceNamespace, resourceId, scalableDimension);+ String key = targetKey(region, serviceNamespace, resourceId, scalableDimension);+ if (targets.get(key).isEmpty()) {+ throw new AwsException("ObjectNotFoundException",+ "No scalable target found for service namespace: " + serviceNamespace+ + ", resource ID: " + resourceId+ + ", scalable dimension: " + scalableDimension, 400);+ }+ for (ScalingPolicy policy : findPolicies(region, serviceNamespace, resourceId, scalableDimension)) {+ deleteAlarms(policy, region);+ policies.delete(policyKey(region, serviceNamespace, resourceId, scalableDimension, policy.getPolicyName()));+ }+ targets.delete(key);+ LOG.infov("DeregisterScalableTarget: {0} {1} {2} in {3}",+ serviceNamespace, resourceId, scalableDimension, region);+ }++ // ---------------------------------------------------------------- scaling policies++ public ScalingPolicy putScalingPolicy(String policyName, String policyType, String serviceNamespace,+ String resourceId, String scalableDimension,+ TargetTrackingConfiguration targetTracking,+ StepScalingConfiguration stepScaling, String region) {+ validateTriple(serviceNamespace, resourceId, scalableDimension);+ if (policyName == null || policyName.isBlank()) {+ throw new AwsException("ValidationException", "PolicyName is required.", 400);+ }+ if (policyType != null && !POLICY_TYPES.contains(policyType)) {+ throw new AwsException("ValidationException",+ "Unsupported policy type: " + policyType, 400);+ }+ String targetKey = targetKey(region, serviceNamespace, resourceId, scalableDimension);+ if (targets.get(targetKey).isEmpty()) {+ throw new AwsException("ObjectNotFoundException",+ "No scalable target found for service namespace: " + serviceNamespace+ + ", resource ID: " + resourceId+ + ", scalable dimension: " + scalableDimension, 400);+ }++ String key = policyKey(region, serviceNamespace, resourceId, scalableDimension, policyName);+ ScalingPolicy existing = policies.get(key).orElse(null);++ ScalingPolicy policy = existing != null ? existing : new ScalingPolicy();+ policy.setPolicyName(policyName);+ policy.setPolicyType(policyType != null ? policyType : "StepScaling");+ policy.setServiceNamespace(serviceNamespace);+ policy.setResourceId(resourceId);+ policy.setScalableDimension(scalableDimension);+ policy.setTargetTrackingConfiguration(targetTracking);+ policy.setStepScalingConfiguration(stepScaling);+ if (existing == null) {+ policy.setCreationTime(nowEpochSeconds());+ policy.setPolicyArn(buildPolicyArn(region, serviceNamespace, resourceId, policyName));+ }++ if ("TargetTrackingScaling".equals(policy.getPolicyType())) {+ if (existing != null) {+ deleteAlarms(existing, region);+ }+ policy.setAlarms(createTargetTrackingAlarms(policy, region));+ } else {+ policy.setAlarms(new ArrayList<>());+ }++ policies.put(key, policy);+ LOG.infov("PutScalingPolicy: {0} ({1}) for {2} {3} in {4}",+ policyName, policy.getPolicyType(), serviceNamespace, resourceId, region);+ return policy;+ }++ public List<ScalingPolicy> describeScalingPolicies(String serviceNamespace, String resourceId,+ String scalableDimension, List<String> policyNames,+ String region) {+ requireNamespace(serviceNamespace);+ if (scalableDimension != null && (resourceId == null || resourceId.isBlank())) {+ throw new AwsException("ValidationException",+ "A resource ID must be specified when a scalable dimension is specified.", 400);+ }+ String prefix = region + "::" + serviceNamespace + "::";+ return policies.scan(k -> k.startsWith(prefix)).stream()+ .filter(p -> resourceId == null || resourceId.equals(p.getResourceId()))+ .filter(p -> scalableDimension == null || scalableDimension.equals(p.getScalableDimension()))+ .filter(p -> policyNames == null || policyNames.isEmpty() || policyNames.contains(p.getPolicyName()))+ .sorted(Comparator.comparing(ScalingPolicy::getPolicyName))+ .toList();+ }++ public void deleteScalingPolicy(String policyName, String serviceNamespace, String resourceId,+ String scalableDimension, String region) {+ validateTriple(serviceNamespace, resourceId, scalableDimension);+ if (policyName == null || policyName.isBlank()) {+ throw new AwsException("ValidationException", "PolicyName is required.", 400);+ }+ String key = policyKey(region, serviceNamespace, resourceId, scalableDimension, policyName);+ ScalingPolicy policy = policies.get(key).orElseThrow(() -> new AwsException("ObjectNotFoundException",+ "No scaling policy found for service namespace: " + serviceNamespace+ + ", resource ID: " + resourceId+ + ", scalable dimension: " + scalableDimension+ + ", policy name: " + policyName, 400));+ deleteAlarms(policy, region);+ policies.delete(key);+ LOG.infov("DeleteScalingPolicy: {0} for {1} {2} in {3}",+ policyName, serviceNamespace, resourceId, region);+ }++ // ---------------------------------------------------------------- tagging++ public Map<String, String> listTagsForResource(String resourceArn, String region) {+ return findTargetByArn(resourceArn, region).getTags();+ }++ public void tagResource(String resourceArn, Map<String, String> tags, String region) {+ if (tags == null || tags.isEmpty()) {+ throw new AwsException("ValidationException", "Tags are required.", 400);+ }+ ScalableTarget target = findTargetByArn(resourceArn, region);+ target.putTags(tags);+ targets.put(targetKey(region, target.getServiceNamespace(), target.getResourceId(),+ target.getScalableDimension()), target);+ }++ public void untagResource(String resourceArn, List<String> tagKeys, String region) {+ if (tagKeys == null || tagKeys.isEmpty()) {+ throw new AwsException("ValidationException", "TagKeys are required.", 400);+ }+ ScalableTarget target = findTargetByArn(resourceArn, region);+ target.removeTags(tagKeys);+ targets.put(targetKey(region, target.getServiceNamespace(), target.getResourceId(),+ target.getScalableDimension()), target);+ }++ // ---------------------------------------------------------------- internals++ private ScalableTarget findTargetByArn(String resourceArn, String region) {+ if (resourceArn == null || resourceArn.isBlank()) {+ throw new AwsException("ValidationException", "ResourceARN is required.", 400);+ }+ String prefix = region + "::";+ return targets.scan(k -> k.startsWith(prefix)).stream()+ .filter(t -> resourceArn.equals(t.getScalableTargetArn()))+ .findFirst()+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Resource not found: " + resourceArn, 400));+ }++ private List<ScalingPolicy> findPolicies(String region, String serviceNamespace, String resourceId,+ String scalableDimension) {+ String prefix = region + "::" + serviceNamespace + "::";+ return policies.scan(k -> k.startsWith(prefix)).stream()+ .filter(p -> resourceId.equals(p.getResourceId()))+ .filter(p -> scalableDimension.equals(p.getScalableDimension()))+ .toList();+ }++ /**+ * Creates the pair of CloudWatch alarms that AWS provisions on behalf of a target+ * tracking policy. The alarms are real: they show up in DescribeAlarms exactly as they+ * would in AWS, even though nothing evaluates them here.+ */+ private List<Alarm> createTargetTrackingAlarms(ScalingPolicy policy, String region) {+ List<Alarm> alarms = new ArrayList<>();+ for (String suffix : List.of("AlarmHigh", "AlarmLow")) {+ String alarmName = "TargetTracking-" + policy.getResourceId() + "-" + suffix + "-"+ + UUID.randomUUID();+ MetricAlarm alarm = new MetricAlarm();+ alarm.setAlarmName(alarmName);+ alarm.setAlarmDescription("DO NOT EDIT OR DELETE. For TargetTrackingScaling policy "+ + policy.getPolicyArn() + ".");+ alarm.setNamespace(cloudWatchNamespace(policy.getServiceNamespace()));+ alarm.setMetricName(predefinedMetricType(policy));+ alarm.setStatistic("Average");+ alarm.setPeriod(60);+ alarm.setEvaluationPeriods("AlarmHigh".equals(suffix) ? 3 : 15);+ alarm.setThreshold(targetValue(policy));+ alarm.setComparisonOperator("AlarmHigh".equals(suffix)+ ? "GreaterThanThreshold" : "LessThanThreshold");+ alarm.setAlarmActions(List.of(policy.getPolicyArn()));+ cloudWatchMetricsService.putMetricAlarm(alarm, region);+ alarms.add(new Alarm(alarmName, alarm.getAlarmArn()));+ }+ return alarms;+ }++ private void deleteAlarms(ScalingPolicy policy, String region) {+ List<String> names = policy.getAlarms().stream().map(Alarm::getAlarmName).toList();+ if (names.isEmpty()) {+ return;+ }+ try {+ cloudWatchMetricsService.deleteAlarms(names, region);+ } catch (RuntimeException e) {+ // Alarm cleanup is best-effort: a user may have deleted them out of band.+ LOG.debugv(e, "Could not delete target-tracking alarms {0} in {1}", names, region);+ }+ }++ private static String cloudWatchNamespace(String serviceNamespace) {+ return switch (serviceNamespace) {+ case "ecs" -> "AWS/ECS";+ case "kafka" -> "AWS/Kafka";+ case "dynamodb" -> "AWS/DynamoDB";+ case "lambda" -> "AWS/Lambda";+ case "rds" -> "AWS/RDS";+ case "elasticache" -> "AWS/ElastiCache";+ default -> "AWS/" + serviceNamespace.toUpperCase(Locale.ROOT);+ };+ }++ private static String predefinedMetricType(ScalingPolicy policy) {+ TargetTrackingConfiguration config = policy.getTargetTrackingConfiguration();+ if (config != null && config.getPredefinedMetricSpecification() != null+ && config.getPredefinedMetricSpecification().getPredefinedMetricType() != null) {+ return config.getPredefinedMetricSpecification().getPredefinedMetricType();+ }+ return "CustomizedMetric";+ }++ private static double targetValue(ScalingPolicy policy) {+ TargetTrackingConfiguration config = policy.getTargetTrackingConfiguration();+ return config != null && config.getTargetValue() != null ? config.getTargetValue() : 0.0d;+ }++ private void validateTriple(String serviceNamespace, String resourceId, String scalableDimension) {+ requireNamespace(serviceNamespace);+ if (resourceId == null || resourceId.isBlank()) {+ throw new AwsException("ValidationException", "ResourceId is required.", 400);+ }+ if (scalableDimension == null || scalableDimension.isBlank()) {+ throw new AwsException("ValidationException", "ScalableDimension is required.", 400);+ }+ if (!SCALABLE_DIMENSIONS.contains(scalableDimension)) {+ throw new AwsException("ValidationException",+ "Value '" + scalableDimension + "' at 'scalableDimension' failed to satisfy constraint: "+ + "Member must satisfy enum value set.", 400);+ }+ }++ private void requireNamespace(String serviceNamespace) {+ if (serviceNamespace == null || serviceNamespace.isBlank()) {+ throw new AwsException("ValidationException", "ServiceNamespace is required.", 400);+ }+ if (!SERVICE_NAMESPACES.contains(serviceNamespace)) {+ throw new AwsException("ValidationException",+ "Value '" + serviceNamespace + "' at 'serviceNamespace' failed to satisfy constraint: "+ + "Member must satisfy enum value set.", 400);+ }+ }++ /**+ * The scalable-target ARN must match+ * {@code ^arn:.+:application-autoscaling:.+:[0-9]+:scalable-target/[a-zA-Z0-9-]+$},+ * so the suffix is a dashless UUID.+ */+ private String buildScalableTargetArn(String region) {+ String id = UUID.randomUUID().toString().replace("-", "");+ return regionResolver.buildArn("application-autoscaling", region, "scalable-target/" + id);+ }++ /**+ * Policy ARNs use the {@code autoscaling} service name — not+ * {@code application-autoscaling} — and embed the resource path and policy name.+ */+ private String buildPolicyArn(String region, String serviceNamespace, String resourceId, String policyName) {+ String resource = "scalingPolicy:" + UUID.randomUUID()+ + ":resource/" + serviceNamespace + "/" + resourceId+ + ":policyName/" + policyName;+ return regionResolver.buildArn("autoscaling", region, resource);+ }++ /**+ * AWS creates and returns a service-linked role when the caller supplies none, so the+ * emulator synthesizes one in the same shape to keep the Computed attribute stable.+ */+ private String serviceLinkedRoleArn(String serviceNamespace) {+ String suffix = switch (serviceNamespace) {+ case "ecs" -> "ECSService";+ case "kafka" -> "KafkaCluster";+ case "dynamodb" -> "DynamoDBTable";+ case "lambda" -> "LambdaConcurrency";+ case "rds" -> "RDSCluster";+ case "elasticache" -> "ElastiCacheRG";+ default -> "CustomResource";+ };+ return "arn:aws:iam::" + regionResolver.getAccountId()+ + ":role/aws-service-role/" + serviceNamespace + ".application-autoscaling.amazonaws.com/"+ + "AWSServiceRoleForApplicationAutoScaling_" + suffix;+ }++ private static double nowEpochSeconds() {+ Instant now = Instant.now();+ return now.getEpochSecond() + (now.getNano() / 1_000_000 / 1000.0d);+ }++ private static String targetKey(String region, String serviceNamespace, String resourceId,+ String scalableDimension) {+ return region + "::" + serviceNamespace + "::" + scalableDimension + "::" + resourceId;+ }++ private static String policyKey(String region, String serviceNamespace, String resourceId,+ String scalableDimension, String policyName) {+ return targetKey(region, serviceNamespace, resourceId, scalableDimension) + "::" + policyName;+ }++ Optional<ScalableTarget> findTarget(String region, String serviceNamespace, String resourceId,+ String scalableDimension) {+ return targets.get(targetKey(region, serviceNamespace, resourceId, scalableDimension));+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/Alarm.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/Alarm.javanew file mode 100644index 0000000000..b411c7aa3e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/Alarm.java@@ -0,0 +1,29 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * A CloudWatch alarm associated with a scaling policy.+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_Alarm.html">Alarm</a>+ */+@RegisterForReflection+public class Alarm {++ private String alarmName;+ private String alarmArn;++ public Alarm() {+ }++ public Alarm(String alarmName, String alarmArn) {+ this.alarmName = alarmName;+ this.alarmArn = alarmArn;+ }++ public String getAlarmName() { return alarmName; }+ public void setAlarmName(String alarmName) { this.alarmName = alarmName; }++ public String getAlarmArn() { return alarmArn; }+ public void setAlarmArn(String alarmArn) { this.alarmArn = alarmArn; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/PredefinedMetricSpecification.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/PredefinedMetricSpecification.javanew file mode 100644index 0000000000..e8e51bce2f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/PredefinedMetricSpecification.java@@ -0,0 +1,25 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * A predefined metric for a target tracking scaling policy.+ *+ * <p>{@code resourceLabel} is required for load-balancer metrics such as+ * {@code ALBRequestCountPerTarget} and must round-trip exactly, otherwise Terraform+ * reports perpetual drift.</p>+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_PredefinedMetricSpecification.html">PredefinedMetricSpecification</a>+ */+@RegisterForReflection+public class PredefinedMetricSpecification {++ private String predefinedMetricType;+ private String resourceLabel;++ public String getPredefinedMetricType() { return predefinedMetricType; }+ public void setPredefinedMetricType(String v) { this.predefinedMetricType = v; }++ public String getResourceLabel() { return resourceLabel; }+ public void setResourceLabel(String v) { this.resourceLabel = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/ScalableTarget.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/ScalableTarget.javanew file mode 100644index 0000000000..2a68977219--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/ScalableTarget.java@@ -0,0 +1,77 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;+import java.util.Collection;+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;++/**+ * A registered scalable target.+ *+ * <p>Identity is the triple (serviceNamespace, resourceId, scalableDimension); there is no+ * separate identifier. {@code scalableTargetArn} is the tagging identifier that the+ * Terraform provider reads from DescribeScalableTargets and then passes to+ * ListTagsForResource, so it must always be populated.</p>+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_ScalableTarget.html">ScalableTarget</a>+ */+@RegisterForReflection+public class ScalableTarget {++ private String serviceNamespace;+ private String resourceId;+ private String scalableDimension;+ private Integer minCapacity;+ private Integer maxCapacity;+ private String roleArn;+ private String scalableTargetArn;+ private double creationTime;+ private SuspendedState suspendedState = new SuspendedState();+ private Map<String, String> tags = new HashMap<>();++ public String getServiceNamespace() { return serviceNamespace; }+ public void setServiceNamespace(String v) { this.serviceNamespace = v; }++ public String getResourceId() { return resourceId; }+ public void setResourceId(String v) { this.resourceId = v; }++ public String getScalableDimension() { return scalableDimension; }+ public void setScalableDimension(String v) { this.scalableDimension = v; }++ public Integer getMinCapacity() { return minCapacity; }+ public void setMinCapacity(Integer v) { this.minCapacity = v; }++ public Integer getMaxCapacity() { return maxCapacity; }+ public void setMaxCapacity(Integer v) { this.maxCapacity = v; }++ public String getRoleArn() { return roleArn; }+ public void setRoleArn(String v) { this.roleArn = v; }++ public String getScalableTargetArn() { return scalableTargetArn; }+ public void setScalableTargetArn(String v) { this.scalableTargetArn = v; }++ public double getCreationTime() { return creationTime; }+ public void setCreationTime(double v) { this.creationTime = v; }++ public SuspendedState getSuspendedState() { return suspendedState; }+ public void setSuspendedState(SuspendedState v) { this.suspendedState = v == null ? new SuspendedState() : v; }++ /** Read-only view; mutate through {@link #putTags} and {@link #removeTags}. */+ public Map<String, String> getTags() { return Collections.unmodifiableMap(tags); }++ /** Copies defensively so that a caller passing an immutable map stays mutable here. */+ public void setTags(Map<String, String> v) { this.tags = v == null ? new HashMap<>() : new HashMap<>(v); }++ public void putTags(Map<String, String> additional) {+ if (additional != null) {+ tags.putAll(additional);+ }+ }++ public void removeTags(Collection<String> tagKeys) {+ if (tagKeys != null) {+ tagKeys.forEach(tags::remove);+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/ScalingPolicy.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/ScalingPolicy.javanew file mode 100644index 0000000000..8f2d5b51a5--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/ScalingPolicy.java@@ -0,0 +1,59 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;+import java.util.ArrayList;+import java.util.List;++/**+ * A scaling policy attached to a scalable target.+ *+ * <p>Note that {@code policyArn} uses the {@code autoscaling} service name rather than+ * {@code application-autoscaling} — the two ARN families differ, which AWS does not+ * document in one place.</p>+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_ScalingPolicy.html">ScalingPolicy</a>+ */+@RegisterForReflection+public class ScalingPolicy {++ private String policyArn;+ private String policyName;+ private String policyType;+ private String serviceNamespace;+ private String resourceId;+ private String scalableDimension;+ private double creationTime;+ private List<Alarm> alarms = new ArrayList<>();+ private TargetTrackingConfiguration targetTrackingConfiguration;+ private StepScalingConfiguration stepScalingConfiguration;++ public String getPolicyArn() { return policyArn; }+ public void setPolicyArn(String v) { this.policyArn = v; }++ public String getPolicyName() { return policyName; }+ public void setPolicyName(String v) { this.policyName = v; }++ public String getPolicyType() { return policyType; }+ public void setPolicyType(String v) { this.policyType = v; }++ public String getServiceNamespace() { return serviceNamespace; }+ public void setServiceNamespace(String v) { this.serviceNamespace = v; }++ public String getResourceId() { return resourceId; }+ public void setResourceId(String v) { this.resourceId = v; }++ public String getScalableDimension() { return scalableDimension; }+ public void setScalableDimension(String v) { this.scalableDimension = v; }++ public double getCreationTime() { return creationTime; }+ public void setCreationTime(double v) { this.creationTime = v; }++ public List<Alarm> getAlarms() { return alarms; }+ public void setAlarms(List<Alarm> v) { this.alarms = v == null ? new ArrayList<>() : new ArrayList<>(v); }++ public TargetTrackingConfiguration getTargetTrackingConfiguration() { return targetTrackingConfiguration; }+ public void setTargetTrackingConfiguration(TargetTrackingConfiguration v) { this.targetTrackingConfiguration = v; }++ public StepScalingConfiguration getStepScalingConfiguration() { return stepScalingConfiguration; }+ public void setStepScalingConfiguration(StepScalingConfiguration v) { this.stepScalingConfiguration = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/StepAdjustment.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/StepAdjustment.javanew file mode 100644index 0000000000..7e41dfdc67--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/StepAdjustment.java@@ -0,0 +1,28 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * One step of a step scaling policy.+ *+ * <p>The bounds are nullable: an omitted lower bound means negative infinity and an+ * omitted upper bound means positive infinity, so they must not be defaulted to zero.</p>+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_StepAdjustment.html">StepAdjustment</a>+ */+@RegisterForReflection+public class StepAdjustment {++ private Double metricIntervalLowerBound;+ private Double metricIntervalUpperBound;+ private Integer scalingAdjustment;++ public Double getMetricIntervalLowerBound() { return metricIntervalLowerBound; }+ public void setMetricIntervalLowerBound(Double v) { this.metricIntervalLowerBound = v; }++ public Double getMetricIntervalUpperBound() { return metricIntervalUpperBound; }+ public void setMetricIntervalUpperBound(Double v) { this.metricIntervalUpperBound = v; }++ public Integer getScalingAdjustment() { return scalingAdjustment; }+ public void setScalingAdjustment(Integer v) { this.scalingAdjustment = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/StepScalingConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/StepScalingConfiguration.javanew file mode 100644index 0000000000..ddf3a3884d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/StepScalingConfiguration.java@@ -0,0 +1,37 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;+import java.util.ArrayList;+import java.util.List;++/**+ * Step scaling configuration for a scaling policy.+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_StepScalingPolicyConfiguration.html">StepScalingPolicyConfiguration</a>+ */+@RegisterForReflection+public class StepScalingConfiguration {++ private String adjustmentType;+ private Integer cooldown;+ private String metricAggregationType;+ private Integer minAdjustmentMagnitude;+ private List<StepAdjustment> stepAdjustments = new ArrayList<>();++ public String getAdjustmentType() { return adjustmentType; }+ public void setAdjustmentType(String v) { this.adjustmentType = v; }++ public Integer getCooldown() { return cooldown; }+ public void setCooldown(Integer v) { this.cooldown = v; }++ public String getMetricAggregationType() { return metricAggregationType; }+ public void setMetricAggregationType(String v) { this.metricAggregationType = v; }++ public Integer getMinAdjustmentMagnitude() { return minAdjustmentMagnitude; }+ public void setMinAdjustmentMagnitude(Integer v) { this.minAdjustmentMagnitude = v; }++ public List<StepAdjustment> getStepAdjustments() { return stepAdjustments; }+ public void setStepAdjustments(List<StepAdjustment> v) {+ this.stepAdjustments = v == null ? new ArrayList<>() : new ArrayList<>(v);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/SuspendedState.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/SuspendedState.javanew file mode 100644index 0000000000..5f669d4ccf--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/SuspendedState.java@@ -0,0 +1,25 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * Suspension flags for a scalable target's automatic scaling activities.+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_SuspendedState.html">SuspendedState</a>+ */+@RegisterForReflection+public class SuspendedState {++ private boolean dynamicScalingInSuspended;+ private boolean dynamicScalingOutSuspended;+ private boolean scheduledScalingSuspended;++ public boolean isDynamicScalingInSuspended() { return dynamicScalingInSuspended; }+ public void setDynamicScalingInSuspended(boolean v) { this.dynamicScalingInSuspended = v; }++ public boolean isDynamicScalingOutSuspended() { return dynamicScalingOutSuspended; }+ public void setDynamicScalingOutSuspended(boolean v) { this.dynamicScalingOutSuspended = v; }++ public boolean isScheduledScalingSuspended() { return scheduledScalingSuspended; }+ public void setScheduledScalingSuspended(boolean v) { this.scheduledScalingSuspended = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/TargetTrackingConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/TargetTrackingConfiguration.javanew file mode 100644index 0000000000..755962eba3--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/model/TargetTrackingConfiguration.java@@ -0,0 +1,42 @@+package io.github.hectorvent.floci.services.applicationautoscaling.model;++import io.quarkus.runtime.annotations.RegisterForReflection;+import java.util.Map;++/**+ * Target tracking configuration for a scaling policy.+ *+ * <p>Every field here is echoed back by DescribeScalingPolicies. Optional numerics stay+ * nullable so that omitted values are not invented on read, which would surface as+ * Terraform drift.</p>+ *+ * @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_TargetTrackingScalingPolicyConfiguration.html">TargetTrackingScalingPolicyConfiguration</a>+ */+@RegisterForReflection+public class TargetTrackingConfiguration {++ private Double targetValue;+ private PredefinedMetricSpecification predefinedMetricSpecification;+ private Map<String, Object> customizedMetricSpecification;+ private Boolean disableScaleIn;+ private Integer scaleInCooldown;+ private Integer scaleOutCooldown;++ public Double getTargetValue() { return targetValue; }+ public void setTargetValue(Double v) { this.targetValue = v; }++ public PredefinedMetricSpecification getPredefinedMetricSpecification() { return predefinedMetricSpecification; }+ public void setPredefinedMetricSpecification(PredefinedMetricSpecification v) { this.predefinedMetricSpecification = v; }++ public Map<String, Object> getCustomizedMetricSpecification() { return customizedMetricSpecification; }+ public void setCustomizedMetricSpecification(Map<String, Object> v) { this.customizedMetricSpecification = v; }++ public Boolean getDisableScaleIn() { return disableScaleIn; }+ public void setDisableScaleIn(Boolean v) { this.disableScaleIn = v; }++ public Integer getScaleInCooldown() { return scaleInCooldown; }+ public void setScaleInCooldown(Integer v) { this.scaleInCooldown = v; }++ public Integer getScaleOutCooldown() { return scaleOutCooldown; }+ public void setScaleOutCooldown(Integer v) { this.scaleOutCooldown = v; }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex c21932c621..ae57efdc76 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -414,6 +414,8 @@ floci:enabled: trueautoscaling:enabled: true+ applicationautoscaling:+ enabled: trueelasticbeanstalk:enabled: truebackup:diff --git a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingIntegrationTest.javanew file mode 100644index 0000000000..5385ec4013--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingIntegrationTest.java@@ -0,0 +1,300 @@+package io.github.hectorvent.floci.services.applicationautoscaling;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestInstance;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.matchesPattern;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;+import static org.hamcrest.Matchers.startsWith;++/**+ * Wire-level coverage for the Application Auto Scaling API.+ *+ * <p>The resource identifiers mirror a real ECS service so that the round-trip of+ * {@code ResourceLabel} and the cooldown fields — the ones that surface as Terraform drift+ * when dropped — are exercised end to end.</p>+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+@TestInstance(TestInstance.Lifecycle.PER_CLASS)+class ApplicationAutoScalingIntegrationTest {++ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String TARGET_PREFIX = "AnyScaleFrontendService.";+ private static final String RESOURCE_ID = "service/aas-it-cluster/aas-it-service";+ private static final String DIMENSION = "ecs:service:DesiredCount";++ private static String scalableTargetArn;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ private static io.restassured.specification.RequestSpecification call(String action) {+ return given().header("X-Amz-Target", TARGET_PREFIX + action).contentType(CONTENT_TYPE);+ }++ @Test+ @Order(1)+ void registerScalableTargetReturnsScalableTargetArn() {+ scalableTargetArn = call("RegisterScalableTarget")+ .body("""+ {+ "ServiceNamespace": "ecs",+ "ResourceId": "%s",+ "ScalableDimension": "%s",+ "MinCapacity": 2,+ "MaxCapacity": 20,+ "Tags": { "Environment": "test" }+ }+ """.formatted(RESOURCE_ID, DIMENSION))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("ScalableTargetARN", matchesPattern(+ "^arn:aws:application-autoscaling:[a-z0-9-]+:\\d+:scalable-target/[a-zA-Z0-9-]+$"))+ .extract().path("ScalableTargetARN");+ }++ @Test+ @Order(2)+ void describeScalableTargetsReturnsTheArnThatDrivesTagging() {+ call("DescribeScalableTargets")+ .body("""+ { "ServiceNamespace": "ecs", "ResourceIds": ["%s"] }+ """.formatted(RESOURCE_ID))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("ScalableTargets", hasSize(1))+ .body("ScalableTargets[0].ResourceId", equalTo(RESOURCE_ID))+ .body("ScalableTargets[0].ScalableDimension", equalTo(DIMENSION))+ .body("ScalableTargets[0].MinCapacity", equalTo(2))+ .body("ScalableTargets[0].MaxCapacity", equalTo(20))+ .body("ScalableTargets[0].ScalableTargetARN", equalTo(scalableTargetArn))+ .body("ScalableTargets[0].RoleARN", containsString(+ "AWSServiceRoleForApplicationAutoScaling_ECSService"))+ .body("ScalableTargets[0].SuspendedState.DynamicScalingInSuspended", equalTo(false))+ .body("ScalableTargets[0].CreationTime", notNullValue());+ }++ @Test+ @Order(3)+ void registerIsAnUpsertThatPreservesUnsuppliedFields() {+ call("RegisterScalableTarget")+ .body("""+ {+ "ServiceNamespace": "ecs",+ "ResourceId": "%s",+ "ScalableDimension": "%s",+ "MaxCapacity": 40+ }+ """.formatted(RESOURCE_ID, DIMENSION))+ .when().post("/").then().statusCode(200)+ .body("ScalableTargetARN", equalTo(scalableTargetArn));++ call("DescribeScalableTargets")+ .body("""+ { "ServiceNamespace": "ecs", "ResourceIds": ["%s"] }+ """.formatted(RESOURCE_ID))+ .when().post("/").then().statusCode(200)+ .body("ScalableTargets[0].MaxCapacity", equalTo(40))+ .body("ScalableTargets[0].MinCapacity", equalTo(2));+ }++ @Test+ @Order(4)+ void listTagsForResourceResolvesByScalableTargetArn() {+ call("ListTagsForResource")+ .body("{ \"ResourceARN\": \"%s\" }".formatted(scalableTargetArn))+ .when().post("/").then().statusCode(200)+ .body("Tags.Environment", equalTo("test"));+ }++ @Test+ @Order(5)+ void tagAndUntagResource() {+ call("TagResource")+ .body("""+ { "ResourceARN": "%s", "Tags": { "Team": "platform" } }+ """.formatted(scalableTargetArn))+ .when().post("/").then().statusCode(200);++ call("ListTagsForResource")+ .body("{ \"ResourceARN\": \"%s\" }".formatted(scalableTargetArn))+ .when().post("/").then().statusCode(200)+ .body("Tags.Team", equalTo("platform"))+ .body("Tags.Environment", equalTo("test"));++ call("UntagResource")+ .body("""+ { "ResourceARN": "%s", "TagKeys": ["Environment"] }+ """.formatted(scalableTargetArn))+ .when().post("/").then().statusCode(200);++ call("ListTagsForResource")+ .body("{ \"ResourceARN\": \"%s\" }".formatted(scalableTargetArn))+ .when().post("/").then().statusCode(200)+ .body("Tags.Environment", nullValue())+ .body("Tags.Team", equalTo("platform"));+ }++ @Test+ @Order(6)+ void putScalingPolicyReturnsPolicyArnAndAlarms() {+ call("PutScalingPolicy")+ .body("""+ {+ "PolicyName": "aas-it-alb-policy",+ "PolicyType": "TargetTrackingScaling",+ "ServiceNamespace": "ecs",+ "ResourceId": "%s",+ "ScalableDimension": "%s",+ "TargetTrackingScalingPolicyConfiguration": {+ "TargetValue": 1000.0,+ "PredefinedMetricSpecification": {+ "PredefinedMetricType": "ALBRequestCountPerTarget",+ "ResourceLabel": "app/my-lb/abc123/targetgroup/my-tg/def456"+ },+ "ScaleInCooldown": 240,+ "ScaleOutCooldown": 60+ }+ }+ """.formatted(RESOURCE_ID, DIMENSION))+ .when().post("/").then().statusCode(200)+ // Policy ARNs use the "autoscaling" service name, not "application-autoscaling".+ .body("PolicyARN", startsWith("arn:aws:autoscaling:"))+ .body("PolicyARN", containsString(":resource/ecs/" + RESOURCE_ID + ":policyName/aas-it-alb-policy"))+ .body("Alarms", hasSize(2))+ .body("Alarms[0].AlarmName", startsWith("TargetTracking-" + RESOURCE_ID))+ .body("Alarms[0].AlarmARN", startsWith("arn:aws:cloudwatch:"));+ }++ @Test+ @Order(7)+ void describeScalingPoliciesRoundTripsEveryConfiguredField() {+ call("DescribeScalingPolicies")+ .body("""+ { "ServiceNamespace": "ecs", "ResourceId": "%s", "ScalableDimension": "%s" }+ """.formatted(RESOURCE_ID, DIMENSION))+ .when().post("/").then().statusCode(200)+ .body("ScalingPolicies", hasSize(1))+ .body("ScalingPolicies[0].PolicyName", equalTo("aas-it-alb-policy"))+ .body("ScalingPolicies[0].PolicyType", equalTo("TargetTrackingScaling"))+ .body("ScalingPolicies[0].TargetTrackingScalingPolicyConfiguration.TargetValue",+ equalTo(1000.0f))+ .body("ScalingPolicies[0].TargetTrackingScalingPolicyConfiguration"+ + ".PredefinedMetricSpecification.PredefinedMetricType",+ equalTo("ALBRequestCountPerTarget"))+ .body("ScalingPolicies[0].TargetTrackingScalingPolicyConfiguration"+ + ".PredefinedMetricSpecification.ResourceLabel",+ equalTo("app/my-lb/abc123/targetgroup/my-tg/def456"))+ .body("ScalingPolicies[0].TargetTrackingScalingPolicyConfiguration.ScaleInCooldown",+ equalTo(240))+ .body("ScalingPolicies[0].TargetTrackingScalingPolicyConfiguration.ScaleOutCooldown",+ equalTo(60))+ // Never configured, so it must be absent rather than defaulted.+ .body("ScalingPolicies[0].TargetTrackingScalingPolicyConfiguration.DisableScaleIn",+ nullValue());+ }++ @Test+ @Order(8)+ void putScalingPolicyOnUnregisteredTargetThrowsObjectNotFound() {+ call("PutScalingPolicy")+ .body("""+ {+ "PolicyName": "orphan",+ "PolicyType": "TargetTrackingScaling",+ "ServiceNamespace": "ecs",+ "ResourceId": "service/absent/absent",+ "ScalableDimension": "%s",+ "TargetTrackingScalingPolicyConfiguration": {+ "TargetValue": 50.0,+ "PredefinedMetricSpecification": {+ "PredefinedMetricType": "ECSServiceAverageCPUUtilization"+ }+ }+ }+ """.formatted(DIMENSION))+ .when().post("/").then().statusCode(400)+ .body("__type", equalTo("ObjectNotFoundException"));+ }++ @Test+ @Order(9)+ void invalidServiceNamespaceIsRejected() {+ call("DescribeScalableTargets")+ .body("{ \"ServiceNamespace\": \"bogus\" }")+ .when().post("/").then().statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(10)+ void tagsOnUnknownArnThrowResourceNotFound() {+ call("ListTagsForResource")+ .body("""+ { "ResourceARN": "arn:aws:application-autoscaling:us-east-1:000000000000:scalable-target/missing" }+ """)+ .when().post("/").then().statusCode(400)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ @Test+ @Order(11)+ void deregisterScalableTargetCascadesToItsPolicies() {+ call("DeregisterScalableTarget")+ .body("""+ { "ServiceNamespace": "ecs", "ResourceId": "%s", "ScalableDimension": "%s" }+ """.formatted(RESOURCE_ID, DIMENSION))+ .when().post("/").then().statusCode(200);++ call("DescribeScalableTargets")+ .body("""+ { "ServiceNamespace": "ecs", "ResourceIds": ["%s"] }+ """.formatted(RESOURCE_ID))+ .when().post("/").then().statusCode(200)+ .body("ScalableTargets", hasSize(0));++ call("DescribeScalingPolicies")+ .body("""+ { "ServiceNamespace": "ecs", "ResourceId": "%s", "ScalableDimension": "%s" }+ """.formatted(RESOURCE_ID, DIMENSION))+ .when().post("/").then().statusCode(200)+ .body("ScalingPolicies", hasSize(0));+ }++ @Test+ @Order(12)+ void deregisteringTwiceThrowsObjectNotFound() {+ call("DeregisterScalableTarget")+ .body("""+ { "ServiceNamespace": "ecs", "ResourceId": "%s", "ScalableDimension": "%s" }+ """.formatted(RESOURCE_ID, DIMENSION))+ .when().post("/").then().statusCode(400)+ .body("__type", equalTo("ObjectNotFoundException"));+ }++ @Test+ @Order(13)+ void unsupportedActionIsRejected() {+ call("PutScheduledAction")+ .body("{ \"ServiceNamespace\": \"ecs\" }")+ .when().post("/").then().statusCode(400);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.javanew file mode 100644index 0000000000..a21b4eb72a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java@@ -0,0 +1,303 @@+package io.github.hectorvent.floci.services.applicationautoscaling;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.applicationautoscaling.model.PredefinedMetricSpecification;+import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget;+import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;+import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;++class ApplicationAutoScalingServiceTest {++ private static final String REGION = "us-east-1";+ private static final String NAMESPACE = "ecs";+ private static final String RESOURCE_ID = "service/my-cluster/my-service";+ private static final String DIMENSION = "ecs:service:DesiredCount";++ private ApplicationAutoScalingService service;++ /** Alarm names currently registered in the stubbed CloudWatch. */+ private final Set<String> alarmsInCloudWatch = new LinkedHashSet<>();++ @BeforeEach+ void setUp() {+ RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");+ alarmsInCloudWatch.clear();++ CloudWatchMetricsService cloudWatch = mock(CloudWatchMetricsService.class);+ doAnswer(invocation -> {+ MetricAlarm alarm = invocation.getArgument(0);+ alarm.setAlarmArn("arn:aws:cloudwatch:" + REGION + ":000000000000:alarm:" + alarm.getAlarmName());+ alarmsInCloudWatch.add(alarm.getAlarmName());+ return null;+ }).when(cloudWatch).putMetricAlarm(any(MetricAlarm.class), anyString());+ doAnswer(invocation -> {+ alarmsInCloudWatch.removeAll(invocation.<List<String>>getArgument(0));+ return null;+ }).when(cloudWatch).deleteAlarms(any(), anyString());++ service = new ApplicationAutoScalingService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, cloudWatch);+ }++ private ScalableTarget register() {+ return service.registerScalableTarget(NAMESPACE, RESOURCE_ID, DIMENSION, 1, 10,+ null, null, Map.of("Environment", "dev"), REGION);+ }++ private TargetTrackingConfiguration targetTracking(double value, String metricType, String resourceLabel) {+ TargetTrackingConfiguration config = new TargetTrackingConfiguration();+ config.setTargetValue(value);+ PredefinedMetricSpecification spec = new PredefinedMetricSpecification();+ spec.setPredefinedMetricType(metricType);+ spec.setResourceLabel(resourceLabel);+ config.setPredefinedMetricSpecification(spec);+ return config;+ }++ @Test+ void registerCreatesTargetWithArnAndServiceLinkedRole() {+ ScalableTarget target = register();++ assertTrue(target.getScalableTargetArn()+ .matches("^arn:aws:application-autoscaling:us-east-1:000000000000:scalable-target/[a-zA-Z0-9-]+$"),+ "ARN must satisfy the AWS pattern, got: " + target.getScalableTargetArn());+ assertEquals("arn:aws:iam::000000000000:role/aws-service-role/"+ + "ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService",+ target.getRoleArn());+ assertEquals(1, target.getMinCapacity());+ assertEquals(10, target.getMaxCapacity());+ }++ @Test+ void registerRequiresCapacityOnlyForNewTargets() {+ assertThrows(AwsException.class, () -> service.registerScalableTarget(+ NAMESPACE, RESOURCE_ID, DIMENSION, null, null, null, null, null, REGION));+ }++ @Test+ void registerIsUpsertOnTheTripleAndLeavesUnsuppliedFieldsUnchanged() {+ String originalArn = register().getScalableTargetArn();++ ScalableTarget updated = service.registerScalableTarget(+ NAMESPACE, RESOURCE_ID, DIMENSION, null, 40, null, null, null, REGION);++ assertEquals(originalArn, updated.getScalableTargetArn(), "upsert must not mint a new ARN");+ assertEquals(40, updated.getMaxCapacity());+ assertEquals(1, updated.getMinCapacity(), "unsupplied min capacity must be preserved");+ assertEquals(1, service.describeScalableTargets(NAMESPACE, null, null, REGION).size());+ }++ @Test+ void describeFiltersByResourceIdAndDimension() {+ register();+ service.registerScalableTarget(NAMESPACE, "service/other/other", DIMENSION, 1, 5,+ null, null, null, REGION);++ assertEquals(2, service.describeScalableTargets(NAMESPACE, null, null, REGION).size());+ assertEquals(1, service.describeScalableTargets(NAMESPACE, List.of(RESOURCE_ID), DIMENSION, REGION).size());+ assertEquals(0, service.describeScalableTargets("kafka", null, null, REGION).size());+ }++ @Test+ void describeRejectsDimensionWithoutResourceId() {+ register();+ assertThrows(AwsException.class,+ () -> service.describeScalableTargets(NAMESPACE, null, DIMENSION, REGION));+ }++ @Test+ void invalidNamespaceAndDimensionAreRejected() {+ AwsException namespace = assertThrows(AwsException.class, () -> service.registerScalableTarget(+ "bogus", RESOURCE_ID, DIMENSION, 1, 2, null, null, null, REGION));+ assertEquals("ValidationException", namespace.getErrorCode());++ AwsException dimension = assertThrows(AwsException.class, () -> service.registerScalableTarget(+ NAMESPACE, RESOURCE_ID, "ecs:service:Bogus", 1, 2, null, null, null, REGION));+ assertEquals("ValidationException", dimension.getErrorCode());+ }++ @Test+ void putScalingPolicyRequiresRegisteredTarget() {+ AwsException e = assertThrows(AwsException.class, () -> service.putScalingPolicy(+ "p", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(50.0, "ECSServiceAverageCPUUtilization", null), null, REGION));+ assertEquals("ObjectNotFoundException", e.getErrorCode());+ }++ @Test+ void policyArnUsesAutoscalingServiceNameNotApplicationAutoscaling() {+ register();+ ScalingPolicy policy = service.putScalingPolicy("cpu", "TargetTrackingScaling",+ NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION);++ assertTrue(policy.getPolicyArn().startsWith("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:"),+ "policy ARN must use the autoscaling service name, got: " + policy.getPolicyArn());+ assertTrue(policy.getPolicyArn().contains(":resource/ecs/" + RESOURCE_ID + ":policyName/cpu"),+ "policy ARN must embed the resource path and policy name, got: " + policy.getPolicyArn());+ }++ @Test+ void targetTrackingConfigurationRoundTripsEveryField() {+ register();+ service.putScalingPolicy("alb", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,+ withCooldowns(targetTracking(1000.0, "ALBRequestCountPerTarget", "app/lb/abc/targetgroup/tg/def")),+ null, REGION);++ TargetTrackingConfiguration stored = service+ .describeScalingPolicies(NAMESPACE, RESOURCE_ID, DIMENSION, null, REGION)+ .get(0)+ .getTargetTrackingConfiguration();++ assertEquals(1000.0, stored.getTargetValue());+ assertEquals("ALBRequestCountPerTarget", stored.getPredefinedMetricSpecification().getPredefinedMetricType());+ assertEquals("app/lb/abc/targetgroup/tg/def",+ stored.getPredefinedMetricSpecification().getResourceLabel());+ assertEquals(240, stored.getScaleInCooldown());+ assertEquals(60, stored.getScaleOutCooldown());+ }++ @Test+ void unsuppliedOptionalsStayNullSoTerraformSeesNoInventedValues() {+ register();+ service.putScalingPolicy("cpu", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION);++ TargetTrackingConfiguration stored = service+ .describeScalingPolicies(NAMESPACE, RESOURCE_ID, DIMENSION, null, REGION)+ .get(0)+ .getTargetTrackingConfiguration();++ assertNull(stored.getScaleInCooldown());+ assertNull(stored.getScaleOutCooldown());+ assertNull(stored.getDisableScaleIn());+ assertNull(stored.getPredefinedMetricSpecification().getResourceLabel());+ }++ @Test+ void targetTrackingPolicyCreatesRealCloudWatchAlarms() {+ register();+ ScalingPolicy policy = service.putScalingPolicy("cpu", "TargetTrackingScaling",+ NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION);++ assertEquals(2, policy.getAlarms().size());+ assertEquals(2, alarmsInCloudWatch.size(),+ "alarms must be registered in CloudWatch, not merely synthesized");+ assertTrue(policy.getAlarms().get(0).getAlarmName().startsWith("TargetTracking-" + RESOURCE_ID));+ assertNotNull(policy.getAlarms().get(0).getAlarmArn());+ }++ @Test+ void deregisterCascadesToPoliciesAndAlarms() {+ register();+ service.putScalingPolicy("cpu", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION);++ service.deregisterScalableTarget(NAMESPACE, RESOURCE_ID, DIMENSION, REGION);++ assertEquals(0, service.describeScalableTargets(NAMESPACE, null, null, REGION).size());+ assertEquals(0, service.describeScalingPolicies(NAMESPACE, null, null, null, REGION).size(),+ "policies must be deleted with their scalable target");+ assertEquals(0, alarmsInCloudWatch.size(),+ "alarms owned by deleted policies must be removed");+ }++ @Test+ void deregisterUnknownTargetThrowsObjectNotFound() {+ AwsException e = assertThrows(AwsException.class,+ () -> service.deregisterScalableTarget(NAMESPACE, RESOURCE_ID, DIMENSION, REGION));+ assertEquals("ObjectNotFoundException", e.getErrorCode());+ }++ @Test+ void deleteScalingPolicyRemovesItsAlarms() {+ register();+ service.putScalingPolicy("cpu", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION);++ service.deleteScalingPolicy("cpu", NAMESPACE, RESOURCE_ID, DIMENSION, REGION);++ assertEquals(0, service.describeScalingPolicies(NAMESPACE, null, null, null, REGION).size());+ assertEquals(0, alarmsInCloudWatch.size());+ }++ @Test+ void replacingATargetTrackingPolicyDoesNotLeakAlarms() {+ register();+ service.putScalingPolicy("cpu", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION);+ service.putScalingPolicy("cpu", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,+ targetTracking(80.0, "ECSServiceAverageCPUUtilization", null), null, REGION);++ assertEquals(1, service.describeScalingPolicies(NAMESPACE, null, null, null, REGION).size());+ assertEquals(2, alarmsInCloudWatch.size(),+ "the superseded policy's alarms must be replaced, not accumulated");+ }++ @Test+ void tagLifecycleIsDrivenByTheScalableTargetArn() {+ ScalableTarget target = register();+ String arn = target.getScalableTargetArn();++ assertEquals(Map.of("Environment", "dev"), service.listTagsForResource(arn, REGION));++ service.tagResource(arn, Map.of("Team", "platform"), REGION);+ assertEquals(2, service.listTagsForResource(arn, REGION).size());++ service.untagResource(arn, List.of("Environment"), REGION);+ assertEquals(Map.of("Team", "platform"), service.listTagsForResource(arn, REGION));+ }++ @Test+ void listedTagsCannotBeMutatedThroughTheReturnedMap() {+ String arn = register().getScalableTargetArn();++ Map<String, String> listed = service.listTagsForResource(arn, REGION);++ assertThrows(UnsupportedOperationException.class, () -> listed.put("Sneaky", "yes"),+ "tags must not be mutable through the map handed back to callers");+ assertEquals(Map.of("Environment", "dev"), service.listTagsForResource(arn, REGION));+ }++ @Test+ void tagsOnUnknownArnThrowResourceNotFound() {+ AwsException e = assertThrows(AwsException.class, () -> service.listTagsForResource(+ "arn:aws:application-autoscaling:us-east-1:000000000000:scalable-target/missing", REGION));+ assertEquals("ResourceNotFoundException", e.getErrorCode());+ }++ @Test+ void targetsAreIsolatedByRegion() {+ register();+ assertEquals(1, service.describeScalableTargets(NAMESPACE, null, null, REGION).size());+ assertEquals(0, service.describeScalableTargets(NAMESPACE, null, null, "eu-west-1").size());+ }++ private TargetTrackingConfiguration withCooldowns(TargetTrackingConfiguration config) {+ config.setScaleInCooldown(240);+ config.setScaleOutCooldown(60);+ return config;+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 8c28b0ca42..ca5359a04d 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -247,6 +247,8 @@ floci:enabled: trueautoscaling:enabled: true+ applicationautoscaling:+ enabled: trueelasticbeanstalk:enabled: truetransfer:diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex b7add862dc..7ff1db5f34 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -14,6 +14,10 @@ services:doc: docs/services/acm.mdsources:- { path: src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java, mode: switch }+ - service: applicationautoscaling+ doc: docs/services/applicationautoscaling.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.java, mode: switch }- service: athenadoc: docs/services/athena.mdsources: