fix(cloudformation): apply TimeToLiveSpecification on DynamoDB tables (#4951)

* feat(dynamodb): add typed time-to-live operations to the table access

DynamoDbTableAccess gains timeToLive and updateTimeToLive next to the
stream operations. The native engine reads the TTL flag and attribute
from the table definition and calls DynamoDbService.updateTimeToLive
under the scope's account; the Local engine sends DescribeTimeToLive
and UpdateTimeToLive.

* fix(cloudformation): apply TimeToLiveSpecification on DynamoDB tables

An AWS::DynamoDB::Table declaring TimeToLiveSpecification reached
CREATE_COMPLETE while DescribeTimeToLive answered DISABLED, because the
provisioner never read the property.

The provisioner now reconciles TTL against what the table reports, so
UpdateTimeToLive is called only when the setting differs: enabled turns
it on, Enabled false or a block removed on an update turns it off with
the current attribute name, and renaming an enabled attribute fails with
the DynamoDB ValidationException before anything changes. Enabled with
no AttributeName fails with ValidationError before the table is created.

An in-place table update now records the tags, stream and TTL setting
it replaces, and rollbackUpdate puts all three back, so a stack whose
update fails on a later resource ends UPDATE_ROLLBACK_COMPLETE instead
of UPDATE_ROLLBACK_FAILED. A restore that throws keeps the snapshot.

* fix(cloudformation): roll back and clean up failed DynamoDB table provisions

A table's in-place update that failed after its snapshot, for example on
UpdateTimeToLive after the tags and the stream had changed, lost the
snapshot: the engine put the previous resource back and reported
UPDATE_ROLLBACK_COMPLETE with the changes still live. The provisioner
now retains a failed attempt that carries its snapshot, so the engine
hands it to rollbackUpdate. A failure before the snapshot changed
nothing and still uses the engine's restore.

A provision that failed after createTable left the new table behind,
on create and on a replacing update alike. The provisioner now deletes
a table this attempt created, tolerating ResourceNotFoundException, and
never one it adopted or updates in place. A delete that fails is logged
and leaves the physical id and the rollback ownership marker, so the
stack's create rollback retries it. A table recreated because the
update target was gone takes no snapshot, since it has no prior state.

* fix(cloudformation): match the AWS status reasons for invalid TimeToLiveSpecification

Renaming an enabled TTL attribute and enabling TTL without an
AttributeName now fail with the handler message AWS CloudFormation
reports, as measured in eu-west-1, and with its InvalidRequest handler
error code. The resource status reason is the AWS inner text exactly;
the type and logical id prefix are gone, since AWS does not include them.

* fix(cloudformation): scope DynamoDB table TTL to the stack and validate Enabled

- An update leaves TTL alone when neither the template nor the previous
  one declared TimeToLiveSpecification, so TTL enabled outside the stack
  survives, as on AWS.
- A TimeToLiveSpecification without Enabled, or with a non-Boolean one,
  fails model validation before the table is created.
- A replacing update whose created table cannot be deleted reports a
  rollback failure naming the table instead of leaving it untracked.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-14 15:57:36 -04:00
1 parent 6e8a083d2b
commit a5228a0bf7
13 files changed
+1161 -43

No files matched your search

@@ -0,0 +1,341 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
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 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.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
/**
* {@code TimeToLiveSpecification} on {@code AWS::DynamoDB::Table}: the setting a stack declares is
* what DescribeTimeToLive reports after create, after an update that disables it and after an
* update that removes the block, and a failed update puts the previous setting back. A failure
* inside the table's own provision is injected through a spy on the DynamoDB service.
*/
@QuarkusTest
class CloudFormationDynamoDbTimeToLiveIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String DDB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/dynamodb/aws4_request";
private static final String TEMPLATE = """
{
"Resources": {
"Orders": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"BillingMode": "PAY_PER_REQUEST",
"Tags": [{"Key": "env", "Value": "%s"}]%s
}
}%s
}
}
""";
private static final String TTL_ENABLED =
",\n\"TimeToLiveSpecification\": {\"AttributeName\": \"expiresAt\", \"Enabled\": true}";
private static final String TTL_DISABLED =
",\n\"TimeToLiveSpecification\": {\"AttributeName\": \"expiresAt\", \"Enabled\": false}";
private static final String TTL_RENAMED =
",\n\"TimeToLiveSpecification\": {\"AttributeName\": \"deleteAfter\", \"Enabled\": true}";
private static final String TTL_WITHOUT_ATTRIBUTE =
",\n\"TimeToLiveSpecification\": {\"Enabled\": true}";
private static final String TTL_WITHOUT_ENABLED =
",\n\"TimeToLiveSpecification\": {\"AttributeName\": \"expiresAt\"}";
private static final String STREAMED =
",\n\"StreamSpecification\": {\"StreamViewType\": \"NEW_AND_OLD_IMAGES\"}";
/** A resource that fails after the table, so the update that changed the table rolls back. */
private static final String FAILING_RESOURCE = """
,
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"DependsOn": "Orders",
"Properties": {
"Name": "ttl-rollback-%s",
"SecretString": "explicit",
"GenerateSecretString": {"PasswordLength": 32}
}
}""";
@InjectSpy
DynamoDbService dynamoDbService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createEnablesTheDeclaredTimeToLiveAndEnabledFalseDisablesIt() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-" + suffix;
String table = "ttl-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", TTL_ENABLED, ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeTimeToLive(table)
.body("TimeToLiveDescription.TimeToLiveStatus", equalTo("ENABLED"))
.body("TimeToLiveDescription.AttributeName", equalTo("expiresAt"));
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(table, "dev", TTL_DISABLED, ""));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeTimeToLive(table)
.body("TimeToLiveDescription.TimeToLiveStatus", equalTo("DISABLED"))
.body("TimeToLiveDescription.AttributeName", nullValue());
deleteStack(stack);
}
@Test
void removingTheTimeToLiveBlockDisablesIt() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-rm-" + suffix;
String table = "ttl-rm-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", TTL_ENABLED, ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeTimeToLive(table).body("TimeToLiveDescription.TimeToLiveStatus", equalTo("ENABLED"));
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(table, "dev", "", ""));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeTimeToLive(table).body("TimeToLiveDescription.TimeToLiveStatus", equalTo("DISABLED"));
deleteStack(stack);
}
@Test
void anUpdateThatFailsOnALaterResourcePutsTheTableBack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-rb-" + suffix;
String table = "ttl-rb-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", TTL_ENABLED, ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
String tableArn = dynamoDb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.extract().path("Table.TableArn");
cloudFormation(stack, "UpdateStack",
TEMPLATE.formatted(table, "prod", TTL_DISABLED, FAILING_RESOURCE.formatted(suffix)));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeTimeToLive(table)
.body("TimeToLiveDescription.TimeToLiveStatus", equalTo("ENABLED"))
.body("TimeToLiveDescription.AttributeName", equalTo("expiresAt"));
dynamoDb("ListTagsOfResource", "{\"ResourceArn\": \"" + tableArn + "\"}")
.statusCode(200)
.body("Tags.Value", contains("dev"));
deleteStack(stack);
}
/**
* The table's own update changes the tags and switches the stream off, then its TTL call fails.
* The rollback must put the tags and the stream back, not just report that it did.
*/
@Test
void anUpdateThatFailsInsideTheTablePutsItsTagsAndStreamBack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-own-" + suffix;
String table = "ttl-own-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", STREAMED, ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
String tableArn = dynamoDb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.extract().path("Table.TableArn");
failNextUpdateTimeToLive();
try {
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(table, "prod", TTL_ENABLED, ""));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
} finally {
Mockito.doCallRealMethod().when(dynamoDbService)
.updateTimeToLive(anyString(), anyString(), anyBoolean(), anyString());
}
dynamoDb("ListTagsOfResource", "{\"ResourceArn\": \"" + tableArn + "\"}")
.statusCode(200)
.body("Tags.Value", contains("dev"));
dynamoDb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.body("Table.StreamSpecification.StreamEnabled", equalTo(true))
.body("Table.StreamSpecification.StreamViewType", equalTo("NEW_AND_OLD_IMAGES"));
describeTimeToLive(table).body("TimeToLiveDescription.TimeToLiveStatus", equalTo("DISABLED"));
deleteStack(stack);
}
/** A create that fails after the table exists rolls back to no table, not to an orphan. */
@Test
void aCreateThatFailsAfterTheTableExistsLeavesNoTable() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-orphan-" + suffix;
String table = "ttl-orphan-table-" + suffix;
failNextUpdateTimeToLive();
try {
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", TTL_ENABLED, ""));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
} finally {
Mockito.doCallRealMethod().when(dynamoDbService)
.updateTimeToLive(anyString(), anyString(), anyBoolean(), anyString());
}
dynamoDb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
deleteStack(stack);
}
/** As measured on AWS: the rename fails the table before any DynamoDB change and the update rolls back. */
@Test
void renamingAnEnabledAttributeFailsWithTheAwsReasonAndRollsBack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-rename-" + suffix;
String table = "ttl-rename-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", TTL_ENABLED, ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(table, "dev", TTL_RENAMED, ""));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeStackEvents(stack).body(containsString("<ResourceStatusReason>Invalid request provided: Cannot change"
+ " time-to-live attribute name. To update this property, you must first disable TTL then enable"
+ " TTL with the new attribute name.</ResourceStatusReason>"));
describeTimeToLive(table)
.body("TimeToLiveDescription.TimeToLiveStatus", equalTo("ENABLED"))
.body("TimeToLiveDescription.AttributeName", equalTo("expiresAt"));
deleteStack(stack);
}
/** As measured on AWS: the create fails with the reason below and leaves no table. */
@Test
void enablingWithoutAnAttributeNameFailsTheCreateWithTheAwsReason() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-noattr-" + suffix;
String table = "ttl-noattr-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", TTL_WITHOUT_ATTRIBUTE, ""));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeStackEvents(stack).body(containsString("<ResourceStatusReason>Invalid request provided: AttributeName"
+ " property of TimeToLiveSpecification is required when TTL status is enabled or when enabling"
+ " TTL.</ResourceStatusReason>"));
dynamoDb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
deleteStack(stack);
}
/** As measured on AWS: an update leaves alone TTL enabled outside a stack that never declared it. */
@Test
void timeToLiveSetOutsideAStackThatNeverDeclaredItSurvivesATagOnlyUpdate() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-oob-" + suffix;
String table = "ttl-oob-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", "", ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
dynamoDb("UpdateTimeToLive", "{\"TableName\": \"" + table + "\", \"TimeToLiveSpecification\":"
+ " {\"AttributeName\": \"expiresAt\", \"Enabled\": true}}").statusCode(200);
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(table, "prod", "", ""));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeTimeToLive(table)
.body("TimeToLiveDescription.TimeToLiveStatus", equalTo("ENABLED"))
.body("TimeToLiveDescription.AttributeName", equalTo("expiresAt"));
deleteStack(stack);
}
/** The registry schema requires Enabled, so the block is rejected before a table exists. */
@Test
void aTimeToLiveBlockWithoutEnabledFailsTheCreateAndLeavesNoTable() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-ttl-noen-" + suffix;
String table = "ttl-noen-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(table, "dev", TTL_WITHOUT_ENABLED, ""));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
describeStackEvents(stack).body(containsString("<ResourceStatusReason>Model validation failed"
+ " (#/TimeToLiveSpecification: required key [Enabled] not found)</ResourceStatusReason>"));
dynamoDb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
deleteStack(stack);
}
private ValidatableResponse describeStackEvents(String stack) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200);
}
private void failNextUpdateTimeToLive() {
Mockito.doThrow(new IllegalStateException("simulated UpdateTimeToLive failure"))
.doCallRealMethod()
.when(dynamoDbService)
.updateTimeToLive(anyString(), anyString(), anyBoolean(), anyString());
}
private void cloudFormation(String stack, String action, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack)
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
}
private void deleteStack(String stack) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
}
private ValidatableResponse describeTimeToLive(String table) {
return dynamoDb("DescribeTimeToLive", "{\"TableName\": \"" + table + "\"}").statusCode(200);
}
private ValidatableResponse dynamoDb(String action, String body) {
return given()
.contentType("application/x-amz-json-1.0")
.header("Authorization", DDB_AUTH)
.header("X-Amz-Target", "DynamoDB_20120810." + action)
.body(body)
.when().post("/").then();
}
}
@@ -19,11 +19,15 @@ import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.anyBoolean;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -33,7 +37,9 @@ import static org.mockito.Mockito.when;
/**
* The DynamoDB CFN provisioner in isolation: the exact {@code Fn::GetAtt} keys the registry
* schema declares, and the delete contract for each of its three types. The stream and replica
* schema declares, the delete contract for each of its three types, the
* {@code TimeToLiveSpecification} reconcile, and the snapshot a failed table update rolls back
* from. The stream and replica
* behaviour keeps its own coverage in {@code DynamoDbStreamSpecificationCfnProvisionerTest} and
* {@code DynamoDbReplicaCfnProvisionerTest}, which reach this class through the fixture.
*/
@@ -43,6 +49,8 @@ class DynamoDbCfnProvisionerTest {
private static final String TABLE_ARN = "arn:aws:dynamodb:us-east-1:000000000000:table/" + TABLE_NAME;
private static final String TABLE_ID = "2d4c5c3a-1b6e-4a1d-9f0a-7b1c2d3e4f50";
private static final String STREAM_ARN = TABLE_ARN + "/stream/2026-01-01T00:00:00.000";
private static final String TTL_PROPS = "{\"TableName\":\"orders\",\"TimeToLiveSpecification\":"
+ "{\"AttributeName\":\"expiresAt\",\"Enabled\":true}}";
private final DynamoDbService dynamoDb = mock(DynamoDbService.class);
private final ObjectMapper mapper = new ObjectMapper();
@@ -67,6 +75,13 @@ class DynamoDbCfnProvisionerTest {
create.stackName(), priorPhysicalId);
}
/** The update path, with the properties the previous template declared. */
private ProvisionContext updateCtx(String priorPhysicalId, String priorProperties) throws Exception {
ProvisionContext create = ctx();
return new ProvisionContext(create.engine(), create.region(), create.accountId(),
create.stackName(), priorPhysicalId, event -> { }, props(priorProperties));
}
private StackResource resource(String type, String logicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
@@ -310,7 +325,7 @@ class DynamoDbCfnProvisionerTest {
assertEquals(priorName, r.getPhysicalId());
verify(dynamoDb).createTable(eq(priorName), anyList(), anyList(), any(), any(), anyList(), anyList(),
eq("us-east-1"));
verify(dynamoDb).describeTable(priorName, "us-east-1");
verify(dynamoDb, atLeastOnce()).describeTable(priorName, "us-east-1");
}
@Test
@@ -326,4 +341,393 @@ class DynamoDbCfnProvisionerTest {
verify(dynamoDb).untagResource(TABLE_ARN, List.of("old"), "us-east-1");
verify(dynamoDb).tagResource(TABLE_ARN, Map.of("env", "prod"), "us-east-1");
}
private TableDefinition withTimeToLive(TableDefinition table, String attributeName) {
table.setTtlEnabled(true);
table.setTtlAttributeName(attributeName);
return table;
}
/** The update path: the table already exists and reports {@code current}. */
private void existingTable(TableDefinition current) {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenThrow(new AwsException("ResourceInUseException", "Table already exists", 400));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(current);
}
@Test
void createWithTimeToLiveEnablesItOnce() throws Exception {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenReturn(table(false));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(table(false));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
provisioner.provision(r, props("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":"
+ "{\"AttributeName\":\"expiresAt\",\"Enabled\":true}}"), ctx());
verify(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", true, "us-east-1");
}
@Test
void enabledGivenAsAStringIsResolvedThroughTheEngine() throws Exception {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenReturn(table(false));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(table(false));
ProvisionContext ctx = ctx();
when(ctx.engine().resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
if (node != null && node.has("Ref")) {
return "true";
}
return node == null ? null : node.asText();
});
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
provisioner.provision(r, props("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":"
+ "{\"AttributeName\":\"expiresAt\",\"Enabled\":{\"Ref\":\"TtlOn\"}}}"), ctx);
verify(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", true, "us-east-1");
}
@Test
void updateWithTheSameTimeToLiveMakesNoTimeToLiveCall() throws Exception {
existingTable(withTimeToLive(table(false), "expiresAt"));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
provisioner.provision(r, props("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":"
+ "{\"AttributeName\":\"expiresAt\",\"Enabled\":true}}"), updateCtx(TABLE_NAME));
verify(dynamoDb, never()).updateTimeToLive(anyString(), any(), anyBoolean(), anyString());
}
@Test
void updateWithEnabledFalseDisablesTheCurrentAttribute() throws Exception {
existingTable(withTimeToLive(table(false), "expiresAt"));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
provisioner.provision(r, props("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":{\"Enabled\":false}}"),
updateCtx(TABLE_NAME));
verify(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", false, "us-east-1");
}
@Test
void updateThatRemovesTheTimeToLiveBlockDisablesIt() throws Exception {
existingTable(withTimeToLive(table(false), "expiresAt"));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
provisioner.provision(r, props("{\"TableName\":\"orders\"}"), updateCtx(TABLE_NAME, TTL_PROPS));
verify(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", false, "us-east-1");
}
/** As measured on AWS: TTL enabled outside a stack that never declared it survives a tag-only update. */
@Test
void updateOfAStackThatNeverDeclaredTimeToLiveLeavesItAlone() throws Exception {
existingTable(withTimeToLive(table(false), "expiresAt"));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
provisioner.provision(r, props("{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}]}"),
updateCtx(TABLE_NAME, "{\"TableName\":\"orders\"}"));
verify(dynamoDb, never()).updateTimeToLive(anyString(), any(), anyBoolean(), anyString());
}
@Test
void timeToLiveWithoutEnabledFailsModelValidationBeforeTheTableIsCreated() throws Exception {
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
JsonNode props = props("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":{\"AttributeName\":\"exp\"}}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("Model validation failed (#/TimeToLiveSpecification: required key [Enabled] not found)",
e.getMessage());
verifyNoInteractions(dynamoDb);
}
@Test
void timeToLiveWithANonBooleanEnabledFailsModelValidationBeforeTheTableIsCreated() throws Exception {
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
JsonNode props = props("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":"
+ "{\"AttributeName\":\"exp\",\"Enabled\":\"tru\"}}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("Model validation failed (#/TimeToLiveSpecification/Enabled: expected type: Boolean,"
+ " found: String)", e.getMessage());
verifyNoInteractions(dynamoDb);
}
/** CloudFormation renames a TTL attribute by disabling it in one update and enabling the new one in a later one. */
@Test
void updateThatRenamesAnEnabledTimeToLiveAttributeFailsBeforeChangingAnything() throws Exception {
existingTable(withTimeToLive(table(false), "expiresAt"));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
// Left by an earlier successful update; it must not make the engine skip its own restore.
r.getAttributes().put(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR, "{}");
JsonNode props = props("{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}],"
+ "\"TimeToLiveSpecification\":{\"AttributeName\":\"deleteAfter\",\"Enabled\":true}}");
ProvisionContext ctx = updateCtx(TABLE_NAME);
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("Invalid request provided: Cannot change time-to-live attribute name. To update this property,"
+ " you must first disable TTL then enable TTL with the new attribute name.", e.getMessage());
assertEquals(400, e.getHttpStatus());
verify(dynamoDb, never()).updateTimeToLive(anyString(), any(), anyBoolean(), anyString());
verify(dynamoDb, never()).tagResource(anyString(), any(), anyString());
assertFalse(provisioner.retainsFailedUpdateState(r));
verify(dynamoDb, never()).deleteTable(anyString(), anyString());
}
/**
* The table's own update fails after it changed the tags and the stream. The engine must keep
* this attempt, snapshot included, and hand it to rollbackUpdate rather than put the previous
* resource back and report a rollback that never happened.
*/
@Test
void inPlaceUpdateThatFailsAfterItsSnapshotIsRetainedAndRolledBack() throws Exception {
existingTable(table(true));
when(dynamoDb.listTagsOfResource(TABLE_ARN, "us-east-1")).thenReturn(Map.of("env", "dev"));
when(dynamoDb.disableStream(TABLE_NAME, "us-east-1")).thenReturn(table(false));
doThrow(new AwsException("InternalServerError", "boom", 500))
.when(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", true, "us-east-1");
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
r.getAttributes().put("Arn", TABLE_ARN);
r.getAttributes().put("StreamArn", STREAM_ARN);
JsonNode props = props("{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}],"
+ "\"TimeToLiveSpecification\":{\"AttributeName\":\"expiresAt\",\"Enabled\":true}}");
ProvisionContext ctx = updateCtx(TABLE_NAME);
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertTrue(provisioner.retainsFailedUpdateState(r));
assertEquals(TABLE_NAME, r.getPhysicalId());
assertEquals(TABLE_ARN, r.getAttributes().get("Arn"));
verify(dynamoDb, never()).deleteTable(anyString(), anyString());
when(dynamoDb.listTagsOfResource(TABLE_ARN, "us-east-1")).thenReturn(Map.of("env", "prod"));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(table(false));
when(dynamoDb.enableStream(TABLE_NAME, "NEW_AND_OLD_IMAGES", "us-east-1")).thenReturn(table(true));
assertTrue(provisioner.rollbackUpdate(r));
verify(dynamoDb).tagResource(TABLE_ARN, Map.of("env", "dev"), "us-east-1");
verify(dynamoDb).enableStream(TABLE_NAME, "NEW_AND_OLD_IMAGES", "us-east-1");
verify(dynamoDb, never()).updateTimeToLive(TABLE_NAME, "expiresAt", false, "us-east-1");
assertFalse(provisioner.retainsFailedUpdateState(r));
}
private void createdTableWhoseTimeToLiveCallFails() {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenReturn(table(false));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(table(false));
doThrow(new AwsException("LimitExceededException", "boom", 400))
.when(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", true, "us-east-1");
}
@Test
void createThatFailsAfterCreatingTheTableDeletesIt() throws Exception {
createdTableWhoseTimeToLiveCallFails();
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
JsonNode props = props(TTL_PROPS);
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("LimitExceededException", e.getErrorCode());
verify(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void replacingUpdateThatFailsDeletesTheNewTableAndLeavesTheOldOne() throws Exception {
createdTableWhoseTimeToLiveCallFails();
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId("orders-v1");
JsonNode props = props(TTL_PROPS);
ProvisionContext ctx = updateCtx("orders-v1");
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
verify(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");
verify(dynamoDb, never()).deleteTable("orders-v1", "us-east-1");
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
/** A table this attempt did not create, the update target or one adopted on create, is never deleted. */
@Test
void failureOnATableThisAttemptDidNotCreateDeletesNothing() throws Exception {
existingTable(table(false));
doThrow(new AwsException("LimitExceededException", "boom", 400))
.when(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", true, "us-east-1");
JsonNode props = props(TTL_PROPS);
for (ProvisionContext ctx : List.of(updateCtx(TABLE_NAME), ctx())) {
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(ctx.priorPhysicalId());
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
verify(dynamoDb, never()).deleteTable(anyString(), anyString());
}
/** A cleanup that fails leaves the table to the engine's create rollback, which retries the delete. */
@Test
void createWhoseCleanupFailsLeavesTheTableOwnedForTheStackRollback() throws Exception {
createdTableWhoseTimeToLiveCallFails();
doThrow(new AwsException("InternalServerError", "delete failed", 500))
.when(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
JsonNode props = props(TTL_PROPS);
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("LimitExceededException", e.getErrorCode());
assertEquals(TABLE_NAME, r.getPhysicalId());
assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
}
/**
* The engine puts the previous resource back after a failed update and never learns the new
* table, so a cleanup that fails there is reported as a rollback failure naming it.
*/
@Test
void replacingUpdateWhoseCleanupFailsReportsTheTableAsARollbackFailure() throws Exception {
createdTableWhoseTimeToLiveCallFails();
doThrow(new AwsException("InternalServerError", "delete failed", 500))
.when(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId("orders-v1");
JsonNode props = props(TTL_PROPS);
ProvisionContext ctx = updateCtx("orders-v1");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("LimitExceededException", e.getErrorCode());
assertEquals(1, e.getSuppressed().length);
String reason = r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
assertTrue(reason != null && reason.contains(TABLE_NAME) && reason.contains("delete failed"), reason);
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
/**
* The update target was deleted outside the stack, so this attempt created it again. That table
* is this attempt's to delete, and there is no prior state to snapshot for a rollback.
*/
@Test
void updateThatRecreatesAMissingTableAndFailsDeletesItAndKeepsNoSnapshot() throws Exception {
createdTableWhoseTimeToLiveCallFails();
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
JsonNode props = props(TTL_PROPS);
ProvisionContext ctx = updateCtx(TABLE_NAME);
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
verify(dynamoDb).deleteTable(TABLE_NAME, "us-east-1");
assertFalse(provisioner.retainsFailedUpdateState(r));
}
@Test
void successfulCreateLeavesNoOwnershipMarker() throws Exception {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenReturn(table(false));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(table(false));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
provisioner.provision(r, props(TTL_PROPS), ctx());
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
verify(dynamoDb, never()).deleteTable(anyString(), anyString());
}
@Test
void enabledTimeToLiveWithoutAnAttributeNameFailsBeforeTheTableIsCreated() throws Exception {
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
JsonNode props = props("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":{\"Enabled\":true}}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("Invalid request provided: AttributeName property of TimeToLiveSpecification is required"
+ " when TTL status is enabled or when enabling TTL.", e.getMessage());
assertEquals(400, e.getHttpStatus());
verifyNoInteractions(dynamoDb);
}
@Test
void rollbackUpdateRestoresTagsStreamAndTimeToLive() throws Exception {
existingTable(table(true));
when(dynamoDb.listTagsOfResource(TABLE_ARN, "us-east-1")).thenReturn(Map.of("env", "dev"));
when(dynamoDb.disableStream(TABLE_NAME, "us-east-1")).thenReturn(table(false));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
r.getAttributes().put("StreamArn", STREAM_ARN);
provisioner.provision(r, props("{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}],"
+ "\"TimeToLiveSpecification\":{\"AttributeName\":\"expiresAt\",\"Enabled\":true}}"),
updateCtx(TABLE_NAME));
// The table as the update left it: retagged, streamless and expiring.
when(dynamoDb.listTagsOfResource(TABLE_ARN, "us-east-1")).thenReturn(Map.of("env", "prod"));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(withTimeToLive(table(false), "expiresAt"));
when(dynamoDb.enableStream(TABLE_NAME, "NEW_AND_OLD_IMAGES", "us-east-1")).thenReturn(table(true));
boolean rolledBack = provisioner.rollbackUpdate(r);
assertTrue(rolledBack);
verify(dynamoDb).tagResource(TABLE_ARN, Map.of("env", "dev"), "us-east-1");
verify(dynamoDb).enableStream(TABLE_NAME, "NEW_AND_OLD_IMAGES", "us-east-1");
verify(dynamoDb).updateTimeToLive(TABLE_NAME, "expiresAt", false, "us-east-1");
assertEquals(STREAM_ARN, r.getAttributes().get("StreamArn"));
assertFalse(r.getAttributes().containsKey(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR));
}
@Test
void rollbackUpdateThatFailsKeepsTheSnapshotForTheNextAttempt() throws Exception {
existingTable(table(false));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId(TABLE_NAME);
provisioner.provision(r, props("{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}]}"),
updateCtx(TABLE_NAME));
when(dynamoDb.listTagsOfResource(TABLE_ARN, "us-east-1")).thenReturn(Map.of("env", "prod"));
doThrow(new AwsException("InternalServerError", "boom", 500))
.when(dynamoDb).untagResource(TABLE_ARN, List.of("env"), "us-east-1");
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertTrue(r.getAttributes().containsKey(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR));
}
/**
* A snapshot describes the update in flight. One left by an earlier update is dropped, so a
* replacing update, which takes none, cannot roll the new table back to the old one's state.
*/
@Test
void replacingUpdateDropsAStaleSnapshotAndReportsNoRollback() throws Exception {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenReturn(table(false));
when(dynamoDb.describeTable(TABLE_NAME, "us-east-1")).thenReturn(table(false));
StackResource r = resource("AWS::DynamoDB::Table", "Orders");
r.setPhysicalId("orders-v1");
r.getAttributes().put(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR, "{}");
provisioner.provision(r, props("{\"TableName\":\"orders\"}"), updateCtx("orders-v1"));
assertFalse(r.getAttributes().containsKey(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR));
assertFalse(provisioner.rollbackUpdate(r));
}
}
@@ -14,6 +14,7 @@ import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
@@ -32,6 +33,7 @@ import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
@@ -58,8 +60,12 @@ class DynamoDbLocalBackendIntegrationTest {
private record Caller(String account, String region) {
String authorization() {
return authorization("dynamodb");
}
String authorization(String service) {
return "AWS4-HMAC-SHA256 Credential=" + account + "/20260215/" + region
+ "/dynamodb/aws4_request, SignedHeaders=host, Signature=abc";
+ "/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -252,6 +258,39 @@ class DynamoDbLocalBackendIntegrationTest {
.body("__type", endsWith("ResourceNotFoundException"));
}
@Test
void theTimeToLiveAStackEnablesIsWhatLocalReports() {
String table = tableName("ttl");
String stack = "local-it-ttl-" + UUID.randomUUID();
String template = """
{
"Resources": {
"Orders": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": "PAY_PER_REQUEST",
"TimeToLiveSpecification": {"AttributeName": "expiresAt", "Enabled": true}
}
}
}
}
""".formatted(table);
cloudFormation(A_EAST, "CreateStack", stack, template);
// The stack stays in Floci; its table is removed from Local with the others.
created.add(new CreatedTable(A_EAST, table));
cloudFormation(A_EAST, "DescribeStacks", stack, null)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
dynamoDb(A_EAST, "DescribeTimeToLive", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.body("TimeToLiveDescription.TimeToLiveStatus", equalTo("ENABLED"))
.body("TimeToLiveDescription.AttributeName", equalTo("expiresAt"));
}
@Test
void resetIsRefused() {
given().when().post("/_floci/state/reset").then().statusCode(409);
@@ -296,6 +335,18 @@ class DynamoDbLocalBackendIntegrationTest {
return dynamoDb(caller, "Scan", "{\"TableName\": \"" + table + "\"}").statusCode(200);
}
private static ValidatableResponse cloudFormation(Caller caller, String action, String stack, String template) {
RequestSpecification request = given()
.header("Authorization", caller.authorization("cloudformation"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("StackName", stack);
if (template != null) {
request.formParam("TemplateBody", template);
}
return request.when().post("/").then().statusCode(200);
}
private static ValidatableResponse dynamoDb(Caller caller, String action, String body) {
return send(caller, "DynamoDB_20120810." + action, body);
}
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.A
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Call;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbTableAccess.TimeToLive;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
@@ -629,6 +630,35 @@ class DynamoDbLocalBackendTest {
neverSent("UpdateTable");
}
@Test
void timeToLiveReadsDescribeTimeToLive() throws Exception {
answer("DescribeTimeToLive", 200, "{\"TimeToLiveDescription\":"
+ "{\"TimeToLiveStatus\":\"ENABLED\",\"AttributeName\":\"expiresAt\"}}");
TimeToLive ttl = backend.timeToLive(SCOPE, "orders");
assertEquals(new TimeToLive(true, "expiresAt"), ttl);
assertEquals(json("{\"TableName\":\"orders\"}"), sent("DescribeTimeToLive"));
}
@Test
void timeToLiveDisabledIsOff() throws Exception {
answer("DescribeTimeToLive", 200, "{\"TimeToLiveDescription\":{\"TimeToLiveStatus\":\"DISABLED\"}}");
assertEquals(new TimeToLive(false, null), backend.timeToLive(SCOPE, "orders"));
}
@Test
void updateTimeToLiveSendsTheSpecification() throws Exception {
answer("UpdateTimeToLive", 200, "{\"TimeToLiveSpecification\":"
+ "{\"AttributeName\":\"expiresAt\",\"Enabled\":false}}");
backend.updateTimeToLive(SCOPE, "orders", "expiresAt", false);
assertEquals(json("{\"TableName\":\"orders\",\"TimeToLiveSpecification\":"
+ "{\"AttributeName\":\"expiresAt\",\"Enabled\":false}}"), sent("UpdateTimeToLive"));
}
@Test
void updateItemReturnsOnlyImages() throws Exception {
answer("UpdateItem", 200, "{\"Attributes\":{\"pk\":{\"S\":\"a\"},\"n\":{\"N\":\"2\"}}}");
@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.A
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Call;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbTableAccess.TimeToLive;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
@@ -179,6 +180,29 @@ class DynamoDbNativeBackendTest {
assertEquals(json("{\"id\":{\"S\":\"k\"},\"n\":{\"N\":\"5\"}}"), backend.getItem(SCOPE, TABLE, key));
}
@Test
void typedTimeToLiveIsWhatDescribeTimeToLiveReportsUnderTheScopesAccount() throws Exception {
Scope owner = new Scope("111122223333", REGION);
backend.createTable(owner, TABLE, List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")), 5L, 5L, List.of(), List.of());
JsonNode describe = json("{\"TableName\":\"" + TABLE + "\"}");
assertEquals(new TimeToLive(false, null), backend.timeToLive(owner, TABLE));
backend.updateTimeToLive(owner, TABLE, "expiresAt", true);
assertEquals(new TimeToLive(true, "expiresAt"), backend.timeToLive(owner, TABLE));
JsonNode enabled = backend.execute(new Call(owner, Api.DYNAMODB, "DescribeTimeToLive", describe)).body();
assertEquals("ENABLED", enabled.path("TimeToLiveDescription").path("TimeToLiveStatus").asText());
assertEquals("expiresAt", enabled.path("TimeToLiveDescription").path("AttributeName").asText());
backend.updateTimeToLive(owner, TABLE, "expiresAt", false);
assertEquals(new TimeToLive(false, null), backend.timeToLive(owner, TABLE));
JsonNode disabled = backend.execute(new Call(owner, Api.DYNAMODB, "DescribeTimeToLive", describe)).body();
assertEquals("DISABLED", disabled.path("TimeToLiveDescription").path("TimeToLiveStatus").asText());
}
@Test
void unknownActionRepliesWithAJsonErrorBody() throws Exception {
Reply reply = call(Api.DYNAMODB, "NoSuchAction", mapper.createObjectNode());
@@ -116,6 +116,17 @@ public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, Dynam
return record("disableStream", scope);
}
@Override
public TimeToLive timeToLive(Scope scope, String tableName) {
record("timeToLive", scope);
return new TimeToLive(false, null);
}
@Override
public void updateTimeToLive(Scope scope, String tableName, String attributeName, boolean enabled) {
record("updateTimeToLive", scope);
}
@Override
public Map<String, String> listTagsOfResource(Scope scope, String resourceArn) {
record("listTagsOfResource", scope);