feat(cloudformation): support four AWS::AppConfig resource types (#6791)

This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-29 12:59:23 -04:00
1 parent 1a871392b7
commit fee688bd05
17 files changed
+2398 -3

No files matched your search

@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.appconfig;
import io.github.hectorvent.floci.services.appconfig.model.Application;
import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile;
import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy;
import io.github.hectorvent.floci.services.appconfig.model.Environment;
import io.github.hectorvent.floci.services.appconfig.model.Monitor;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* The update methods CloudFormation uses write a new copy of the entity rather than change the
* stored one field by field. The in-memory stores hand out the stored instance itself, so a caller
* that read an entity before the update, such as a ListDeployments building a summary from a
* strategy, must keep seeing all of its prior values rather than a mix of old and new.
*/
class AppConfigServiceUpdateIsolationTest {
private static final String ALARM = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors";
private final AppConfigService service = new AppConfigService(new InMemoryStorageFactory("000000000000"), null);
@Test
void aStrategyReadBeforeAnUpdateKeepsItsPriorSettings() {
DeploymentStrategy created = service.createDeploymentStrategy(Map.of("Name", "gradual",
"DeploymentDurationInMinutes", 10, "FinalBakeTimeInMinutes", 5, "GrowthFactor", 25,
"GrowthType", "EXPONENTIAL", "ReplicateTo", "NONE"));
DeploymentStrategy before = service.getDeploymentStrategy(created.getId());
service.updateDeploymentStrategy(created.getId(), "faster", 1, 0, 100f, "LINEAR");
assertEquals(10, before.getDeploymentDurationInMinutes());
assertEquals(5, before.getFinalBakeTimeInMinutes());
assertEquals(25f, before.getGrowthFactor());
assertEquals("EXPONENTIAL", before.getGrowthType());
assertNull(before.getDescription());
DeploymentStrategy after = service.getDeploymentStrategy(created.getId());
assertEquals(1, after.getDeploymentDurationInMinutes());
assertEquals(100f, after.getGrowthFactor());
assertEquals("faster", after.getDescription());
assertEquals("gradual", after.getName());
assertEquals("NONE", after.getReplicateTo());
}
@Test
void anApplicationReadBeforeAnUpdateKeepsItsPriorNameAndTags() {
Application created = service.createApplication(Map.of("Name", "orders", "Description", "First"));
service.tagApplication(created.getId(), Map.of("team", "payments"));
Application before = service.getApplication(created.getId());
service.updateApplication(created.getId(), "orders-v2", null);
assertEquals("orders", before.getName());
assertEquals("First", before.getDescription());
Application after = service.getApplication(created.getId());
assertEquals("orders-v2", after.getName());
assertNull(after.getDescription());
assertEquals(Map.of("team", "payments"), after.getTags(), "an update keeps the application's tags");
}
@Test
void anEnvironmentReadBeforeAnUpdateKeepsItsPriorMonitors() {
String appId = service.createApplication(Map.of("Name", "orders")).getId();
Environment created = service.createEnvironment(appId, Map.of("Name", "beta",
"Monitors", List.of(Map.of("AlarmArn", ALARM))));
Environment before = service.getEnvironment(appId, created.getId());
service.updateEnvironment(appId, created.getId(), "gamma", "Second", null);
assertEquals("beta", before.getName());
assertEquals(List.of(new Monitor(ALARM, null)), before.getMonitors());
Environment after = service.getEnvironment(appId, created.getId());
assertEquals("gamma", after.getName());
assertNull(after.getMonitors());
assertEquals("READY", after.getState(), "an update keeps the environment's state");
}
@Test
void aProfileReadBeforeAnUpdateKeepsItsPriorName() {
String appId = service.createApplication(Map.of("Name", "orders")).getId();
ConfigurationProfile created = service.createConfigurationProfile(appId,
Map.of("Name", "settings", "LocationUri", "hosted", "Type", "AWS.Freeform"));
ConfigurationProfile before = service.getConfigurationProfile(appId, created.getId());
service.updateConfigurationProfile(appId, created.getId(), "renamed", "Now described");
assertEquals("settings", before.getName());
assertNull(before.getDescription());
ConfigurationProfile after = service.getConfigurationProfile(appId, created.getId());
assertEquals("renamed", after.getName());
assertEquals("hosted", after.getLocationUri());
assertEquals("AWS.Freeform", after.getType());
}
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.appconfig;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.storage.WriteProfile;
import io.github.hectorvent.floci.services.appconfig.model.Application;
import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile;
import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy;
import io.github.hectorvent.floci.services.appconfig.model.Environment;
import io.github.hectorvent.floci.testing.ParkingStore;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The update methods CloudFormation uses read an entity, change it and write it back. A delete the
* AppConfig API runs on another thread in between must wait for the write and then remove the
* entity, not finish first and have the update store it again. Each case parks the update inside
* its write to the store and must see the delete waiting on the service.
*/
class AppConfigServiceUpdateRaceTest {
private static final String ACCOUNT = "000000000000";
private static final String APPLICATIONS = "appconfig-applications.json";
private static final String ENVIRONMENTS = "appconfig-environments.json";
private static final String PROFILES = "appconfig-profiles.json";
private static final String STRATEGIES = "appconfig-strategies.json";
@Test
void anApplicationDeletedDuringItsUpdateStaysDeleted() throws Exception {
ParkingStore<Application> store = new ParkingStore<>();
AppConfigService service = serviceWithStore(APPLICATIONS, store);
Application app = service.createApplication(Map.of("Name", "orders"));
deleteWaitsForTheWrite(store,
() -> service.updateApplication(app.getId(), "orders-v2", null),
() -> service.deleteApplication(app.getId()));
assertTrue(service.findApplication(app.getId()).isEmpty(), "the entity outlived its delete");
}
@Test
void aStrategyDeletedDuringItsUpdateStaysDeleted() throws Exception {
ParkingStore<DeploymentStrategy> store = new ParkingStore<>();
AppConfigService service = serviceWithStore(STRATEGIES, store);
DeploymentStrategy strategy = service.createDeploymentStrategy(Map.of("Name", "gradual",
"DeploymentDurationInMinutes", 0, "GrowthFactor", 100, "ReplicateTo", "NONE"));
deleteWaitsForTheWrite(store,
() -> service.updateDeploymentStrategy(strategy.getId(), "slower", 1, 0, 50f, "LINEAR"),
() -> service.deleteDeploymentStrategy(strategy.getId()));
assertTrue(service.listDeploymentStrategies().stream()
.noneMatch(listed -> listed.getId().equals(strategy.getId())), "the strategy outlived its delete");
}
@Test
void aProfileDeletedDuringItsUpdateStaysDeleted() throws Exception {
ParkingStore<ConfigurationProfile> store = new ParkingStore<>();
AppConfigService service = serviceWithStore(PROFILES, store);
Application app = service.createApplication(Map.of("Name", "orders"));
ConfigurationProfile profile = service.createConfigurationProfile(app.getId(),
Map.of("Name", "settings", "LocationUri", "hosted"));
deleteWaitsForTheWrite(store,
() -> service.updateConfigurationProfile(app.getId(), profile.getId(), "renamed", null),
() -> service.deleteConfigurationProfile(app.getId(), profile.getId()));
assertTrue(service.findConfigurationProfile(profile.getId()).isEmpty(), "the entity outlived its delete");
}
@Test
void anEnvironmentDeletedDuringItsUpdateStaysDeleted() throws Exception {
ParkingStore<Environment> store = new ParkingStore<>();
AppConfigService service = serviceWithStore(ENVIRONMENTS, store);
Application app = service.createApplication(Map.of("Name", "orders"));
Environment env = service.createEnvironment(app.getId(), Map.of("Name", "beta"));
deleteWaitsForTheWrite(store,
() -> service.updateEnvironment(app.getId(), env.getId(), "gamma", null, List.of()),
() -> service.deleteEnvironment(app.getId(), env.getId()));
assertTrue(service.findEnvironment(env.getId()).isEmpty(), "the entity outlived its delete");
}
/**
* Parks {@code write} in its next write to {@code store}, starts {@code delete}, and requires
* the delete to be unfinished and blocked on the service's monitor until the write is released;
* then both finish.
*/
private static void deleteWaitsForTheWrite(ParkingStore<?> store, Runnable write, Runnable delete)
throws Exception {
store.parkNextWrite();
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> writing = pool.submit(write);
assertTrue(store.awaitParked(), "the write must reach the store");
AtomicReference<Thread> deleteThread = new AtomicReference<>();
Future<?> deleting = pool.submit(() -> {
deleteThread.set(Thread.currentThread());
delete.run();
});
awaitBlockedOrDone(deleteThread, deleting);
assertFalse(deleting.isDone(), "the delete ran while a write of the same entity was mid-flight");
assertEquals(Thread.State.BLOCKED, deleteThread.get().getState(),
"the delete waits on the service's monitor");
store.release();
writing.get(2, TimeUnit.SECONDS);
deleting.get(2, TimeUnit.SECONDS);
} catch (ExecutionException e) {
throw new AssertionError(e.getCause());
} finally {
store.release();
pool.shutdownNow();
}
}
/** An AppConfig service whose {@code fileName} store is {@code store} and every other store in memory. */
private static AppConfigService serviceWithStore(String fileName, StorageBackend<String, ?> store) {
return new AppConfigService(new StorageFactory(null, null) {
@Override
@SuppressWarnings("unchecked")
public <V> AccountAwareStorageBackend<V> create(String serviceName, String file,
TypeReference<Map<String, V>> typeReference, WriteProfile profile) {
return file.equals(fileName)
? new AccountAwareStorageBackend<>((StorageBackend<String, V>) (Object) store, null, ACCOUNT)
: AccountAwareStorageBackend.inMemory(ACCOUNT);
}
}, null);
}
}
@@ -94,6 +94,19 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Comment"));
}
@Test
void isCreateOnly_appConfigReplacesOnlyOnItsSchemaProperties() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Application", "Name"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Environment", "ApplicationId"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Environment", "Name"));
assertEquals(Set.of("ApplicationId", "LocationUri", "Type"),
CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::AppConfig::ConfigurationProfile"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::ConfigurationProfile", "Name"));
assertEquals(Set.of("Name", "ReplicateTo"),
CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::AppConfig::DeploymentStrategy"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::DeploymentStrategy", "GrowthFactor"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.appconfig.AppConfigService;
import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingService;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
@@ -23,6 +24,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2DomainCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppConfigCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApplicationAutoScalingCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner;
@@ -205,6 +207,7 @@ final class CfnProvisionerFixture {
private DynamoDbService dynamoDbService;
private LambdaService lambdaService;
private AppSyncService appSyncService;
private AppConfigService appConfigService;
private IamService iamService;
private SsmService ssmService;
private KmsService kmsService;
@@ -417,6 +420,9 @@ final class CfnProvisionerFixture {
if (appSyncService != null) {
discovered.add(new AppSyncCfnProvisioner(appSyncService));
}
if (appConfigService != null) {
discovered.add(new AppConfigCfnProvisioner(appConfigService));
}
if (lambdaService != null) {
discovered.add(new LambdaAddressingCfnProvisioner(lambdaService));
discovered.add(new LambdaEventInvokeConfigCfnProvisioner(lambdaService));
@@ -564,6 +570,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder appConfig(AppConfigService v) {
this.appConfigService = v;
return this;
}
public Builder iam(IamService v) {
this.iamService = v;
return this;
@@ -0,0 +1,343 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@code AWS::AppConfig::Application}, {@code Environment}, {@code ConfigurationProfile} and
* {@code DeploymentStrategy} through real stack operations, read back through the AppConfig API.
* {@code Ref} and the ID attribute of each are the AppConfig ID; an update changes mutable
* properties in place and replaces a profile whose {@code LocationUri} changes; a failed update puts
* the in-place changes back and deletes the replacement; and the stack delete removes everything,
* hosted configuration versions and deployments included. A failing operation ends in a Secrets
* Manager secret that cannot be created.
*/
@QuarkusTest
class CloudFormationAppConfigIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ALARM = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors";
private static final List<String> RESOURCES = List.of("App", "Env", "Profile", "Strategy");
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aStackCreatesTheFourTypesAndItsDeleteRemovesThemWithTheirVersionsAndDeployments() throws Exception {
String stack = unique("cfn-appconfig-create");
Map<String, Object> resources = first();
resources.put("Untyped", Map.of("Type", "AWS::AppConfig::ConfigurationProfile", "Properties",
Map.of("ApplicationId", ref("App"), "Name", "untyped", "LocationUri", "hosted")));
deploy("CreateStack", stack, template(resources, false));
assertStatus(stack, "CREATE_COMPLETE");
Map<String, String> outputs = outputs(stack);
Map<String, String> physicalIds = physicalIds(stack);
for (String resource : RESOURCES) {
assertEquals(outputs.get(resource + "Ref"), outputs.get(resource + "Id"), resource);
assertEquals(physicalIds.get(resource), outputs.get(resource + "Ref"), resource);
}
String app = outputs.get("AppRef");
String env = outputs.get("EnvRef");
String profile = outputs.get("ProfileRef");
String strategy = outputs.get("StrategyRef");
String envPath = "/applications/" + app + "/environments/" + env;
String profilePath = "/applications/" + app + "/configurationprofiles/" + profile;
appconfig().get("/applications/" + app).then().statusCode(200)
.body("Name", equalTo("orders"), "Description", equalTo("Order service"));
assertEquals(Map.of("team", "payments", "tier", "gold"), applicationTags(app));
appconfig().get(envPath).then().statusCode(200)
.body("Name", equalTo("beta"), "Monitors[0].AlarmArn", equalTo(ALARM))
.body("Monitors[0]", not(hasKey("AlarmRoleArn")));
appconfig().get(profilePath).then().statusCode(200)
.body("Name", equalTo("settings"), "LocationUri", equalTo("hosted"), "Type", equalTo("AWS.Freeform"));
appconfig().get("/applications/" + app + "/configurationprofiles/" + physicalIds.get("Untyped"))
.then().statusCode(200).body("Type", nullValue());
appconfig().get("/deploymentstrategies/" + strategy).then().statusCode(200)
.body("Name", equalTo("gradual"), "DeploymentDurationInMinutes", equalTo(0),
"FinalBakeTimeInMinutes", equalTo(0), "GrowthFactor", equalTo(100f),
"GrowthType", equalTo("LINEAR"), "ReplicateTo", equalTo("NONE"));
// The stack's resources work together: a hosted version deploys with the stack's strategy.
appconfig().body("{\"enabled\":true}").post(profilePath + "/hostedconfigurationversions")
.then().statusCode(201).header("Version-Number", equalTo("1"));
int deployment = appconfig().body(Map.of("ConfigurationProfileId", profile, "ConfigurationVersion", "1",
"DeploymentStrategyId", strategy))
.post(envPath + "/deployments").then().statusCode(201)
.body("ConfigurationName", equalTo("settings"), "ConfigurationLocationUri", equalTo("hosted"))
.extract().path("DeploymentNumber");
deleteStack(stack);
appconfig().get(envPath + "/deployments/" + deployment).then().statusCode(404);
appconfig().get(envPath).then().statusCode(404);
appconfig().get(profilePath + "/hostedconfigurationversions/1").then().statusCode(404);
appconfig().get(profilePath).then().statusCode(404);
appconfig().get("/deploymentstrategies/" + strategy).then().statusCode(404);
appconfig().get("/applications/" + app).then().statusCode(404);
}
@Test
void anUpdateChangesMutablePropertiesInPlaceAndReplacesAProfileWhoseLocationChanges() throws Exception {
String stack = unique("cfn-appconfig-update");
deploy("CreateStack", stack, template(first(), false));
assertStatus(stack, "CREATE_COMPLETE");
Map<String, String> before = outputs(stack);
deploy("UpdateStack", stack, template(second(), false));
assertStatus(stack, "UPDATE_COMPLETE");
Map<String, String> after = outputs(stack);
String app = after.get("AppRef");
for (String kept : List.of("App", "Env", "Strategy")) {
assertEquals(before.get(kept + "Ref"), after.get(kept + "Ref"), kept + " is changed in place");
}
String oldProfile = before.get("ProfileRef");
String newProfile = after.get("ProfileRef");
assertNotEquals(oldProfile, newProfile, "a LocationUri change replaces the profile");
assertEquals(newProfile, after.get("ProfileId"));
appconfig().get("/applications/" + app).then().statusCode(200)
.body("Name", equalTo("orders-v2"), "Description", nullValue());
assertEquals(Map.of("team", "billing", "owner", "ops"), applicationTags(app));
appconfig().get("/applications/" + app + "/environments/" + after.get("EnvRef")).then().statusCode(200)
.body("Name", equalTo("gamma"), "Description", equalTo("Second stage"))
.body("$", not(hasKey("Monitors")));
appconfig().get("/applications/" + app + "/configurationprofiles/" + newProfile).then().statusCode(200)
.body("Name", equalTo("settings"), "LocationUri", equalTo("ssm-parameter://orders-settings"));
appconfig().get("/applications/" + app + "/configurationprofiles/" + oldProfile).then().statusCode(404);
appconfig().get("/deploymentstrategies/" + after.get("StrategyRef")).then().statusCode(200)
.body("Description", equalTo("Ten minutes"), "DeploymentDurationInMinutes", equalTo(10),
"GrowthFactor", equalTo(20f), "GrowthType", equalTo("EXPONENTIAL"));
assertTrue(hasEvent(stack, "Profile", oldProfile, "DELETE_COMPLETE"),
"the update's cleanup reports the displaced profile deleted");
deleteStack(stack);
appconfig().get("/applications/" + app).then().statusCode(404);
}
@Test
void aFailedUpdatePutsTheInPlaceChangesBackAndDeletesTheReplacement() throws Exception {
String stack = unique("cfn-appconfig-rollback");
deploy("CreateStack", stack, template(first(), false));
assertStatus(stack, "CREATE_COMPLETE");
Map<String, String> before = outputs(stack);
String app = before.get("AppRef");
deploy("UpdateStack", stack, template(second(), true));
assertStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(before, outputs(stack));
appconfig().get("/applications/" + app).then().statusCode(200)
.body("Name", equalTo("orders"), "Description", equalTo("Order service"));
assertEquals(Map.of("team", "payments", "tier", "gold"), applicationTags(app));
appconfig().get("/applications/" + app + "/environments/" + before.get("EnvRef")).then().statusCode(200)
.body("Name", equalTo("beta"), "Monitors[0].AlarmArn", equalTo(ALARM));
List<String> profiles = appconfig().get("/applications/" + app + "/configurationprofiles")
.then().statusCode(200).extract().jsonPath().getList("Items.Id", String.class);
assertEquals(List.of(before.get("ProfileRef")), profiles, "the replacement profile is deleted");
appconfig().get("/deploymentstrategies/" + before.get("StrategyRef")).then().statusCode(200)
.body("Description", equalTo("Immediate"), "DeploymentDurationInMinutes", equalTo(0),
"GrowthFactor", equalTo(100f), "GrowthType", equalTo("LINEAR"));
deleteStack(stack);
appconfig().get("/applications/" + app).then().statusCode(404);
}
@Test
void aChangeSetReportsReplacementForCreateOnlyChangesOnly() throws Exception {
String stack = unique("cfn-appconfig-change-set");
deploy("CreateStack", stack, template(first(), false));
assertStatus(stack, "CREATE_COMPLETE");
Map<String, Object> renamed = first();
properties(renamed, "App").put("Name", "orders-v2");
properties(renamed, "Env").put("Name", "gamma");
properties(renamed, "Profile").put("Name", "renamed");
properties(renamed, "Strategy").put("GrowthFactor", 50);
assertEquals(Map.of("App", "False", "Env", "False", "Profile", "False", "Strategy", "False"),
replacements(stack, "renamed", template(renamed, false)));
Map<String, Object> moved = first();
properties(moved, "Profile").put("LocationUri", "ssm-parameter://orders-settings");
properties(moved, "Strategy").put("Name", "immediate");
assertEquals(Map.of("Profile", "True", "Strategy", "True"),
replacements(stack, "moved", template(moved, false)));
deleteStack(stack);
}
/** The first version of the four resources. */
private static Map<String, Object> first() {
Map<String, Object> resources = new LinkedHashMap<>();
resources.put("App", resource("Application", props("Name", "orders", "Description", "Order service",
"Tags", tags("team", "payments", "tier", "gold"))));
resources.put("Env", resource("Environment", props("ApplicationId", ref("App"), "Name", "beta",
"Monitors", List.of(Map.of("AlarmArn", ALARM)))));
resources.put("Profile", resource("ConfigurationProfile", props("ApplicationId", ref("App"),
"Name", "settings", "LocationUri", "hosted", "Type", "AWS.Freeform")));
resources.put("Strategy", resource("DeploymentStrategy", props("Name", "gradual", "ReplicateTo", "NONE",
"DeploymentDurationInMinutes", 0, "FinalBakeTimeInMinutes", 0, "GrowthFactor", 100,
"Description", "Immediate")));
return resources;
}
/**
* The second version: the application renamed, its description dropped and its tags changed,
* the environment renamed with its monitors dropped, the profile moved to another location, and
* the strategy slowed down.
*/
private static Map<String, Object> second() {
Map<String, Object> resources = new LinkedHashMap<>();
resources.put("App", resource("Application", props("Name", "orders-v2",
"Tags", tags("team", "billing", "owner", "ops"))));
resources.put("Env", resource("Environment", props("ApplicationId", ref("App"), "Name", "gamma",
"Description", "Second stage")));
resources.put("Profile", resource("ConfigurationProfile", props("ApplicationId", ref("App"),
"Name", "settings", "LocationUri", "ssm-parameter://orders-settings", "Type", "AWS.Freeform")));
resources.put("Strategy", resource("DeploymentStrategy", props("Name", "gradual", "ReplicateTo", "NONE",
"DeploymentDurationInMinutes", 10, "GrowthFactor", 20, "GrowthType", "EXPONENTIAL",
"Description", "Ten minutes")));
return resources;
}
private static String template(Map<String, Object> resources, boolean failAfter) throws JsonProcessingException {
Map<String, Object> all = new LinkedHashMap<>(resources);
if (failAfter) {
all.put("Failure", Map.of("Type", "AWS::SecretsManager::Secret", "DependsOn", RESOURCES,
"Properties", Map.of("SecretString", "explicit",
"GenerateSecretString", Map.of("PasswordLength", 32))));
}
Map<String, Object> outputs = new LinkedHashMap<>();
Map<String, String> idAttributes = Map.of("App", "ApplicationId", "Env", "EnvironmentId",
"Profile", "ConfigurationProfileId", "Strategy", "Id");
for (String resource : RESOURCES) {
outputs.put(resource + "Ref", Map.of("Value", ref(resource)));
outputs.put(resource + "Id", Map.of("Value",
Map.of("Fn::GetAtt", List.of(resource, idAttributes.get(resource)))));
}
return MAPPER.writeValueAsString(Map.of("Resources", all, "Outputs", outputs));
}
private static Map<String, Object> resource(String type, Map<String, Object> properties) {
Map<String, Object> resource = new LinkedHashMap<>();
resource.put("Type", "AWS::AppConfig::" + type);
resource.put("Properties", properties);
return resource;
}
@SuppressWarnings("unchecked")
private static Map<String, Object> properties(Map<String, Object> resources, String logicalId) {
return (Map<String, Object>) ((Map<String, Object>) resources.get(logicalId)).get("Properties");
}
/** Alternating property names and values, in order, in a map a test can change. */
private static Map<String, Object> props(Object... namesAndValues) {
Map<String, Object> properties = new LinkedHashMap<>();
for (int i = 0; i < namesAndValues.length; i += 2) {
properties.put((String) namesAndValues[i], namesAndValues[i + 1]);
}
return properties;
}
private static List<Map<String, String>> tags(String... keysAndValues) {
List<Map<String, String>> tags = new ArrayList<>();
for (int i = 0; i < keysAndValues.length; i += 2) {
tags.add(Map.of("Key", keysAndValues[i], "Value", keysAndValues[i + 1]));
}
return tags;
}
private static Map<String, String> ref(String logicalId) {
return Map.of("Ref", logicalId);
}
private static String unique(String prefix) {
return prefix + "-" + Long.toString(System.nanoTime(), 36);
}
private static void deploy(String action, String stack, String template) {
cfn(action, stack).formParam("TemplateBody", template).post("/").then().statusCode(200);
}
private static void assertStatus(String stack, String expected) {
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
assertEquals(expected, state.status(), state.reason());
}
private static void deleteStack(String stack) {
cfn("DeleteStack", stack).post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stack);
}
private static Map<String, String> outputs(String stack) {
String body = cfn("DescribeStacks", stack).post("/").then().statusCode(200).extract().asString();
return XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue");
}
private static Map<String, String> physicalIds(String stack) {
String body = cfn("DescribeStackResources", stack).post("/").then().statusCode(200).extract().asString();
return XmlParser.extractPairs(body, "StackResources", "LogicalResourceId", "PhysicalResourceId");
}
private static boolean hasEvent(String stack, String logicalId, String physicalId, String status) {
String body = cfn("DescribeStackEvents", stack).post("/").then().statusCode(200).extract().asString();
return XmlParser.extractGroups(body, "member").stream()
.anyMatch(event -> logicalId.equals(event.get("LogicalResourceId"))
&& physicalId.equals(event.get("PhysicalResourceId"))
&& status.equals(event.get("ResourceStatus")));
}
/** The {@code Replacement} a change set to {@code template} reports, by logical id. */
private static Map<String, String> replacements(String stack, String changeSet, String template) {
cfn("CreateChangeSet", stack).formParam("ChangeSetName", changeSet).formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template).post("/").then().statusCode(200);
XmlPath body = cfn("DescribeChangeSet", stack).formParam("ChangeSetName", changeSet).post("/")
.then().statusCode(200).extract().xmlPath();
List<String> logicalIds = body.getList(
"**.findAll { it.name() == 'ResourceChange' }.LogicalResourceId", String.class);
List<String> values = body.getList("**.findAll { it.name() == 'ResourceChange' }.Replacement", String.class);
Map<String, String> replacements = new LinkedHashMap<>();
for (int i = 0; i < logicalIds.size(); i++) {
replacements.put(logicalIds.get(i), values.get(i));
}
return replacements;
}
private static RequestSpecification appconfig() {
return given().contentType(ContentType.JSON);
}
private static Map<String, String> applicationTags(String applicationId) {
JsonPath body = appconfig().get("/tags/arn:aws:appconfig:us-east-1:000000000000:application/" + applicationId)
.then().statusCode(200).extract().jsonPath();
return body.getMap("Tags", String.class, String.class);
}
}
@@ -0,0 +1,199 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.services.appconfig.AppConfigService;
import io.github.hectorvent.floci.services.appconfig.model.Application;
import io.github.hectorvent.floci.services.appconfig.model.Deployment;
import io.github.hectorvent.floci.services.appconfig.model.DeploymentSummary;
import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersion;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppConfigCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
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.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* AppConfig resources through the real stack engine, for the paths that need it: the order the
* engine deletes a removed application and its displaced children in, a ContinueUpdateRollback
* after an in-place undo that failed, and what earlier deployments report once stack updates change
* or replace the strategy and profile they used. The AppConfig service runs on in-memory storage, whose stores
* the test also reads directly to see what the API can no longer reach.
*/
class CloudFormationAppConfigLifecycleTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final ObjectMapper MAPPER = new ObjectMapper();
private InMemoryStorageFactory storage;
private AppConfigService appConfig;
private CloudFormationService cfn;
private int changeSets;
@BeforeEach
void setUp() {
storage = new InMemoryStorageFactory(ACCOUNT);
appConfig = spy(new AppConfigService(storage, null));
CfnResourceDispatcher dispatcher = new CfnResourceDispatcher(MAPPER,
new CloudFormationResourceRegistry(List.of(new AppConfigCfnProvisioner(appConfig))), null, null);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
cfn = new CloudFormationService(dispatcher, mock(S3Service.class), mock(SsmService.class),
mock(GetStackOutputRoleAuthorizer.class), new CfnDynamicReferences(null, null, MAPPER), MAPPER,
config, regionResolver, Clock.systemUTC(), new InMemoryStorageFactory(ACCOUNT));
}
/**
* Renaming the application's logical id replaces the environment and profile that refer to it.
* The engine deletes the removed application before the displaced children, so their deletes
* must not depend on finding it.
*/
@Test
void childrenMovedToANewApplicationAreDeletedAfterTheOldApplicationIsRemoved() throws Exception {
String children = """
"Env":{"Type":"AWS::AppConfig::Environment","Properties":{"ApplicationId":{"Ref":"%1$s"},"Name":"beta"}},
"Profile":{"Type":"AWS::AppConfig::ConfigurationProfile","Properties":{
"ApplicationId":{"Ref":"%1$s"},"Name":"settings","LocationUri":"hosted"}}""";
deploy("moved", "CREATE", "{\"Resources\":{\"AppA\":{\"Type\":\"AWS::AppConfig::Application\","
+ "\"Properties\":{\"Name\":\"orders\"}}," + children.formatted("AppA") + "}}");
Stack stack = stack("moved");
String oldApp = stack.getResources().get("AppA").getPhysicalId();
String oldEnv = stack.getResources().get("Env").getPhysicalId();
String oldProfile = stack.getResources().get("Profile").getPhysicalId();
appConfig.createHostedConfigurationVersion(oldApp, oldProfile, "{}".getBytes(StandardCharsets.UTF_8),
"application/json", null);
appConfig.startDeployment(oldApp, oldEnv, Map.of("ConfigurationProfileId", oldProfile,
"ConfigurationVersion", "1", "DeploymentStrategyId", "AppConfig.AllAtOnce"));
deploy("moved", "UPDATE", "{\"Resources\":{\"AppB\":{\"Type\":\"AWS::AppConfig::Application\","
+ "\"Properties\":{\"Name\":\"orders\"}}," + children.formatted("AppB") + "}}");
stack = stack("moved");
assertEquals("UPDATE_COMPLETE", stack.getStatus(), stack.getStatusReason());
assertNotEquals(oldEnv, stack.getResources().get("Env").getPhysicalId());
assertTrue(appConfig.listApplications().stream().noneMatch(app -> app.getId().equals(oldApp)));
assertTrue(appConfig.findEnvironment(oldEnv).isEmpty(), "the displaced environment is deleted");
assertTrue(appConfig.findConfigurationProfile(oldProfile).isEmpty(), "the displaced profile is deleted");
assertTrue(store("appconfig-deployments.json", new TypeReference<Map<String, Deployment>>() {})
.scan(key -> key.startsWith(oldApp + "::")).isEmpty(), "with its deployments");
assertTrue(store("appconfig-versions.json", new TypeReference<Map<String, HostedConfigurationVersion>>() {})
.scan(key -> key.startsWith(oldApp + "::")).isEmpty(), "and its hosted configuration versions");
}
/**
* An in-place update whose undo fails ends the stack in UPDATE_ROLLBACK_FAILED. The
* ContinueUpdateRollback that follows must put back the state the update started from, the
* last committed one, not an older state an earlier committed update had replaced.
*/
@Test
void continueUpdateRollbackAfterAFailedUndoRestoresTheLastCommittedState() throws Exception {
String template = "{\"Resources\":{\"App\":{\"Type\":\"AWS::AppConfig::Application\",\"Properties\":"
+ "{\"Name\":\"%s\",\"Tags\":[{\"Key\":\"stage\",\"Value\":\"%s\"}]}}}}";
deploy("retried", "CREATE", template.formatted("first", "1"));
String app = stack("retried").getResources().get("App").getPhysicalId();
deploy("retried", "UPDATE", template.formatted("second", "2"));
assertEquals("UPDATE_COMPLETE", stack("retried").getStatus());
doThrow(new AwsException("InternalServerException", "tag store down", 500))
.when(appConfig).setApplicationTags(anyString(), any());
deploy("retried", "UPDATE", template.formatted("third", "3"));
assertEquals("UPDATE_ROLLBACK_FAILED", stack("retried").getStatus());
doCallRealMethod().when(appConfig).setApplicationTags(anyString(), any());
cfn.continueUpdateRollback("retried", List.of(), false, REGION).get(30, TimeUnit.SECONDS);
assertEquals("UPDATE_ROLLBACK_COMPLETE", stack("retried").getStatus(), stack("retried").getStatusReason());
Application restored = appConfig.getApplication(app);
assertEquals("second", restored.getName());
assertEquals(Map.of("stage", "2"), restored.getTags());
}
/**
* A deployment reports the profile name and strategy settings it started with: an in-place stack
* update that renames the profile and slows the strategy leaves it as it was, and so does a
* replacement that deletes the strategy, after which ListDeployments still answers.
*/
@Test
void earlierDeploymentsKeepTheirSettingsThroughInPlaceUpdatesAndAStrategyReplacement() throws Exception {
String template = """
{"Resources":{
"App":{"Type":"AWS::AppConfig::Application","Properties":{"Name":"orders"}},
"Env":{"Type":"AWS::AppConfig::Environment","Properties":{"ApplicationId":{"Ref":"App"},"Name":"beta"}},
"Profile":{"Type":"AWS::AppConfig::ConfigurationProfile","Properties":{
"ApplicationId":{"Ref":"App"},"Name":"%s","LocationUri":"hosted"}},
"Strategy":{"Type":"AWS::AppConfig::DeploymentStrategy","Properties":{
"Name":"%s","ReplicateTo":"NONE","DeploymentDurationInMinutes":%d,"GrowthFactor":%d}}
}}""";
deploy("history", "CREATE", template.formatted("settings", "gradual", 0, 100));
Stack stack = stack("history");
String app = stack.getResources().get("App").getPhysicalId();
String env = stack.getResources().get("Env").getPhysicalId();
String profile = stack.getResources().get("Profile").getPhysicalId();
String strategy = stack.getResources().get("Strategy").getPhysicalId();
appConfig.createHostedConfigurationVersion(app, profile, "{}".getBytes(StandardCharsets.UTF_8),
"application/json", null);
appConfig.startDeployment(app, env, Map.of("ConfigurationProfileId", profile, "ConfigurationVersion", "1",
"DeploymentStrategyId", strategy));
deploy("history", "UPDATE", template.formatted("renamed", "gradual", 10, 20));
assertEquals("UPDATE_COMPLETE", stack("history").getStatus(), stack("history").getStatusReason());
assertEquals(strategy, stack("history").getResources().get("Strategy").getPhysicalId(), "changed in place");
assertStartedWith(app, env);
deploy("history", "UPDATE", template.formatted("renamed", "faster", 10, 20));
assertEquals("UPDATE_COMPLETE", stack("history").getStatus(), stack("history").getStatusReason());
assertNotEquals(strategy, stack("history").getResources().get("Strategy").getPhysicalId(), "replaced");
assertStartedWith(app, env);
}
private void assertStartedWith(String app, String env) {
DeploymentSummary deployment = appConfig.listDeployments(app, env, null, null).items().getFirst();
assertEquals("settings", deployment.getConfigurationName());
assertEquals(0, deployment.getDeploymentDurationInMinutes());
assertEquals(100f, deployment.getGrowthFactor());
}
private <V> StorageBackend<String, V> store(String fileName, TypeReference<Map<String, V>> type) {
return storage.create("appconfig", fileName, type);
}
private void deploy(String name, String type, String template) throws Exception {
String changeSet = "change-" + (++changeSets);
cfn.createChangeSet(name, changeSet, type, template, null, Map.of(), List.of(), Map.of(), REGION, ACCOUNT);
cfn.executeChangeSet(name, changeSet, REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
}
private Stack stack(String name) {
return cfn.describeStacks(name, REGION, ACCOUNT).getFirst();
}
}
@@ -0,0 +1,669 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.appconfig.AppConfigService;
import io.github.hectorvent.floci.services.appconfig.model.Application;
import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile;
import io.github.hectorvent.floci.services.appconfig.model.Deployment;
import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy;
import io.github.hectorvent.floci.services.appconfig.model.Environment;
import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersion;
import io.github.hectorvent.floci.services.appconfig.model.Monitor;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* {@code AWS::AppConfig::*} against a real AppConfig service on in-memory storage: the physical id
* is the AppConfig ID and the ID attribute, mutable properties change in place and roll back from
* the snapshot, a create-only change replaces the entity, and deletes go by exact ID.
*/
class AppConfigCfnProvisionerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String STACK = "configuration";
private static final String APPLICATION = "AWS::AppConfig::Application";
private static final String ENVIRONMENT = "AWS::AppConfig::Environment";
private static final String PROFILE = "AWS::AppConfig::ConfigurationProfile";
private static final String STRATEGY = "AWS::AppConfig::DeploymentStrategy";
private static final String ALARM = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors";
private static final String ALARM_ROLE = "arn:aws:iam::000000000000:role/appconfig-monitor";
private InMemoryStorageFactory storage;
private AppConfigService service;
private AppConfigCfnProvisioner provisioner;
private CloudFormationTemplateEngine engine;
@BeforeEach
void setUp() {
storage = new InMemoryStorageFactory(ACCOUNT);
service = spy(new AppConfigService(storage, null));
provisioner = new AppConfigCfnProvisioner(service);
engine = CloudFormationTemplateEngine.standalone(ACCOUNT, REGION, STACK, MAPPER, value -> value);
}
@Test
void anApplicationIsCreatedWithItsTagsAndItsIdIsTheRefAndTheAttribute() {
StackResource app = create(APPLICATION, props("Name", "orders", "Description", "Order service",
"Tags", List.of(tag("team", "payments"))));
Application stored = service.getApplication(app.getPhysicalId());
assertEquals(app.getPhysicalId(), app.getAttributes().get("ApplicationId"));
assertEquals("orders", stored.getName());
assertEquals("Order service", stored.getDescription());
assertEquals(Map.of("team", "payments"), stored.getTags());
}
@Test
void anApplicationUpdateChangesItInPlaceAndARollbackPutsItBack() {
StackResource app = create(APPLICATION, props("Name", "orders", "Description", "Order service",
"Tags", List.of(tag("team", "payments"), tag("tier", "gold"))));
String id = app.getPhysicalId();
update(app, props("Name", "orders-v2", "Tags", List.of(tag("team", "billing"), tag("owner", "ops"))));
assertEquals(id, app.getPhysicalId());
Application updated = service.getApplication(id);
assertEquals("orders-v2", updated.getName());
assertNull(updated.getDescription(), "a Description the template drops is cleared");
assertEquals(Map.of("team", "billing", "owner", "ops"), updated.getTags(), "tags follow the template");
assertTrue(provisioner.rollbackUpdate(app));
Application restored = service.getApplication(id);
assertEquals("orders", restored.getName());
assertEquals("Order service", restored.getDescription());
assertEquals(Map.of("team", "payments", "tier", "gold"), restored.getTags());
assertFalse(app.getAttributes().containsKey(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR));
}
@Test
void aCreateWhoseTaggingFailsDeletesTheApplication() {
doThrow(new AwsException("InternalServerException", "tagging failed", 500))
.when(service).setApplicationTags(anyString(), any());
StackResource app = resource(APPLICATION);
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(app,
MAPPER.valueToTree(props("Name", "orders", "Tags", List.of(tag("team", "payments")))), context(null)));
assertEquals("tagging failed", failure.getMessage());
assertTrue(service.listApplications().isEmpty(), "the application the failed create made is deleted");
assertFalse(app.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void anUpdateWhoseTaggingFailsPutsTheNameBack() {
StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments"))));
// Only the update's own tag call fails; the undo's succeeds.
doThrow(new AwsException("InternalServerException", "tagging failed", 500)).doCallRealMethod()
.when(service).setApplicationTags(anyString(), any());
assertThrows(AwsException.class, () -> update(app, props("Name", "orders-v2",
"Tags", List.of(tag("team", "billing")))));
Application restored = service.getApplication(app.getPhysicalId());
assertEquals("orders", restored.getName());
assertEquals(Map.of("team", "payments"), restored.getTags());
assertFalse(app.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR),
"the undo completed, so the stack can report the prior application intact");
}
@Test
void anUndoThatFailsTooIsRecordedForTheRollback() {
StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments"))));
doThrow(new AwsException("InternalServerException", "tagging failed", 500))
.when(service).setApplicationTags(anyString(), any());
AwsException failure = assertThrows(AwsException.class, () -> update(app, props("Name", "orders-v2",
"Tags", List.of(tag("team", "billing")))));
assertEquals("tagging failed", failure.getMessage(), "the stack reports the update's own failure");
assertTrue(app.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)
.startsWith("Could not restore " + app.getPhysicalId()));
}
/**
* The engine puts the previous resource back over an attempt whose undo failed; that resource
* then carries the attempt's snapshot, the state the update started from, in place of the one an
* earlier committed update left on it, so a ContinueUpdateRollback restores the right state.
*/
@Test
void anUndoThatFailedLeavesItsSnapshotOnTheRestoredResource() {
StackResource app = create(APPLICATION, props("Name", "first", "Tags", List.of(tag("stage", "1"))));
update(app, props("Name", "second", "Tags", List.of(tag("stage", "2"))));
StackResource committed = copy(app);
StackResource attempt = copy(committed);
doThrow(new AwsException("InternalServerException", "tagging failed", 500))
.when(service).setApplicationTags(anyString(), any());
assertThrows(AwsException.class, () -> update(attempt, props("Name", "third",
"Tags", List.of(tag("stage", "3")))));
provisioner.mergeFailedUpdateResourceTracking(committed, attempt);
doCallRealMethod().when(service).setApplicationTags(anyString(), any());
assertTrue(provisioner.rollbackUpdate(committed));
Application restored = service.getApplication(app.getPhysicalId());
assertEquals("second", restored.getName());
assertEquals(Map.of("stage", "2"), restored.getTags());
}
@Test
void anUndoThatCompletedLeavesTheRestoredResourceAlone() {
StackResource app = create(APPLICATION, props("Name", "first"));
StackResource committed = copy(app);
StackResource attempt = copy(committed);
update(attempt, props("Name", "second"));
provisioner.mergeFailedUpdateResourceTracking(committed, attempt);
assertEquals(app.getAttributes(), committed.getAttributes());
}
@Test
void anEnvironmentKeepsItsMonitorsAndChangesInPlace() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta",
"Monitors", List.of(Map.of("AlarmArn", ALARM, "AlarmRoleArn", ALARM_ROLE))));
String id = env.getPhysicalId();
assertEquals(id, env.getAttributes().get("EnvironmentId"));
assertEquals(List.of(new Monitor(ALARM, ALARM_ROLE)), service.getEnvironment(appId, id).getMonitors());
update(env, props("ApplicationId", appId, "Name", "gamma", "Description", "Second stage"));
assertEquals(id, env.getPhysicalId());
Environment updated = service.getEnvironment(appId, id);
assertEquals("gamma", updated.getName());
assertEquals("Second stage", updated.getDescription());
assertNull(updated.getMonitors(), "Monitors the template drops are cleared");
provisioner.rollbackUpdate(env);
Environment restored = service.getEnvironment(appId, id);
assertEquals("beta", restored.getName());
assertNull(restored.getDescription());
assertEquals(List.of(new Monitor(ALARM, ALARM_ROLE)), restored.getMonitors());
}
@Test
void invalidMonitorsAreRefusedBeforeTheEnvironmentChanges() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta"));
AwsException failure = assertThrows(AwsException.class, () -> update(env, props("ApplicationId", appId,
"Name", "gamma", "Monitors", List.of(Map.of("AlarmArn", ALARM, "AlarmRoleArn", "not-a-role")))));
assertEquals("BadRequestException", failure.getErrorCode());
assertEquals("beta", service.getEnvironment(appId, env.getPhysicalId()).getName());
}
@Test
void movingAnEnvironmentToAnotherApplicationReplacesItAndTheCommittedUpdateDeletesTheOldOne() {
String first = create(APPLICATION, props("Name", "orders")).getPhysicalId();
String second = create(APPLICATION, props("Name", "billing")).getPhysicalId();
StackResource env = create(ENVIRONMENT, props("ApplicationId", first, "Name", "beta"));
String oldId = env.getPhysicalId();
update(env, props("ApplicationId", second, "Name", "beta"));
String newId = env.getPhysicalId();
assertNotEquals(oldId, newId);
assertEquals(second, service.getEnvironment(second, newId).getApplicationId());
assertTrue(provisioner.hasReplacementUpdate(env));
assertEquals(oldId, provisioner.updateCleanupPhysicalId(env));
assertTrue(service.findEnvironment(oldId).isPresent(), "the displaced environment stays until the update commits");
assertTrue(provisioner.completeUpdate(env).complete());
assertTrue(service.findEnvironment(oldId).isEmpty());
provisioner.clearUpdate(env);
assertFalse(provisioner.hasReplacementUpdate(env));
}
@Test
void aRolledBackReplacementDeletesTheNewProfileAndNamesThePriorOneAgain() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings",
"LocationUri", "hosted", "Type", "AWS.Freeform"));
String oldId = profile.getPhysicalId();
Map<String, String> before = Map.copyOf(profile.getAttributes());
update(profile, props("ApplicationId", appId, "Name", "settings", "LocationUri", "ssm-parameter://settings",
"Type", "AWS.Freeform"));
String newId = profile.getPhysicalId();
assertNotEquals(oldId, newId);
assertEquals("ssm-parameter://settings", service.getConfigurationProfile(appId, newId).getLocationUri());
assertTrue(provisioner.rollbackUpdate(profile));
assertEquals(oldId, profile.getPhysicalId());
assertEquals(before, profile.getAttributes(), "the prior profile's ID and create-only values are back");
assertTrue(service.findConfigurationProfile(newId).isEmpty(), "the replacement is deleted");
assertEquals("hosted", service.getConfigurationProfile(appId, oldId).getLocationUri());
}
@Test
void aProfileWithoutTypeHasNoneAndAddingOneReplacesIt() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings",
"LocationUri", "hosted"));
String oldId = profile.getPhysicalId();
assertEquals(oldId, profile.getAttributes().get("ConfigurationProfileId"));
assertNull(service.getConfigurationProfile(appId, oldId).getType());
update(profile, props("ApplicationId", appId, "Name", "flags", "LocationUri", "hosted",
"Type", "AWS.AppConfig.FeatureFlags"));
assertNotEquals(oldId, profile.getPhysicalId());
ConfigurationProfile replacement = service.getConfigurationProfile(appId, profile.getPhysicalId());
assertEquals("AWS.AppConfig.FeatureFlags", replacement.getType());
assertEquals("flags", replacement.getName());
}
@Test
void aProfileNameAndDescriptionChangeInPlace() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings",
"LocationUri", "hosted", "Description", "First"));
String id = profile.getPhysicalId();
update(profile, props("ApplicationId", appId, "Name", "renamed", "LocationUri", "hosted"));
assertEquals(id, profile.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(profile));
ConfigurationProfile updated = service.getConfigurationProfile(appId, id);
assertEquals("renamed", updated.getName());
assertNull(updated.getDescription());
provisioner.rollbackUpdate(profile);
assertEquals("settings", service.getConfigurationProfile(appId, id).getName());
assertEquals("First", service.getConfigurationProfile(appId, id).getDescription());
}
@Test
void aStrategyChangesInPlaceAndPropertiesTheTemplateDropsGoBackToTheirDefaults() {
StackResource strategy = create(STRATEGY, props("Name", "gradual", "ReplicateTo", "NONE",
"DeploymentDurationInMinutes", 10, "FinalBakeTimeInMinutes", 5, "GrowthFactor", 25,
"GrowthType", "EXPONENTIAL", "Description", "Slow"));
String id = strategy.getPhysicalId();
assertEquals(id, strategy.getAttributes().get("Id"));
update(strategy, props("Name", "gradual", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", "20",
"GrowthFactor", 12.5));
assertEquals(id, strategy.getPhysicalId());
DeploymentStrategy updated = service.getDeploymentStrategy(id);
assertEquals(20, updated.getDeploymentDurationInMinutes(), "a parameter supplies a number as a string");
assertEquals(0, updated.getFinalBakeTimeInMinutes());
assertEquals(12.5f, updated.getGrowthFactor());
assertEquals("LINEAR", updated.getGrowthType());
assertNull(updated.getDescription());
provisioner.rollbackUpdate(strategy);
DeploymentStrategy restored = service.getDeploymentStrategy(id);
assertEquals(10, restored.getDeploymentDurationInMinutes());
assertEquals(5, restored.getFinalBakeTimeInMinutes());
assertEquals(25f, restored.getGrowthFactor());
assertEquals("EXPONENTIAL", restored.getGrowthType());
assertEquals("Slow", restored.getDescription());
}
@Test
void renamingAStrategyReplacesIt() {
StackResource strategy = create(STRATEGY, props("Name", "gradual", "ReplicateTo", "NONE",
"DeploymentDurationInMinutes", 0, "GrowthFactor", 100));
String oldId = strategy.getPhysicalId();
update(strategy, props("Name", "immediate", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 0,
"GrowthFactor", 100));
assertNotEquals(oldId, strategy.getPhysicalId());
assertEquals("immediate", service.getDeploymentStrategy(strategy.getPhysicalId()).getName());
assertEquals(oldId, provisioner.updateCleanupPhysicalId(strategy));
provisioner.completeUpdate(strategy);
assertThrows(AwsException.class, () -> service.getDeploymentStrategy(oldId));
}
@Test
void invalidStrategyNumbersAndEnumsAreRefusedBeforeAnythingIsCreated() {
List<Map<String, Object>> invalid = List.of(
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1.5, "GrowthFactor", 10),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", -1, "GrowthFactor", 10),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1441, "GrowthFactor", 10),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", "soon", "GrowthFactor", 10),
props("Name", "s", "ReplicateTo", "NONE", "GrowthFactor", 10),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1,
"FinalBakeTimeInMinutes", 2000, "GrowthFactor", 10),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 0.5),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 101),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1),
props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10,
"GrowthType", "QUADRATIC"),
props("Name", "s", "ReplicateTo", "S3", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10),
props("Name", "s", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10),
props("ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10),
props("Name", "s".repeat(65), "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1,
"GrowthFactor", 10));
for (Map<String, Object> properties : invalid) {
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource(STRATEGY), MAPPER.valueToTree(properties), context(null)),
properties.toString());
assertEquals("ValidationError", failure.getErrorCode(), properties.toString());
}
verify(service, never()).createDeploymentStrategy(any());
}
@Test
void requiredPropertiesAndLimitsAreCheckedBeforeAnythingIsCreated() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
Map<String, Map<String, Object>> invalid = new LinkedHashMap<>();
invalid.put(APPLICATION, props("Description", "no name"));
invalid.put(APPLICATION + " long name", props("Name", "a".repeat(65)));
invalid.put(APPLICATION + " long description", props("Name", "orders", "Description", "d".repeat(1025)));
invalid.put(ENVIRONMENT, props("Name", "beta"));
invalid.put(ENVIRONMENT + " no name", props("ApplicationId", appId));
invalid.put(ENVIRONMENT + " deletion protection", props("ApplicationId", appId, "Name", "beta",
"DeletionProtectionCheck", "SOMETIMES"));
invalid.put(PROFILE, props("ApplicationId", appId, "Name", "settings"));
invalid.put(PROFILE + " long name", props("ApplicationId", appId, "Name", "p".repeat(129),
"LocationUri", "hosted"));
invalid.put(PROFILE + " no application", props("Name", "settings", "LocationUri", "hosted"));
for (Map.Entry<String, Map<String, Object>> entry : invalid.entrySet()) {
String type = entry.getKey().split(" ")[0];
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(type),
MAPPER.valueToTree(entry.getValue()), context(null)), entry.getKey());
assertEquals("ValidationError", failure.getErrorCode(), entry.getKey());
}
assertEquals(1, service.listApplications().size());
assertTrue(service.listEnvironments(appId).isEmpty());
assertTrue(service.listConfigurationProfiles(appId).isEmpty());
}
@Test
void noValueLeavesAnOptionalPropertyOut() {
StackResource app = create(APPLICATION, props("Name", "orders",
"Description", Map.of("Ref", "AWS::NoValue")));
assertNull(service.getApplication(app.getPhysicalId()).getDescription());
}
@Test
void aStubFromBeforeTheProvisionerIsReplacedByARealEntityAndARollbackPutsTheStubBack() {
StackResource app = resource(APPLICATION);
String stubId = "App-0a1b2c3d";
app.setPhysicalId(stubId);
app.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "App");
provisioner.provision(app, MAPPER.valueToTree(props("Name", "orders")), context(stubId));
String created = app.getPhysicalId();
assertNotEquals(stubId, created);
assertEquals("orders", service.getApplication(created).getName());
assertTrue(provisioner.rollbackUpdate(app));
assertEquals(stubId, app.getPhysicalId());
assertTrue(service.listApplications().isEmpty(), "the rollback deletes what the migration created");
}
@Test
void deletesGoByExactIdAndCountAnEntityAlreadyGoneAsDeleted() {
StackResource app = create(APPLICATION, props("Name", "orders"));
StackResource env = create(ENVIRONMENT, props("ApplicationId", app.getPhysicalId(), "Name", "beta"));
StackResource profile = create(PROFILE, props("ApplicationId", app.getPhysicalId(), "Name", "settings",
"LocationUri", "hosted"));
StackResource strategy = create(STRATEGY, props("Name", "now", "ReplicateTo", "NONE",
"DeploymentDurationInMinutes", 0, "GrowthFactor", 100));
// An application named like a gone application's ID must survive that ID's delete.
Application namedLikeAnId = service.createApplication(Map.of("Name", "gone123"));
for (StackResource resource : List.of(env, profile, strategy, app)) {
provisioner.delete(resource, REGION);
assertDoesNotThrow(() -> provisioner.delete(resource, REGION), resource.getResourceType());
}
provisioner.delete(APPLICATION, "gone123", REGION);
assertTrue(service.findEnvironment(env.getPhysicalId()).isEmpty());
assertTrue(service.findConfigurationProfile(profile.getPhysicalId()).isEmpty());
assertThrows(AwsException.class, () -> service.getDeploymentStrategy(strategy.getPhysicalId()));
assertEquals(List.of(namedLikeAnId.getId()), service.listApplications().stream().map(Application::getId).toList());
}
/**
* DeleteApplication takes a name as well as an ID, so a delete that first looks the application
* up and then deletes it through that API removes another application named like its ID when
* the API deletes the first in between. A stack's delete is one exact-ID call; this pins that
* it neither calls DeleteApplication's lookup nor looks the application up first.
*/
@Test
void anApplicationDeletedThroughTheApiMidDeleteLeavesOneNamedLikeItsIdAlone() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
Application namedLikeTheId = service.createApplication(Map.of("Name", appId));
doAnswer(invocation -> {
Object found = invocation.callRealMethod();
service.deleteApplication(appId);
return found;
}).when(service).findApplication(appId);
provisioner.delete(APPLICATION, appId, REGION);
verify(service).deleteApplicationById(appId);
verify(service, never()).deleteApplication(anyString());
assertEquals(List.of(namedLikeTheId.getId()),
service.listApplications().stream().map(Application::getId).toList());
}
@Test
void aFailedCreateUndoesOnlyItsOwnApplication() {
StackResource app = resource(APPLICATION);
doAnswer(invocation -> {
String appId = invocation.getArgument(0);
service.deleteApplication(appId);
service.createApplication(Map.of("Name", appId));
throw new AwsException("InternalServerException", "tagging failed", 500);
}).when(service).setApplicationTags(anyString(), any());
assertThrows(AwsException.class, () -> provisioner.provision(app,
MAPPER.valueToTree(props("Name", "orders", "Tags", List.of(tag("team", "payments")))), context(null)));
assertEquals(List.of(app.getPhysicalId()),
service.listApplications().stream().map(Application::getName).toList(),
"the application named like the undone one's ID is not the stack's");
}
/**
* Tags, like deletes, go by exact ID: an application the API deletes while the stack writes its
* tags fails the stack, and the tags never land on another application named like its ID.
*/
@Test
void anUpdateWhoseApplicationTheApiDeletedLeavesOneNamedLikeItsIdUntagged() {
StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments"))));
String appId = app.getPhysicalId();
Application namedLikeTheId = service.createApplication(Map.of("Name", appId));
service.tagApplication(namedLikeTheId.getId(), Map.of("owner", "billing"));
doAnswer(invocation -> {
Object updated = invocation.callRealMethod();
service.deleteApplication(appId);
return updated;
}).when(service).updateApplication(anyString(), any(), any());
AwsException failure = assertThrows(AwsException.class, () -> update(app, props("Name", "orders-v2",
"Tags", List.of(tag("team", "checkout")))));
assertEquals("ResourceNotFoundException", failure.getErrorCode());
assertEquals(Map.of("owner", "billing"), service.getApplication(namedLikeTheId.getId()).getTags());
}
@Test
void aCreateWhoseApplicationTheApiDeletedLeavesOneNamedLikeItsIdUntagged() {
doAnswer(invocation -> {
Application created = (Application) invocation.callRealMethod();
service.deleteApplication(created.getId());
service.createApplication(Map.of("Name", created.getId()));
return created;
}).doCallRealMethod().when(service).createApplication(any());
StackResource app = resource(APPLICATION);
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(app,
MAPPER.valueToTree(props("Name", "orders", "Tags", List.of(tag("team", "payments")))), context(null)));
assertEquals("ResourceNotFoundException", failure.getErrorCode());
Application namedLikeTheId = service.getApplication(app.getPhysicalId());
assertNotEquals(app.getPhysicalId(), namedLikeTheId.getId());
assertTrue(namedLikeTheId.getTags().isEmpty(), "the stack's tags are not written to another application");
}
/**
* {@code ApplicationId} is the application's ID or name, as on AWS: an environment and a profile
* whose {@code ApplicationId} names an existing application are created under it.
*/
@Test
void anEnvironmentAndAProfileCanNameTheirApplication() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource env = create(ENVIRONMENT, props("ApplicationId", "orders", "Name", "beta"));
StackResource profile = create(PROFILE, props("ApplicationId", "orders", "Name", "settings",
"LocationUri", "hosted"));
assertEquals(appId, service.findEnvironment(env.getPhysicalId()).orElseThrow().getApplicationId());
assertEquals(appId, service.findConfigurationProfile(profile.getPhysicalId()).orElseThrow().getApplicationId());
String recordedApplication = CfnRollback.USES_ATTR_PREFIX + "AppConfigApplicationId";
assertEquals(appId, env.getAttributes().get(recordedApplication), "the stack records the application's ID");
assertEquals(appId, profile.getAttributes().get(recordedApplication));
}
@Test
void anUpdateThatDropsTagsClearsThem() {
StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments"))));
update(app, props("Name", "orders"));
assertTrue(service.getApplication(app.getPhysicalId()).getTags().isEmpty());
}
/**
* An update that moves an environment and a profile to another application can delete the old
* application first, so their deletes must not depend on it; they still take their deployments
* and hosted configuration versions with them.
*/
@Test
void anEnvironmentAndAProfileWhoseApplicationIsGoneAreStillDeleted() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta"));
StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings",
"LocationUri", "hosted"));
service.createHostedConfigurationVersion(appId, profile.getPhysicalId(), "{}".getBytes(), "application/json",
null);
service.startDeployment(appId, env.getPhysicalId(), Map.of("ConfigurationProfileId", profile.getPhysicalId(),
"ConfigurationVersion", "1", "DeploymentStrategyId", "AppConfig.AllAtOnce"));
service.deleteApplication(appId);
provisioner.delete(ENVIRONMENT, env.getPhysicalId(), REGION);
provisioner.delete(PROFILE, profile.getPhysicalId(), REGION);
assertTrue(service.findEnvironment(env.getPhysicalId()).isEmpty());
assertTrue(service.findConfigurationProfile(profile.getPhysicalId()).isEmpty());
assertTrue(storage.create("appconfig", "appconfig-deployments.json",
new TypeReference<Map<String, Deployment>>() {}).scan(key -> key.startsWith(appId + "::")).isEmpty());
assertTrue(storage.create("appconfig", "appconfig-versions.json",
new TypeReference<Map<String, HostedConfigurationVersion>>() {})
.scan(key -> key.startsWith(appId + "::")).isEmpty());
}
@Test
void aDeleteFailureOtherThanNotFoundPropagates() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta"));
AwsException storage = new AwsException("InternalServerException", "storage failed", 500);
doThrow(storage).when(service).deleteEnvironmentById(env.getPhysicalId());
assertSame(storage, assertThrows(AwsException.class, () -> provisioner.delete(env, REGION)));
}
@Test
void aStubIsNotDeleted() {
StackResource stub = resource(ENVIRONMENT);
stub.setPhysicalId("Env-0a1b2c3d");
stub.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "Env");
provisioner.delete(stub, REGION);
verify(service, never()).deleteEnvironmentById(anyString());
verify(service, never()).deleteEnvironment(anyString(), anyString());
}
@Test
void anUpdateOfAnEnvironmentDeletedOutsideTheStackFails() {
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta"));
service.deleteEnvironment(appId, env.getPhysicalId());
AwsException failure = assertThrows(AwsException.class,
() -> update(env, props("ApplicationId", appId, "Name", "gamma")));
assertEquals("ResourceNotFoundException", failure.getErrorCode());
}
private StackResource create(String type, Map<String, Object> properties) {
StackResource resource = resource(type);
provisioner.provision(resource, MAPPER.valueToTree(properties), context(null));
return resource;
}
/** Provisions {@code resource} again with {@code properties}, as an UpdateStack does. */
private void update(StackResource resource, Map<String, Object> properties) {
provisioner.provision(resource, MAPPER.valueToTree(properties), context(resource.getPhysicalId()));
}
/** The resource as the stack stores it, so a provision of the copy leaves the original alone. */
private static StackResource copy(StackResource resource) {
StackResource copy = resource(resource.getResourceType());
copy.setPhysicalId(resource.getPhysicalId());
copy.getAttributes().putAll(resource.getAttributes());
return copy;
}
private static StackResource resource(String type) {
StackResource resource = new StackResource();
resource.setLogicalId(type.substring(type.lastIndexOf(':') + 1));
resource.setResourceType(type);
return resource;
}
private ProvisionContext context(String priorPhysicalId) {
return new ProvisionContext(engine, REGION, ACCOUNT, STACK, priorPhysicalId);
}
/** Alternating property names and values, in order. */
private static Map<String, Object> props(Object... namesAndValues) {
Map<String, Object> properties = new LinkedHashMap<>();
for (int i = 0; i < namesAndValues.length; i += 2) {
properties.put((String) namesAndValues[i], namesAndValues[i + 1]);
}
return properties;
}
private static Map<String, String> tag(String key, String value) {
return Map.of("Key", key, "Value", value);
}
}