fix(cloudformation): provision a usage plan's throttle, quota and stage throttles (#6419)

* fix(cloudformation): provision a usage plan's throttle, quota and stage throttles

* fix(cloudformation): roll back a usage plan when its stack update fails

* fix(cloudformation): keep a failed usage plan update for its rollback retry

* fix(cloudformation): snapshot a usage plan under its patch lock

* fix(cloudformation): restore a usage plan without a lock-free comparison

* refactor(cloudformation): share the API key and usage plan update rollback through CfnRollback
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-26 06:55:14 -04:00
1 parent 0634184f5e
commit e09c0b648f
11 files changed
+1141 -175

No files matched your search

@@ -21,8 +21,12 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -165,4 +169,62 @@ class ApiGatewayUsagePlanServiceTest {
}
assertEquals(0, resurrected, "plans a patch wrote back after they were deleted");
}
// A failed CloudFormation update is undone with every value it had, a description it lacked included.
@Test
void restoreSetsEveryValueOfThePlanANullDescriptionIncluded() {
ApiGatewayService service = service();
String planId = service.createUsagePlan(REGION, Map.of("name", "restored", "tags", Map.of("stack", "v1")))
.getId();
service.updateUsagePlan(REGION, planId, List.of(
Map.of("op", "replace", "path", "/name", "value", "renamed"),
Map.of("op", "replace", "path", "/description", "value", "added")));
UsagePlan.Limits limits = new UsagePlan.Limits(
List.of(new UsagePlan.ApiStage("api", "v1", Map.of("/pets/GET", new UsagePlan.Throttle(3, 1.0)))),
new UsagePlan.Throttle(10, 5.0), new UsagePlan.Quota(100, 0, "DAY"));
service.restoreUsagePlan(REGION, planId, "restored", null, limits, Map.of("stack", "v1"));
UsagePlan plan = service.getUsagePlan(REGION, planId);
assertEquals("restored", plan.getName());
assertNull(plan.getDescription());
assertEquals(limits, plan.limits());
assertEquals(Map.of("stack", "v1"), plan.getTags());
}
// A CloudFormation update snapshots the plan through this read, so a patch landing halfway through it
// would leave a snapshot mixing two revisions. The patch has to wait until the reader returns: the
// reader holds on until the patch's thread is blocked or the patch is done, so a slow start cannot
// pass for a wait.
@Test
void aPatchWaitsForAReadOfThePlanToFinish() throws Exception {
ApiGatewayService service = service();
String planId = service.createUsagePlan(REGION, Map.of("name", "before")).getId();
AtomicReference<Thread> worker = new AtomicReference<>();
CountDownLatch started = new CountDownLatch(1);
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<UsagePlan> patch = service.readUsagePlan(REGION, planId, plan -> {
Future<UsagePlan> pending = executor.submit(() -> {
worker.set(Thread.currentThread());
started.countDown();
return service.updateUsagePlan(REGION, planId,
List.of(Map.of("op", "replace", "path", "/name", "value", "after")));
});
assertTrue(assertDoesNotThrow(() -> started.await(5, TimeUnit.SECONDS)),
"the patch never started");
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (worker.get().getState() != Thread.State.BLOCKED && !pending.isDone()
&& System.nanoTime() < deadline) {
Thread.onSpinWait();
}
assertFalse(pending.isDone(), "the patch finished while the plan was being read");
assertEquals(Thread.State.BLOCKED, worker.get().getState());
assertEquals("before", plan.getName());
return pending;
});
assertEquals("after", patch.get(5, TimeUnit.SECONDS).getName());
assertEquals("after", service.getUsagePlan(REGION, planId).getName());
}
}
}
@@ -1,24 +1,22 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
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.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
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.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -26,13 +24,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* {@code AWS::ApiGateway::UsagePlanKey} attaching an API key to it, the way a template guards an
* API behind a key. The API and the key are created outside the stack, since the stack only owns
* the plan and the association. Asserts that {@code Ref} and {@code Fn::GetAtt Id} resolve to the
* plan id and to {@code <keyId>:<usagePlanId>}, that an update renames the plan and moves its stage
* in place, and that deleting the stack removes the plan and the association but not the key.
* plan id and to {@code <keyId>:<usagePlanId>}, that the plan reports its stage with the stage's
* method throttle, its throttle and its quota, that an update renames the plan, moves its stage and
* changes the stage throttle in place and drops a quota the template omits through
* {@code AWS::NoValue}, and that deleting the stack removes the plan and
* the association but not the key.
*/
@QuarkusTest
class ApiGatewayUsagePlanCfnIntegrationTest {
private static final String REGION = "us-east-1";
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
private static final String STACK = "apigw-usageplan-cfn-it";
@@ -45,7 +45,13 @@ class ApiGatewayUsagePlanCfnIntegrationTest {
"KeyId": {"Type": "String"},
"PlanName": {"Type": "String"},
"Description": {"Type": "String"},
"TagValue": {"Type": "String"}
"TagValue": {"Type": "String"},
"QuotaLimit": {"Type": "Number"},
"BurstLimit": {"Type": "Number"},
"WithQuota": {"Type": "String"}
},
"Conditions": {
"HasQuota": {"Fn::Equals": [{"Ref": "WithQuota"}, "true"]}
},
"Resources": {
"Plan": {
@@ -53,9 +59,11 @@ class ApiGatewayUsagePlanCfnIntegrationTest {
"Properties": {
"UsagePlanName": {"Ref": "PlanName"},
"Description": {"Ref": "Description"},
"ApiStages": [{"ApiId": {"Ref": "ApiId"}, "Stage": {"Ref": "StageName"}}],
"ApiStages": [{"ApiId": {"Ref": "ApiId"}, "Stage": {"Ref": "StageName"},
"Throttle": {"/items/GET": {"BurstLimit": {"Ref": "BurstLimit"}, "RateLimit": 2}}}],
"Throttle": {"BurstLimit": 10, "RateLimit": 5},
"Quota": {"Limit": 1000, "Period": "MONTH"},
"Quota": {"Fn::If": ["HasQuota", {"Limit": {"Ref": "QuotaLimit"}, "Period": "MONTH"},
{"Ref": "AWS::NoValue"}]},
"Tags": [{"Key": "stack", "Value": {"Ref": "TagValue"}}]
}
},
@@ -77,9 +85,6 @@ class ApiGatewayUsagePlanCfnIntegrationTest {
}
""";
@Inject
ApiGatewayService apiGatewayService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -94,7 +99,7 @@ class ApiGatewayUsagePlanCfnIntegrationTest {
String keyId = given().contentType(ContentType.JSON).body("{\"name\":\"" + STACK + "-key\"}")
.when().post("/apikeys").then().statusCode(201).extract().path("id");
try {
cloudFormation("CreateStack", parameters(apiId, "dev", keyId, "gold", "first", "v1"));
cloudFormation("CreateStack", parameters(apiId, "dev", keyId, "gold", "first", "v1", "1000", "4", "true"));
String created = describeStacks("CREATE_COMPLETE");
String planId = outputValue(created, "PlanRef");
@@ -108,11 +113,21 @@ class ApiGatewayUsagePlanCfnIntegrationTest {
.body("name", equalTo("gold"))
.body("description", equalTo("first"))
.body("tags.stack", equalTo("v1"));
assertEquals(List.of(new UsagePlan.ApiStage(apiId, "dev")),
apiGatewayService.getUsagePlan(REGION, planId).getApiStages());
getUsagePlan(planId)
.statusCode(200)
.body("apiStages", hasSize(1))
.body("apiStages[0].apiId", equalTo(apiId))
.body("apiStages[0].stage", equalTo("dev"))
.body("apiStages[0].throttle['/items/GET'].burstLimit", equalTo(4))
.body("apiStages[0].throttle['/items/GET'].rateLimit", equalTo(2.0f))
.body("throttle.burstLimit", equalTo(10))
.body("throttle.rateLimit", equalTo(5.0f))
.body("quota.limit", equalTo(1000))
.body("quota.offset", equalTo(0))
.body("quota.period", equalTo("MONTH"));
getUsagePlanKey(planId, keyId).statusCode(200).body("type", equalTo("API_KEY"));
cloudFormation("UpdateStack", parameters(apiId, "prod", keyId, "platinum", "second", "v2"));
cloudFormation("UpdateStack", parameters(apiId, "prod", keyId, "platinum", "second", "v2", "2000", "6", "false"));
String updated = describeStacks("UPDATE_COMPLETE");
// The plan is renamed and moved to the other stage in place; the association survives.
@@ -123,8 +138,17 @@ class ApiGatewayUsagePlanCfnIntegrationTest {
.body("name", equalTo("platinum"))
.body("description", equalTo("second"))
.body("tags.stack", equalTo("v2"));
assertEquals(List.of(new UsagePlan.ApiStage(apiId, "prod")),
apiGatewayService.getUsagePlan(REGION, planId).getApiStages());
getUsagePlan(planId)
.statusCode(200)
.body("apiStages", hasSize(1))
.body("apiStages[0].apiId", equalTo(apiId))
.body("apiStages[0].stage", equalTo("prod"))
.body("apiStages[0].throttle['/items/GET'].burstLimit", equalTo(6))
.body("apiStages[0].throttle['/items/GET'].rateLimit", equalTo(2.0f))
.body("throttle.burstLimit", equalTo(10))
.body("throttle.rateLimit", equalTo(5.0f))
// AWS::NoValue leaves the quota out of the template, so the update takes it off the plan.
.body("quota", nullValue());
getUsagePlanKey(planId, keyId).statusCode(200);
cloudFormation("DeleteStack", Map.of());
@@ -141,9 +165,11 @@ class ApiGatewayUsagePlanCfnIntegrationTest {
}
private static Map<String, String> parameters(String apiId, String stage, String keyId, String planName,
String description, String tagValue) {
String description, String tagValue, String quotaLimit,
String burstLimit, String withQuota) {
return Map.of("ApiId", apiId, "StageName", stage, "KeyId", keyId, "PlanName", planName,
"Description", description, "TagValue", tagValue);
"Description", description, "TagValue", tagValue, "QuotaLimit", quotaLimit,
"BurstLimit", burstLimit, "WithQuota", withQuota);
}
private static void cloudFormation(String action, Map<String, String> parameters) {
@@ -0,0 +1,228 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
/**
* Stack updates of an {@code AWS::ApiGateway::UsagePlan} that a later resource fails, so the update
* rolls back. Asserts that the plan's name, description, stages with their method throttles,
* throttle, quota and tags come back as they were, that a plan the update created in place of one
* deleted out of band is deleted again, and that a plan whose failed update could not be undone at
* once is put back by ContinueUpdateRollback.
*/
@QuarkusTest
class ApiGatewayUsagePlanCfnRollbackIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
/** One plan with the given properties, optionally followed by more resources. */
private static final String PLAN_TEMPLATE = """
{
"Resources": {
"Plan": {
"Type": "AWS::ApiGateway::UsagePlan",
"Properties": {%s}
}%s
},
"Outputs": {"PlanRef": {"Value": {"Ref": "Plan"}}}
}
""";
/** A resource that fails after the one it depends on, so the update rolls back. */
private static final String FAILING_RESOURCE = """
,
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"DependsOn": "%s",
"Properties": {
"Name": "%s",
"SecretString": "explicit",
"GenerateSecretString": {"PasswordLength": 32}
}
}""";
@InjectSpy
ApiGatewayService apiGatewayService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aFailedUpdatePutsThePlansQuotaThrottleAndNameBack() {
String stack = "apigw-usageplan-cfn-rollback-it";
String original = """
"UsagePlanName": "apigw-usageplan-rollback-original",
"ApiStages": [{"ApiId": "rollbackapi", "Stage": "v1",
"Throttle": {"/items/GET": {"BurstLimit": 3, "RateLimit": 1}}}],
"Throttle": {"BurstLimit": 10, "RateLimit": 5},
"Quota": {"Limit": 1000, "Period": "MONTH"},
"Tags": [{"Key": "stack", "Value": "v1"}]""";
cloudFormation(stack, "CreateStack", PLAN_TEMPLATE.formatted(original, ""));
String planId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "PlanRef");
// Every value changes, the description is added, before the secret fails the update.
String changed = """
"UsagePlanName": "apigw-usageplan-rollback-changed",
"Description": "changed",
"ApiStages": [{"ApiId": "rollbackapi", "Stage": "v2"}],
"Throttle": {"BurstLimit": 20, "RateLimit": 8},
"Quota": {"Limit": 50, "Offset": 1, "Period": "WEEK"},
"Tags": [{"Key": "stack", "Value": "v2"}]""";
cloudFormation(stack, "UpdateStack",
PLAN_TEMPLATE.formatted(changed, FAILING_RESOURCE.formatted("Plan", stack)));
assertEquals(planId, outputValue(describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"), "PlanRef"));
getUsagePlan(planId)
.statusCode(200)
.body("name", equalTo("apigw-usageplan-rollback-original"))
.body("$", not(hasKey("description")))
.body("throttle.burstLimit", equalTo(10))
.body("throttle.rateLimit", equalTo(5.0f))
.body("quota.limit", equalTo(1000))
.body("quota.offset", equalTo(0))
.body("quota.period", equalTo("MONTH"))
.body("apiStages", hasSize(1))
.body("apiStages[0].stage", equalTo("v1"))
.body("apiStages[0].throttle['/items/GET'].burstLimit", equalTo(3))
.body("tags.stack", equalTo("v1"));
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
getUsagePlan(planId).statusCode(404);
}
@Test
void aFailedUpdateDeletesThePlanItCreatedInPlaceOfOneDeletedOutOfBand() {
String stack = "apigw-usageplan-cfn-recreate-it";
String name = "apigw-usageplan-cfn-recreate-it-plan";
String properties = "\"UsagePlanName\": \"" + name + "\"";
cloudFormation(stack, "CreateStack", PLAN_TEMPLATE.formatted(properties, ""));
String planId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "PlanRef");
given().when().delete("/usageplans/" + planId).then().statusCode(202);
// The description makes the update re-provision the plan, which creates one in place of the
// deleted one before the secret fails the update.
cloudFormation(stack, "UpdateStack", PLAN_TEMPLATE.formatted(properties + ", \"Description\": \"changed\"",
FAILING_RESOURCE.formatted("Plan", stack)));
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
given().when().get("/usageplans").then()
.statusCode(200)
.body("item.name", not(hasItem(name)));
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
// The plan's own write fails after changing it, and the provisioner's undo fails once too, so the stack
// stops in UPDATE_ROLLBACK_FAILED with the plan holding the failed update's values. The retry must put
// them back rather than report a rollback that restored nothing.
@Test
void continueUpdateRollbackPutsBackAPlanWhoseFailedUpdateCouldNotBeUndoneAtOnce() {
String stack = "apigw-usageplan-cfn-retry-it";
String original = """
"UsagePlanName": "apigw-usageplan-retry-original",
"Throttle": {"BurstLimit": 10, "RateLimit": 5},
"Quota": {"Limit": 1000, "Period": "MONTH"}""";
cloudFormation(stack, "CreateStack", PLAN_TEMPLATE.formatted(original, ""));
String planId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "PlanRef");
Mockito.doAnswer(invocation -> {
invocation.callRealMethod();
throw new IllegalStateException("simulated write failure");
}).doCallRealMethod().when(apiGatewayService).replaceUsagePlanLimits(anyString(), eq(planId), any());
Mockito.doThrow(new IllegalStateException("simulated restore failure")).doCallRealMethod()
.when(apiGatewayService).restoreUsagePlan(anyString(), eq(planId), any(), any(), any(), anyMap());
String changed = """
"UsagePlanName": "apigw-usageplan-retry-changed",
"Throttle": {"BurstLimit": 20, "RateLimit": 8},
"Quota": {"Limit": 50, "Period": "WEEK"}""";
cloudFormation(stack, "UpdateStack", PLAN_TEMPLATE.formatted(changed, ""));
describeStacks(stack, "UPDATE_ROLLBACK_FAILED");
getUsagePlan(planId)
.statusCode(200)
.body("name", equalTo("apigw-usageplan-retry-changed"))
.body("quota.limit", equalTo(50));
cloudFormation(stack, "ContinueUpdateRollback", null);
assertEquals(planId, outputValue(describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"), "PlanRef"));
getUsagePlan(planId)
.statusCode(200)
.body("name", equalTo("apigw-usageplan-retry-original"))
.body("throttle.burstLimit", equalTo(10))
.body("throttle.rateLimit", equalTo(5.0f))
.body("quota.limit", equalTo(1000))
.body("quota.period", equalTo("MONTH"));
// An update that only changes an output commits afterwards, and leaves the plan as it is.
cloudFormation(stack, "UpdateStack", PLAN_TEMPLATE.formatted(original, "")
.replace("\"PlanRef\": {\"Value\": {\"Ref\": \"Plan\"}}",
"\"PlanRef\": {\"Value\": {\"Ref\": \"Plan\"}}, \"Extra\": {\"Value\": \"x\"}"));
describeStacks(stack, "UPDATE_COMPLETE");
getUsagePlan(planId)
.statusCode(200)
.body("name", equalTo("apigw-usageplan-retry-original"))
.body("quota.limit", equalTo(1000));
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
private static void cloudFormation(String stack, String action, String templateBody) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String stack, String expectedStatus) {
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
assertEquals(expectedStatus, state.status(), state.reason());
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
private static ValidatableResponse getUsagePlan(String planId) {
return given().when().get("/usageplans/" + planId).then();
}
}
@@ -10,25 +10,35 @@ import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
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.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.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/** The API Gateway usage plan CFN provisioner in isolation, against a mocked {@link ApiGatewayService}. */
@@ -39,11 +49,24 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
private static final String PLAN_KEY = "AWS::ApiGateway::UsagePlanKey";
private static final AwsException NOT_FOUND =
new AwsException("NotFoundException", "Usage Plan not found", 404);
/** Stage api1:dev throttling /pets/GET at 10/5.0, throttle 20/10.0, quota 1000/0/MONTH. */
private static final UsagePlan.Limits ORIGINAL_LIMITS = new UsagePlan.Limits(
List.of(new UsagePlan.ApiStage("api1", "dev", Map.of("/pets/GET", new UsagePlan.Throttle(10, 5.0)))),
new UsagePlan.Throttle(20, 10.0), new UsagePlan.Quota(1000, 0, "MONTH"));
private final ApiGatewayService apiGateway = mock(ApiGatewayService.class);
private final ApiGatewayUsagePlanCfnProvisioner provisioner = new ApiGatewayUsagePlanCfnProvisioner(apiGateway);
private final ObjectMapper mapper = new ObjectMapper();
/** The locked read hands its reader the plan {@code getUsagePlan} is stubbed with. */
@BeforeEach
void readTheStubbedPlan() {
when(apiGateway.readUsagePlan(any(), any(), any())).thenAnswer(inv -> {
Function<UsagePlan, Object> reader = inv.getArgument(2);
return reader.apply(apiGateway.getUsagePlan(inv.getArgument(0), inv.getArgument(1)));
});
}
private ProvisionContext ctx() {
return ctx(null);
}
@@ -55,6 +78,7 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
}
@@ -150,11 +174,80 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
}
@Test
void usagePlanUpdatePatchesNameDescriptionAndStagesInPlace() {
void usagePlanCreateSendsThrottleQuotaAndStageThrottles() {
when(apiGateway.createUsagePlan(eq(REGION), anyMap())).thenReturn(plan("plan-1", "gold", null, Map.of()));
ObjectNode props = planProps("gold", null, null);
props.putObject("Throttle").put("BurstLimit", 10).put("RateLimit", 5);
props.putObject("Quota").put("Limit", 1000).put("Offset", 2).put("Period", "WEEK");
ObjectNode stage = ((ArrayNode) props.get("ApiStages")).addObject().put("ApiId", "api1").put("Stage", "dev");
stage.putObject("Throttle").putObject("/pets/GET").put("BurstLimit", 3).put("RateLimit", 1.5);
provisioner.provision(resource(PLAN, "Plan", null), props, ctx());
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
verify(apiGateway).createUsagePlan(eq(REGION), request.capture());
assertEquals(Map.of("burstLimit", "10", "rateLimit", "5"), request.getValue().get("throttle"));
assertEquals(Map.of("limit", "1000", "offset", "2", "period", "WEEK"), request.getValue().get("quota"));
assertEquals(List.of(Map.of("apiId", "api1", "stage", "dev",
"throttle", Map.of("/pets/GET", Map.of("burstLimit", "3", "rateLimit", "1.5")))),
request.getValue().get("apiStages"));
}
@Test
void aQuotaTheServiceWouldRefuseLeavesThePlanUntouched() {
UsagePlan existing = plan("plan-1", "gold", null, Map.of());
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
ObjectNode props = planProps("platinum", null, null);
props.putObject("Quota").put("Limit", 10);
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(PLAN, "Plan", "plan-1"), props, ctx("plan-1")));
assertEquals("BadRequestException", e.getErrorCode());
verify(apiGateway, never()).updateUsagePlan(any(), any(), anyList());
verify(apiGateway, never()).replaceUsagePlanLimits(any(), any(), any());
}
@Test
void aBlankQuotaOffsetIsRefusedRatherThanReadAsZero() {
UsagePlan existing = plan("plan-1", "gold", null, Map.of());
existing.setQuota(new UsagePlan.Quota(10, 3, "WEEK"));
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
ObjectNode props = planProps("gold", null, null);
props.putObject("Quota").put("Limit", 10).put("Offset", "").put("Period", "WEEK");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(PLAN, "Plan", "plan-1"), props, ctx("plan-1")));
assertEquals("Usage Plan quota offset must be numeric and less than the number of time units in the period",
e.getMessage());
verify(apiGateway, never()).replaceUsagePlanLimits(any(), any(), any());
}
@Test
void aBurstLimitThatIsAListIsRefusedRatherThanReadAsZero() {
UsagePlan existing = plan("plan-1", "gold", null, Map.of());
existing.setThrottle(new UsagePlan.Throttle(20, 10.0));
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
ObjectNode props = planProps("gold", null, null);
props.putObject("Throttle").put("RateLimit", 5).putArray("BurstLimit");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(PLAN, "Plan", "plan-1"), props, ctx("plan-1")));
assertEquals("Usage Plan throttle rate limit and burst limit must be numeric and greater than zero",
e.getMessage());
verify(apiGateway, never()).replaceUsagePlanLimits(any(), any(), any());
}
@Test
void usagePlanUpdatePatchesNameAndDescriptionAndReplacesTheStages() {
UsagePlan existing = plan("plan-1", "gold", "old", Map.of(),
new UsagePlan.ApiStage("api1", "dev"), new UsagePlan.ApiStage("api1", "test"));
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
when(apiGateway.updateUsagePlan(eq(REGION), eq("plan-1"), anyList())).thenReturn(existing);
when(apiGateway.replaceUsagePlanLimits(eq(REGION), eq("plan-1"), any())).thenReturn(existing);
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, planProps("platinum", "new", null, "api1:dev", "api1:prod"), ctx("plan-1"));
@@ -166,32 +259,13 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
List<Map<String, String>> ops = patches.getValue();
assertTrue(ops.contains(Map.of("op", "replace", "path", "/name", "value", "platinum")), ops.toString());
assertTrue(ops.contains(Map.of("op", "replace", "path", "/description", "value", "new")), ops.toString());
assertTrue(ops.contains(Map.of("op", "remove", "path", "/apiStages", "value", "api1:test")), ops.toString());
assertTrue(ops.contains(Map.of("op", "add", "path", "/apiStages", "value", "api1:prod")), ops.toString());
assertEquals(4, ops.size(), ops.toString());
assertEquals(2, ops.size(), ops.toString());
verify(apiGateway).replaceUsagePlanLimits(REGION, "plan-1", new UsagePlan.Limits(
List.of(new UsagePlan.ApiStage("api1", "dev"), new UsagePlan.ApiStage("api1", "prod")), null, null));
assertEquals("plan-1", r.getPhysicalId());
assertEquals("plan-1", r.getAttributes().get("Id"));
}
// A stage's method throttle is not part of its identity, so a stage the template still lists stays on the
// plan with its throttle rather than being removed and added again.
@Test
void aThrottledStageTheTemplateStillListsIsLeftInPlace() {
UsagePlan existing = plan("plan-1", "gold", "old", Map.of(), new UsagePlan.ApiStage("api1", "dev",
Map.of("/pets/GET", new UsagePlan.Throttle(10, 5.0))));
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
when(apiGateway.updateUsagePlan(eq(REGION), eq("plan-1"), anyList())).thenReturn(existing);
provisioner.provision(resource(PLAN, "Plan", "plan-1"), planProps("gold", "new", null, "api1:dev"),
ctx("plan-1"));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Map<String, String>>> patches = ArgumentCaptor.forClass(List.class);
verify(apiGateway).updateUsagePlan(eq(REGION), eq("plan-1"), patches.capture());
assertEquals(List.of(Map.of("op", "replace", "path", "/description", "value", "new")),
patches.getValue());
}
@Test
void anUnchangedUsagePlanUpdateTouchesNothing() {
UsagePlan existing = plan("plan-1", "gold", "same", Map.of("stack", "v1"), new UsagePlan.ApiStage("api1", "dev"));
@@ -202,6 +276,7 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
verify(apiGateway, never()).createUsagePlan(any(), anyMap());
verify(apiGateway, never()).updateUsagePlan(any(), any(), anyList());
verify(apiGateway, never()).replaceUsagePlanTags(any(), any(), anyMap());
verify(apiGateway, never()).replaceUsagePlanLimits(any(), any(), any());
}
@Test
@@ -343,6 +418,75 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
verify(apiGateway, never()).createUsagePlanKey(any(), any(), anyMap());
}
private void assertCreateRefused(ObjectNode props, String message) {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(PLAN, "Plan", null), props, ctx()));
assertEquals("ValidationError", e.getErrorCode());
assertEquals(message, e.getMessage());
verify(apiGateway, never()).createUsagePlan(any(), anyMap());
}
@Test
void aPlanThrottleThatIsNotAnObjectIsRefused() {
ObjectNode props = planProps("gold", null, null);
props.putArray("Throttle").addObject().put("BurstLimit", 10);
assertCreateRefused(props, "Property [Throttle] expected type: JSONObject, found: JSONArray");
}
@Test
void aQuotaThatIsNotAnObjectIsRefused() {
ObjectNode props = planProps("gold", null, null);
props.put("Quota", "1000 a month");
assertCreateRefused(props, "Property [Quota] expected type: JSONObject, found: String");
}
@Test
void anApiStagesEntryThatIsNotAnObjectIsRefusedByItsIndex() {
ObjectNode props = planProps("gold", null, null, "api1:dev");
((ArrayNode) props.get("ApiStages")).add("api1:prod");
assertCreateRefused(props, "Property [1] expected type: JSONObject, found: String");
}
@Test
void aStageThrottleThatIsNotAnObjectIsRefused() {
ObjectNode props = planProps("gold", null, null);
props.putObject("Throttle").put("BurstLimit", 10).put("RateLimit", 5);
((ArrayNode) props.get("ApiStages")).addObject().put("ApiId", "api1").put("Stage", "dev")
.putArray("Throttle").addObject().put("BurstLimit", 3);
assertCreateRefused(props, "Property [Throttle] expected type: JSONObject, found: JSONArray");
}
@Test
void aMethodThrottleSettingThatIsNotAnObjectIsRefused() {
ObjectNode props = planProps("gold", null, null);
props.putObject("Throttle").put("BurstLimit", 10).put("RateLimit", 5);
((ArrayNode) props.get("ApiStages")).addObject().put("ApiId", "api1").put("Stage", "dev")
.putObject("Throttle").put("/pets/GET", 3);
assertCreateRefused(props, "Property [/pets/GET] expected type: JSONObject, found: String");
}
@Test
void anUpdateWithAThrottleThatIsNotAnObjectLeavesThePlanUntouched() {
UsagePlan existing = plan("plan-1", "gold", null, Map.of());
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
ObjectNode props = planProps("platinum", null, null);
props.put("Throttle", "fast");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(PLAN, "Plan", "plan-1"), props, ctx("plan-1")));
assertEquals("ValidationError", e.getErrorCode());
assertEquals("Property [Throttle] expected type: JSONObject, found: String", e.getMessage());
verify(apiGateway, never()).updateUsagePlan(any(), any(), anyList());
verify(apiGateway, never()).replaceUsagePlanLimits(any(), any(), any());
}
@Test
void apiStagesThatIsNotAListIsRejected() {
ObjectNode props = mapper.createObjectNode().put("UsagePlanName", "gold").put("ApiStages", "api1:dev");
@@ -363,4 +507,304 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
.when(apiGateway).deleteUsagePlanKey(REGION, "plan-1", "gone");
assertDoesNotThrow(() -> provisioner.delete(PLAN_KEY, "gone:plan-1", REGION));
}
// ──────────────────────────── Update rollback ────────────────────────────
/** plan-1 "gold" with no description, tag stack=v1 and {@link #ORIGINAL_LIMITS}. */
private static UsagePlan originalPlan() {
UsagePlan plan = plan("plan-1", "gold", null, Map.of("stack", "v1"));
plan.applyLimits(ORIGINAL_LIMITS);
return plan;
}
/** A template that changes every value of {@link #originalPlan}. */
private ObjectNode changedPlanProps() {
ObjectNode props = planProps("platinum", "new", "v2", "api1:prod");
props.putObject("Throttle").put("BurstLimit", "30").put("RateLimit", "15");
props.putObject("Quota").put("Limit", "50").put("Offset", "1").put("Period", "WEEK");
return props;
}
/**
* Stubs the plan's lookups and writes the way the in-memory store behaves: every call sees the one
* stored plan object, and a write changes that object in place.
*/
private void storeHolds(UsagePlan stored) {
when(apiGateway.getUsagePlan(REGION, stored.getId())).thenReturn(stored);
when(apiGateway.updateUsagePlan(eq(REGION), eq(stored.getId()), anyList())).thenAnswer(inv -> {
List<Map<String, String>> ops = inv.getArgument(2);
for (Map<String, String> op : ops) {
switch (op.get("path")) {
case "/name" -> stored.setName(op.get("value"));
case "/description" -> stored.setDescription(op.get("value"));
default -> throw new IllegalArgumentException(op.toString());
}
}
return stored;
});
when(apiGateway.replaceUsagePlanLimits(eq(REGION), eq(stored.getId()), any())).thenAnswer(inv -> {
stored.applyLimits(inv.getArgument(2));
return stored;
});
when(apiGateway.replaceUsagePlanTags(eq(REGION), eq(stored.getId()), anyMap())).thenAnswer(inv -> {
Map<String, String> tags = inv.getArgument(2);
stored.setTags(new HashMap<>(tags));
return stored;
});
when(apiGateway.restoreUsagePlan(eq(REGION), eq(stored.getId()), any(), any(), any(), anyMap()))
.thenAnswer(inv -> {
stored.setName(inv.getArgument(2));
stored.setDescription(inv.getArgument(3));
stored.applyLimits(inv.getArgument(4));
Map<String, String> tags = inv.getArgument(5);
stored.setTags(new HashMap<>(tags));
return stored;
});
}
private static void assertOriginal(UsagePlan plan) {
assertEquals("gold", plan.getName());
assertNull(plan.getDescription());
assertEquals(ORIGINAL_LIMITS, plan.limits());
assertEquals(Map.of("stack", "v1"), plan.getTags());
}
@Test
void anUpdateSnapshotsThePlanBeforeItChangesIt() throws Exception {
storeHolds(originalPlan());
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
JsonNode snapshot = mapper.readTree(r.getAttributes().get(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR));
assertEquals(REGION, snapshot.path("region").asText());
assertEquals("plan-1", snapshot.path("id").asText());
assertEquals("gold", snapshot.path("name").asText());
assertTrue(snapshot.path("description").isNull(), snapshot.toString());
assertEquals(ORIGINAL_LIMITS, mapper.convertValue(snapshot.path("limits"), UsagePlan.Limits.class));
assertEquals(Map.of("stack", "v1"), mapper.convertValue(snapshot.path("tags"), Map.class));
}
@Test
void aFailedStackUpdatePutsThePlanBackAsItWas() {
UsagePlan stored = originalPlan();
storeHolds(stored);
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
assertEquals("platinum", stored.getName());
clearInvocations(apiGateway);
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).restoreUsagePlan(REGION, "plan-1", "gold", null, ORIGINAL_LIMITS, Map.of("stack", "v1"));
assertOriginal(stored);
assertFalse(r.getAttributes().containsKey(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR));
}
// A patch cannot set a description back to none; the service's replace of /description writes "".
@Test
void aRollbackRemovesADescriptionThePlanDidNotHave() {
UsagePlan stored = originalPlan();
storeHolds(stored);
StackResource r = resource(PLAN, "Plan", "plan-1");
ObjectNode describedOnly = planProps("gold", "new", "v1");
describedOnly.set("ApiStages", mapper.valueToTree(List.of(Map.of("ApiId", "api1", "Stage", "dev",
"Throttle", Map.of("/pets/GET", Map.of("BurstLimit", "10", "RateLimit", "5.0"))))));
describedOnly.putObject("Throttle").put("BurstLimit", "20").put("RateLimit", "10.0");
describedOnly.putObject("Quota").put("Limit", "1000").put("Period", "MONTH");
provisioner.provision(r, describedOnly, ctx("plan-1"));
assertEquals("new", stored.getDescription());
clearInvocations(apiGateway);
assertTrue(provisioner.rollbackUpdate(r));
assertNull(stored.getDescription());
verify(apiGateway, never()).updateUsagePlan(any(), any(), anyList());
}
@Test
void aRollbackWithoutASnapshotTouchesNothing() {
assertTrue(provisioner.rollbackUpdate(resource(PLAN, "Plan", "plan-1")));
verifyNoInteractions(apiGateway);
}
@Test
void aSnapshotFromAnEarlierUpdateIsReplacedSoAnUnchangedUpdateLeavesNothingToUndo() {
UsagePlan stored = originalPlan();
storeHolds(stored);
StackResource r = resource(PLAN, "Plan", "plan-1");
// An earlier update that changed the plan and committed, then one that changes nothing.
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
clearInvocations(apiGateway);
assertTrue(provisioner.rollbackUpdate(r));
verifyNoInteractions(apiGateway);
assertEquals("platinum", stored.getName());
}
// The provisioner does not compare the plan with its snapshot first: a read outside the service's
// patch lock could mix two revisions, so it always restores, which is idempotent and runs under it.
@Test
void aRollbackRestoresThePlanEvenWhenItAlreadyMatchesItsSnapshot() {
UsagePlan stored = originalPlan();
storeHolds(stored);
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
UsagePlan original = originalPlan();
stored.setName(original.getName());
stored.setDescription(original.getDescription());
stored.applyLimits(original.limits());
stored.setTags(original.getTags());
clearInvocations(apiGateway);
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).restoreUsagePlan(REGION, "plan-1", "gold", null, ORIGINAL_LIMITS, Map.of("stack", "v1"));
assertOriginal(stored);
assertFalse(r.getAttributes().containsKey(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR));
}
@Test
void aFailedStackUpdateDeletesThePlanItCreatedInPlaceOfOneDeletedOutOfBand() {
when(apiGateway.getUsagePlan(REGION, "gone")).thenThrow(NOT_FOUND);
when(apiGateway.createUsagePlan(eq(REGION), anyMap())).thenReturn(plan("plan-2", "gold", null, Map.of()));
StackResource r = resource(PLAN, "Plan", "gone");
r.getAttributes().put("Id", "gone");
provisioner.provision(r, planProps("gold", null, null), ctx("gone"));
assertEquals("plan-2", r.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).deleteUsagePlan(REGION, "plan-2");
assertEquals("gone", r.getPhysicalId());
assertEquals("gone", r.getAttributes().get("Id"));
assertFalse(r.getAttributes().containsKey(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR));
}
@Test
void aFailedWriteDuringTheUpdatePutsTheWholePlanBack() {
UsagePlan stored = originalPlan();
storeHolds(stored);
RuntimeException failure = new IllegalStateException("store write failed");
// The limits change the stored plan and then fail to save, as a failing store write does.
doAnswer(inv -> {
stored.applyLimits(inv.getArgument(2));
throw failure;
}).when(apiGateway).replaceUsagePlanLimits(eq(REGION), eq("plan-1"), any());
StackResource r = resource(PLAN, "Plan", "plan-1");
RuntimeException thrown = assertThrows(RuntimeException.class,
() -> provisioner.provision(r, changedPlanProps(), ctx("plan-1")));
assertSame(failure, thrown);
verify(apiGateway).restoreUsagePlan(REGION, "plan-1", "gold", null, ORIGINAL_LIMITS, Map.of("stack", "v1"));
assertOriginal(stored);
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void aFailedUndoOfAFailedUpdateMarksTheRollbackFailed() {
storeHolds(originalPlan());
RuntimeException failure = new IllegalStateException("store write failed");
doThrow(failure).when(apiGateway).replaceUsagePlanTags(eq(REGION), eq("plan-1"), anyMap());
RuntimeException restoreFailure = new IllegalStateException("store write failed again");
doThrow(restoreFailure).when(apiGateway).restoreUsagePlan(eq(REGION), eq("plan-1"), any(), any(), any(),
anyMap());
StackResource r = resource(PLAN, "Plan", "plan-1");
RuntimeException thrown = assertThrows(RuntimeException.class,
() -> provisioner.provision(r, changedPlanProps(), ctx("plan-1")));
assertSame(failure, thrown);
assertTrue(List.of(thrown.getSuppressed()).contains(restoreFailure));
String reason = r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
assertTrue(reason != null && reason.contains("plan-1") && reason.contains("store write failed again"),
String.valueOf(reason));
}
@Test
void aRestoreRethrowingTheUpdateFailureIsNotSuppressedInItself() {
storeHolds(originalPlan());
RuntimeException failure = new IllegalStateException("store write failed");
// The update and its restore both fail to save the plan with the same exception object.
doThrow(failure).when(apiGateway).replaceUsagePlanTags(eq(REGION), eq("plan-1"), anyMap());
doThrow(failure).when(apiGateway).restoreUsagePlan(eq(REGION), eq("plan-1"), any(), any(), any(), anyMap());
StackResource r = resource(PLAN, "Plan", "plan-1");
RuntimeException thrown = assertThrows(RuntimeException.class,
() -> provisioner.provision(r, changedPlanProps(), ctx("plan-1")));
assertSame(failure, thrown);
assertEquals(0, thrown.getSuppressed().length);
assertTrue(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
// The snapshot is the plan read under the service's patch lock before the first write, not the
// provisioner's earlier lookup: here a patch renamed the plan between the two, and the rollback
// puts back the revision the locked read saw.
@Test
void theSnapshotIsTheRevisionReadUnderThePatchLockBeforeTheFirstWrite() {
UsagePlan stored = originalPlan();
storeHolds(stored);
UsagePlan patched = originalPlan();
patched.setName("renamed-by-a-patch");
doAnswer(inv -> {
Function<UsagePlan, Object> reader = inv.getArgument(2);
return reader.apply(patched);
}).when(apiGateway).readUsagePlan(eq(REGION), eq("plan-1"), any());
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
InOrder order = inOrder(apiGateway);
order.verify(apiGateway).readUsagePlan(eq(REGION), eq("plan-1"), any());
order.verify(apiGateway).updateUsagePlan(eq(REGION), eq("plan-1"), anyList());
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("renamed-by-a-patch", stored.getName());
}
// An attempt that failed after its snapshot may have changed the plan, so the engine keeps it for
// rollbackUpdate; one without a snapshot changed nothing and the engine puts the previous resource back.
@Test
void aFailedUpdateIsKeptForItsRollbackOnlyWhileItHasASnapshot() {
storeHolds(originalPlan());
StackResource r = resource(PLAN, "Plan", "plan-1");
assertFalse(provisioner.retainsFailedUpdateState(r));
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
assertTrue(provisioner.retainsFailedUpdateState(r));
assertTrue(provisioner.rollbackUpdate(r));
assertFalse(provisioner.retainsFailedUpdateState(r));
}
@Test
void aCommittedUpdateDropsItsSnapshot() {
storeHolds(originalPlan());
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
UpdateCleanupResult result = provisioner.completeUpdate(r);
assertFalse(result.applicable());
assertFalse(r.getAttributes().containsKey(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR));
assertFalse(provisioner.retainsFailedUpdateState(r));
}
@Test
void aRollbackOfAPlanDeletedSinceTheUpdateFails() {
storeHolds(originalPlan());
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, changedPlanProps(), ctx("plan-1"));
doThrow(NOT_FOUND).when(apiGateway).getUsagePlan(REGION, "plan-1");
doThrow(NOT_FOUND).when(apiGateway).restoreUsagePlan(eq(REGION), eq("plan-1"), any(), any(), any(),
anyMap());
AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals("NotFoundException", e.getErrorCode());
assertTrue(r.getAttributes().containsKey(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR));
}
}