feat(dynamodb): export the changes of a period as an incremental export (#6480)

* feat(dynamodb): export the changes of a period as an incremental export

* fix(dynamodb): write characters above U+FFFF in export lines as UTF-8

* feat(dynamodb): refuse incremental export periods over 24 hours

* fix(dynamodb): wait for unfinished writes when an incremental export reads items

* fix(dynamodb): write no incremental export record when only the order of set members changes
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-25 07:38:55 -04:00
1 parent 9242c7003a
commit 3dc5d356d0
13 files changed
+796 -60

No files matched your search

@@ -158,21 +158,48 @@ class DynamoDbExportIntegrationTest {
}
@Test
void exportTableToPointInTime_unsupportedExportType_returnsValidationException() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.ExportTableToPointInTime")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableArn": "%s",
"S3Bucket": "%s",
"ExportType": "INCREMENTAL_EXPORT"
}
""".formatted(TABLE_ARN, BUCKET_NAME))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"));
void incrementalExportRequestIsCheckedAsAwsChecksIt() {
String over1024 = "a".repeat(1025);
String enumSet = "' failed to satisfy constraint: Member must satisfy enum value set: ";
expectError(ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "S3SseAlgorithm": "BAD", "S3Prefix": "%s", "ExportType": "BAD",
"IncrementalExportSpecification": {"ExportViewType": "BAD"}, "ExportFormat": "BAD"}
""".formatted(TABLE_ARN_PREFIX + "IncrementalMissing", BUCKET_NAME, over1024)), "ValidationException",
"5 validation errors detected: Value 'BAD' at 's3SseAlgorithm" + enumSet + "[AES256, KMS]; Value '"
+ over1024 + "' at 's3Prefix' failed to satisfy constraint: Member must have length less than or equal to 1024; "
+ "Value 'BAD' at 'exportType" + enumSet + "[FULL_EXPORT, INCREMENTAL_EXPORT]; "
+ "Value 'BAD' at 'incrementalExportSpecification.exportViewType" + enumSet + "[NEW_AND_OLD_IMAGES, NEW_IMAGE]; "
+ "Value 'BAD' at 'exportFormat" + enumSet + "[ION, DYNAMODB_JSON]");
expectError(incrementalExport("IncrementalMissing", "inc", null), "TableNotFoundException",
"Table not found: " + TABLE_ARN_PREFIX + "IncrementalMissing");
String tooLong = "a".repeat(949);
expectError(incrementalExport(TABLE_NAME, tooLong, null), "ValidationException",
"Invalid Request: Incremental Export Specification expected when export type is set as Incremental Export");
expectError(ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "S3Prefix": "%s", "ExportType": "FULL_EXPORT",
"IncrementalExportSpecification": {"ExportFromTime": 1}}
""".formatted(TABLE_ARN, BUCKET_NAME, tooLong)), "ValidationException",
"Invalid Request: When Export Type is Full Export , Incremental Export Specification should not be provided");
expectError(ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "S3Prefix": "%s", "IncrementalExportSpecification": {"ExportFromTime": 1}}
""".formatted(TABLE_ARN, BUCKET_NAME, tooLong)), "ValidationException",
"Invalid Request: Export Type expected to be Incremental Export when incremental export specification is provided");
expectError(incrementalExport(TABLE_NAME, tooLong, "{\"ExportToTime\": 1}"), "ValidationException",
"Invalid Request: ExportFromTime must be provided in IncrementalExportSpecification");
expectError(incrementalExport(TABLE_NAME, tooLong, "{\"ExportFromTime\": 1}"), "ValidationException",
"Invalid Request: S3 Prefix is too long");
expectError(incrementalExport(TABLE_NAME, "inc", "{\"ExportFromTime\": 1000000000.5, \"ExportToTime\": 1}"),
"InvalidExportTimeException",
"Incremental export period from time cannot be less than the table creation time : 2001-09-09T01:46:40.500Z");
long now = System.currentTimeMillis() / 1000;
expectError(incrementalExport(TABLE_NAME, "inc", "{\"ExportFromTime\": %d, \"ExportToTime\": %d}"
.formatted(now, now + 3600)), "InvalidExportTimeException",
"Incremental export period to time cannot be greater than the current time : "
+ Instant.ofEpochSecond(now + 3600));
expectError(incrementalExport(TABLE_NAME, "inc", "{\"ExportFromTime\": %d}".formatted(now + 60)),
"InvalidExportTimeException",
"Incremental export period from time should not be greater or equal to incremental export period to time");
}
@Test
@@ -398,6 +425,13 @@ class DynamoDbExportIntegrationTest {
// --- Helpers ---
private static ValidatableResponse incrementalExport(String table, String prefix, String specification) {
return ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "S3Prefix": "%s", "ExportType": "INCREMENTAL_EXPORT"%s}
""".formatted(TABLE_ARN_PREFIX + table, BUCKET_NAME, prefix,
specification != null ? ", \"IncrementalExportSpecification\": " + specification : ""));
}
private static ValidatableResponse exportWithPrefix(String table, String prefix) {
return given()
.header("X-Amz-Target", "DynamoDB_20120810.ExportTableToPointInTime")
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPointInTimeRecovery.ItemChange;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DynamoDbExportRecordsTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final TableDefinition TABLE = new TableDefinition("Sorted",
List.of(new KeySchemaElement("zk", "HASH"), new KeySchemaElement("ak", "RANGE")),
List.of(new AttributeDefinition("zk", "S"), new AttributeDefinition("ak", "N")));
private static final String ITEM = """
{"zk": {"S": "old"}, "ak": {"N": "1"}, "😀": {"S": "emoji name"}, "~": {"S": "fullwidth tilde name"},
"z": {"S": "z"}, "a": {"S": "a"}, "B": {"S": "upper B"}, "é": {"S": "e acute"},
"ss": {"SS": ["😀", "~", "b", "B", "a", "é"]}, "ns": {"NS": ["3", "-10", "100", "-2.5", "0", "0.25"]},
"bs": {"BS": ["/w==", "AA==", "gA==", "fw==", "Pg==", "AAE="]},
"m": {"M": {"z": {"N": "1"}, "a": {"N": "2"}, "😀": {"S": "e"}, "~": {"S": "t"},
"nested": {"M": {"y": {"N": "1"}, "b": {"N": "2"}}}}},
"l": {"L": [{"M": {"z": {"N": "1"}, "a": {"N": "2"}}}, {"SS": ["b", "a"]}, {"NS": ["2", "1"]}]},
"v": {"S": "%s"}}
""";
private static final String SORTED = "\"B\":{\"S\":\"upper B\"},\"a\":{\"S\":\"a\"},\"ak\":{\"N\":\"1\"},"
+ "\"bs\":{\"BS\":[\"AA==\",\"AAE=\",\"Pg==\",\"fw==\",\"gA==\",\"/w==\"]},"
+ "\"l\":{\"L\":[{\"M\":{\"a\":{\"N\":\"2\"},\"z\":{\"N\":\"1\"}}},{\"SS\":[\"a\",\"b\"]},{\"NS\":[\"1\",\"2\"]}]},"
+ "\"m\":{\"M\":{\"a\":{\"N\":\"2\"},\"nested\":{\"M\":{\"b\":{\"N\":\"2\"},\"y\":{\"N\":\"1\"}}},"
+ "\"z\":{\"N\":\"1\"},\"~\":{\"S\":\"t\"},\"😀\":{\"S\":\"e\"}}},"
+ "\"ns\":{\"NS\":[\"-10\",\"-2.5\",\"0\",\"0.25\",\"3\",\"100\"]},"
+ "\"ss\":{\"SS\":[\"B\",\"a\",\"b\",\"é\",\"~\",\"😀\"]},\"v\":{\"S\":\"%s\"},\"z\":{\"S\":\"z\"},"
+ "\"zk\":{\"S\":\"old\"},\"é\":{\"S\":\"e acute\"},\"~\":{\"S\":\"fullwidth tilde name\"},"
+ "\"😀\":{\"S\":\"emoji name\"}";
private static final String ION_SORTED = "B:\"upper B\",a:\"a\",ak:1.,"
+ "bs:$dynamodb_BS::[{{AA==}},{{AAE=}},{{Pg==}},{{fw==}},{{gA==}},{{/w==}}],"
+ "l:[{a:2.,z:1.},$dynamodb_SS::[\"a\",\"b\"],$dynamodb_NS::[1.,2.]],"
+ "m:{a:2.,nested:{b:2.,y:1.},z:1.,'~':\"t\",'😀':\"e\"},ns:$dynamodb_NS::[-1d1,-2.5,0.,0.25,3.,1d2],"
+ "ss:$dynamodb_SS::[\"B\",\"a\",\"b\",\"é\",\"~\",\"😀\"],v:\"%s\",z:\"z\",zk:\"old\",'é':\"e acute\","
+ "'~':\"fullwidth tilde name\",'😀':\"emoji name\"";
@Test
void recordIsTheRecordAwsWrites() throws IOException {
ItemChange update = new ItemChange(MAPPER.readTree(ITEM.formatted("before")), MAPPER.readTree(ITEM.formatted("after")),
Instant.EPOCH.plus(1792884188164874L, ChronoUnit.MICROS));
JsonNode record = DynamoDbExportRecords.records(List.of(update), TABLE, false).getFirst();
assertEquals("{\"Metadata\":{\"WriteTimestampMicros\":{\"N\":\"1792884188164874\"}},"
+ "\"Keys\":{\"ak\":{\"N\":\"1\"},\"zk\":{\"S\":\"old\"}},\"OldImage\":{" + SORTED.formatted("before")
+ "},\"NewImage\":{" + SORTED.formatted("after") + "}}", MAPPER.writeValueAsString(record));
assertEquals("$ion_1_0 {Record:{Keys:{ak:1.,zk:\"old\"},Metadata:{WriteTimestampMicros:1792884188164874.},"
+ "OldImage:{" + ION_SORTED.formatted("before") + "},NewImage:{" + ION_SORTED.formatted("after") + "}}}",
DynamoDbIonText.recordLine(record));
}
@Test
void itemWhoseSetsOnlyChangeOrderGetsNoRecord() throws IOException {
String item = """
{"zk": {"S": "k"}, "ak": {"N": "1"}, "ss": {"SS": %s}, "ns": {"NS": %s}, "bs": {"BS": %s},
"m": {"M": {"ss": {"SS": %s}}}, "l": {"L": [{"NS": %s}]}}
""";
ItemChange reordered = new ItemChange(
MAPPER.readTree(item.formatted("[\"a\", \"b\"]", "[\"1\", \"2\"]", "[\"AQ==\", \"Ag==\"]",
"[\"x\", \"y\"]", "[\"10\", \"20\"]")),
MAPPER.readTree(item.formatted("[\"b\", \"a\"]", "[\"2\", \"1\"]", "[\"Ag==\", \"AQ==\"]",
"[\"y\", \"x\"]", "[\"20\", \"10\"]")),
Instant.EPOCH);
assertEquals(List.of(), DynamoDbExportRecords.records(List.of(reordered), TABLE, false));
}
}
@@ -0,0 +1,78 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPointInTimeRecovery.ItemChange;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DynamoDbPointInTimeRecoveryTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ACCOUNT = "000000000000";
private static final String TABLE_KEY = "us-east-1::Items";
private final MutableClock clock = new MutableClock();
private final DynamoDbPointInTimeRecovery recovery =
new DynamoDbPointInTimeRecovery(new InMemoryStorage<>(), ACCOUNT, Duration.ofMinutes(5), clock);
private final TableDefinition table = new TableDefinition("Items",
List.of(new KeySchemaElement("pk", "HASH")), List.of(new AttributeDefinition("pk", "S")));
private final Map<String, JsonNode> live = new ConcurrentHashMap<>();
@Test
void changesBetweenWaitsForAWriteThatIsRecordedButNotYetWritten() {
table.setPointInTimeRecoveryEnabled(true);
Instant from = clock.instant();
live.put("k", item("A"));
recovery.recordItem(ACCOUNT, TABLE_KEY, table, "k", item("A"));
List<ItemChange> changes = recovery.changesBetween(ACCOUNT, TABLE_KEY, live, from, from.plusSeconds(60),
(itemKey, read) -> {
live.put(itemKey, item("B"));
return read.get();
});
assertEquals(1, changes.size());
assertEquals(item("A"), changes.getFirst().oldItem());
assertEquals(item("B"), changes.getFirst().newItem());
}
@Test
void changesBetweenLeavesOutAWriteAfterTheEndThatFinishesBeforeTheItemIsRead() {
table.setPointInTimeRecoveryEnabled(true);
Instant from = clock.instant();
recovery.recordItem(ACCOUNT, TABLE_KEY, table, "k", item("A"));
live.put("k", item("B"));
List<ItemChange> changes = recovery.changesBetween(ACCOUNT, TABLE_KEY, live, from, from.plusSeconds(60),
(itemKey, read) -> {
clock.advance(Duration.ofMinutes(2));
recovery.recordItem(ACCOUNT, TABLE_KEY, table, itemKey, live.get(itemKey));
live.put(itemKey, item("C"));
return read.get();
});
assertEquals(1, changes.size());
assertEquals(item("B"), changes.getFirst().newItem());
}
private static JsonNode item(String value) {
ObjectNode item = MAPPER.createObjectNode();
item.putObject("pk").put("S", "k");
item.putObject("v").put("S", value);
return item;
}
}
@@ -33,13 +33,17 @@ import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -4509,7 +4513,7 @@ class DynamoDbServiceTest {
Map<String, Object> request = Map.of("TableArn", tableArn, "S3Bucket", "bucket");
AwsException e = assertThrows(AwsException.class,
() -> service.exportTable(request, Instant.EPOCH, "us-east-1"));
() -> service.exportTable(request, Instant.EPOCH, null, "us-east-1"));
assertEquals("TableNotFoundException", e.getErrorCode());
assertEquals("Table not found: " + tableArn, e.getMessage());
@@ -4524,7 +4528,7 @@ class DynamoDbServiceTest {
.thenThrow(new AwsException("InternalError", "We encountered an internal error. Please try again.", 500));
DynamoDbService svc = inlineExportService(s3);
String exportArn = svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket"), null, "us-east-1")
String exportArn = svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket"), null, null, "us-east-1")
.getExportArn();
verify(s3).abortMultipartUpload(eq("bucket"), endsWith("/_started"), eq(upload.getUploadId()));
@@ -4538,8 +4542,8 @@ class DynamoDbServiceTest {
String longest = "a".repeat(948);
String slashed = svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket", "S3Prefix", "ends-with/"),
null, "us-east-1").getExportArn();
svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket", "S3Prefix", longest), null, "us-east-1");
null, null, "us-east-1").getExportArn();
svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket", "S3Prefix", longest), null, null, "us-east-1");
String slashedId = slashed.substring(slashed.lastIndexOf('/') + 1);
verify(s3).initiateMultipartUpload("bucket", "ends-with/AWSDynamoDB/" + slashedId + "/_started",
@@ -4558,24 +4562,198 @@ class DynamoDbServiceTest {
svc.putItem("Users", mapper.readTree("{\"userId\": {\"S\": \"u1\"}, \"total\": {\"N\": \"150\"}}"), "us-east-1");
String exportArn = svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket", "S3Prefix", "exports-ion",
"ExportFormat", "ION"), null, "us-east-1").getExportArn();
"ExportFormat", "ION"), null, null, "us-east-1").getExportArn();
ExportDescription described = svc.describeExport(exportArn);
assertEquals("COMPLETED", described.getExportStatus());
assertEquals("ION", described.getExportFormat());
Map<String, byte[]> files = uploadedFiles(s3);
String dir = "exports-ion/AWSDynamoDB/" + exportArn.substring(exportArn.lastIndexOf('/') + 1) + "/";
String dataKey = files.keySet().stream().filter(key -> key.endsWith(".ion.gz")).findFirst().orElseThrow();
assertTrue(dataKey.matches(dir + "data/[a-z2-7]{26}\\.ion\\.gz"), dataKey);
assertEquals("$ion_1_0 {Item:{userId:\"u1\",total:15d1}}\n", gunzip(files.get(dataKey)));
assertEquals("ION", mapper.readTree(files.get(dir + "manifest-summary.json")).get("outputFormat").asText());
}
@Test
void jsonExportWritesCharactersAboveUffffAsUtf8() throws Exception {
S3Service s3 = exportBucket();
DynamoDbService svc = inlineExportService(s3);
svc.putItem("Users", item("userId", "u1", "😀", "😀"), "us-east-1");
svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket"), null, null, "us-east-1");
byte[] dataFile = uploadedFiles(s3).entrySet().stream().filter(file -> file.getKey().endsWith(".json.gz"))
.findFirst().orElseThrow().getValue();
assertEquals("{\"Item\":{\"userId\":{\"S\":\"u1\"},\"😀\":{\"S\":\"😀\"}}}\n", gunzip(dataFile));
}
@Test
void incrementalExportWritesARecordForEachChangedItem() throws Exception {
S3Service s3 = exportBucket();
DynamoDbService svc = incrementalExportService(s3);
for (String id : List.of("updated", "deleted", "same", "twice", "deletedThenPut")) {
svc.putItem("Users", item("userId", id, "v", "before"), "us-east-1");
}
clock.advance(Duration.ofSeconds(1));
Instant from = clock.instant();
svc.putItem("Users", item("userId", "updated", "v", "after"), "us-east-1");
svc.deleteItem("Users", item("userId", "deleted"), "us-east-1");
svc.putItem("Users", item("userId", "new", "v", "new 😀"), "us-east-1");
svc.putItem("Users", item("userId", "newThenDeleted", "v", "new"), "us-east-1");
svc.deleteItem("Users", item("userId", "newThenDeleted"), "us-east-1");
svc.putItem("Users", item("userId", "same", "v", "before"), "us-east-1");
svc.putItem("Users", item("userId", "twice", "v", "first"), "us-east-1");
Instant beforeLastWrite = clock.instant();
svc.putItem("Users", item("userId", "twice", "v", "second"), "us-east-1");
svc.deleteItem("Users", item("userId", "deletedThenPut"), "us-east-1");
svc.putItem("Users", item("userId", "deletedThenPut", "v", "put"), "us-east-1");
clock.advance(Duration.ofMinutes(15));
Instant to = clock.instant();
svc.putItem("Users", item("userId", "updated", "v", "after the period"), "us-east-1");
String exportArn = svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket", "S3Prefix", "inc",
"ExportType", "INCREMENTAL_EXPORT"), null, new DynamoDbService.IncrementalExportRequest(from, to, null),
"us-east-1").getExportArn();
assertTrue(exportArn.matches(".*/export/\\d{11}000-[0-9a-f]{8}"), exportArn);
ExportDescription described = svc.describeExport(exportArn);
assertEquals("COMPLETED", described.getExportStatus());
assertEquals("INCREMENTAL_EXPORT", described.getExportType());
assertNull(described.getExportTime());
assertEquals(BigDecimal.valueOf(from.toEpochMilli(), 3),
described.getIncrementalExportSpecification().getExportFromTime());
assertEquals(BigDecimal.valueOf(to.toEpochMilli(), 3), described.getIncrementalExportSpecification().getExportToTime());
assertEquals("NEW_AND_OLD_IMAGES", described.getIncrementalExportSpecification().getExportViewType());
Map<String, byte[]> files = uploadedFiles(s3);
String dataKey = files.keySet().stream().filter(key -> key.endsWith(".json.gz")).findFirst().orElseThrow();
assertTrue(dataKey.matches("inc/AWSDynamoDB/data/[a-z2-7]{26}\\.json\\.gz"), dataKey);
String[] records = gunzip(files.get(dataKey)).split("\n");
assertEquals(List.of(
"{\"Metadata\":{\"WriteTimestampMicros\":{\"N\":\"T\"}},\"Keys\":{\"userId\":{\"S\":\"updated\"}},"
+ "\"OldImage\":{\"userId\":{\"S\":\"updated\"},\"v\":{\"S\":\"before\"}},"
+ "\"NewImage\":{\"userId\":{\"S\":\"updated\"},\"v\":{\"S\":\"after\"}}}",
"{\"Metadata\":{\"WriteTimestampMicros\":{\"N\":\"T\"}},\"Keys\":{\"userId\":{\"S\":\"deleted\"}},"
+ "\"OldImage\":{\"userId\":{\"S\":\"deleted\"},\"v\":{\"S\":\"before\"}}}",
"{\"Metadata\":{\"WriteTimestampMicros\":{\"N\":\"T\"}},\"Keys\":{\"userId\":{\"S\":\"new\"}},"
+ "\"NewImage\":{\"userId\":{\"S\":\"new\"},\"v\":{\"S\":\"new 😀\"}}}",
"{\"Metadata\":{\"WriteTimestampMicros\":{\"N\":\"T\"}},\"Keys\":{\"userId\":{\"S\":\"twice\"}},"
+ "\"OldImage\":{\"userId\":{\"S\":\"twice\"},\"v\":{\"S\":\"before\"}},"
+ "\"NewImage\":{\"userId\":{\"S\":\"twice\"},\"v\":{\"S\":\"second\"}}}",
"{\"Metadata\":{\"WriteTimestampMicros\":{\"N\":\"T\"}},\"Keys\":{\"userId\":{\"S\":\"deletedThenPut\"}},"
+ "\"OldImage\":{\"userId\":{\"S\":\"deletedThenPut\"},\"v\":{\"S\":\"before\"}},"
+ "\"NewImage\":{\"userId\":{\"S\":\"deletedThenPut\"},\"v\":{\"S\":\"put\"}}}"),
Arrays.stream(records).map(r -> r.replaceFirst("\"N\":\"\\d+\"", "\"N\":\"T\"")).toList());
assertEquals(5L, described.getItemCount());
assertEquals(10_000_000L, described.getBilledSizeBytes());
long lastWriteMicros = mapper.readTree(records[3]).at("/Metadata/WriteTimestampMicros/N").asLong();
assertTrue(ChronoUnit.MICROS.between(Instant.EPOCH, beforeLastWrite) < lastWriteMicros);
assertTrue(lastWriteMicros < ChronoUnit.MICROS.between(Instant.EPOCH, to));
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
JsonNode summary = mapper.readTree(files.get("inc/AWSDynamoDB/" + exportId + "/manifest-summary.json"));
List<String> summaryFields = new ArrayList<>();
summary.fieldNames().forEachRemaining(summaryFields::add);
assertEquals(List.of("version", "exportArn", "startTime", "endTime", "tableArn", "tableId", "exportFromTime",
"exportToTime", "s3Bucket", "s3Prefix", "s3SseAlgorithm", "s3SseKmsKeyId", "manifestFilesS3Key",
"billedSizeBytes", "itemCount", "outputFormat", "outputView", "exportType"), summaryFields);
assertEquals("2023-08-01", summary.get("version").asText());
assertEquals("NEW_AND_OLD_IMAGES", summary.get("outputView").asText());
assertEquals("INCREMENTAL_EXPORT", summary.get("exportType").asText());
}
@Test
void incrementalIonExportOfNewImagesLeavesOutOldImages() throws Exception {
S3Service s3 = exportBucket();
DynamoDbService svc = incrementalExportService(s3);
svc.putItem("Users", item("userId", "updated", "v", "before"), "us-east-1");
svc.putItem("Users", item("userId", "deleted", "v", "before"), "us-east-1");
clock.advance(Duration.ofSeconds(1));
Instant from = clock.instant();
svc.putItem("Users", item("userId", "updated", "v", "after"), "us-east-1");
svc.deleteItem("Users", item("userId", "deleted"), "us-east-1");
clock.advance(Duration.ofMinutes(20));
String exportArn = svc.exportTable(Map.of("TableArn", USERS_ARN, "S3Bucket", "bucket", "ExportFormat", "ION",
"ExportType", "INCREMENTAL_EXPORT"), null,
new DynamoDbService.IncrementalExportRequest(from, null, "NEW_IMAGE"), "us-east-1").getExportArn();
ExportDescription described = svc.describeExport(exportArn);
assertEquals("COMPLETED", described.getExportStatus());
assertEquals(described.getStartTime(), described.getIncrementalExportSpecification().getExportToTime());
assertEquals(0, described.getStartTime().remainder(BigDecimal.ONE).signum());
Map<String, byte[]> files = uploadedFiles(s3);
String dataKey = files.keySet().stream().filter(key -> key.endsWith(".ion.gz")).findFirst().orElseThrow();
assertTrue(dataKey.matches("AWSDynamoDB/data/[a-z2-7]{26}\\.ion\\.gz"), dataKey);
assertEquals("""
$ion_1_0 {Record:{Keys:{userId:"updated"},Metadata:{WriteTimestampMicros:T},NewImage:{userId:"updated",v:"after"}}}
$ion_1_0 {Record:{Keys:{userId:"deleted"},Metadata:{WriteTimestampMicros:T}}}
""", gunzip(files.get(dataKey)).replaceAll("WriteTimestampMicros:\\d+d\\d+", "WriteTimestampMicros:T"));
}
@Test
void incrementalExportChecksThePeriodInTheAwsOrder() {
DynamoDbService svc = incrementalExportService(exportBucket());
svc.createTable("NoBackups", List.of(new KeySchemaElement("userId", "HASH")),
List.of(new AttributeDefinition("userId", "S")), 5L, 5L, "us-east-1");
Instant creationSecond = svc.describeTable("NoBackups", "us-east-1").getCreationDateTime()
.truncatedTo(ChronoUnit.SECONDS);
clock.advance(Duration.ofHours(25));
Instant now = clock.instant();
Instant beforeCreation = creationSecond.minusMillis(1);
expectInvalidExportTime(svc, "NoBackups", beforeCreation, now.plusSeconds(60),
"Incremental export period from time cannot be less than the table creation time : " + beforeCreation);
Instant afterNow = now.plusSeconds(60);
expectInvalidExportTime(svc, "NoBackups", afterNow.plusSeconds(60), afterNow,
"Incremental export period to time cannot be greater than the current time : " + afterNow);
expectInvalidExportTime(svc, "NoBackups", creationSecond, creationSecond,
"Incremental export period from time should not be greater or equal to incremental export period to time");
expectInvalidExportTime(svc, "NoBackups", creationSecond, creationSecond.plus(Duration.ofMinutes(15)).minusMillis(1),
"Difference between export period from time and export period to time is less than 15 minutes");
Instant overADay = creationSecond.plus(Duration.ofHours(24)).plusSeconds(1);
String overADayMessage = "Difference between export period from time and export period to time is greater than 24 hours";
expectInvalidExportTime(svc, "NoBackups", creationSecond, overADay, overADayMessage);
for (Duration period : List.of(Duration.ofMinutes(15), Duration.ofHours(24).plusMillis(1))) {
AwsException noBackups = assertThrows(AwsException.class, () -> incrementalExport(svc, "NoBackups",
creationSecond, creationSecond.plus(period)));
assertEquals("PointInTimeRecoveryUnavailableException", noBackups.getErrorCode());
}
svc.updateContinuousBackups("Users", false, null, "us-east-1");
svc.updateContinuousBackups("Users", true, null, "us-east-1");
expectInvalidExportTime(svc, "Users", creationSecond, overADay, overADayMessage);
expectInvalidExportTime(svc, "Users", creationSecond, creationSecond.plus(Duration.ofMinutes(15)),
"Export period from time cannot be earlier than the Point in Time Recovery window");
}
private static void expectInvalidExportTime(DynamoDbService svc, String table, Instant from, Instant to,
String message) {
AwsException e = assertThrows(AwsException.class, () -> incrementalExport(svc, table, from, to));
assertEquals("InvalidExportTimeException", e.getErrorCode());
assertEquals(message, e.getMessage());
}
private static ExportDescription incrementalExport(DynamoDbService svc, String table, Instant from, Instant to) {
return svc.exportTable(Map.of("TableArn", "arn:aws:dynamodb:us-east-1:000000000000:table/" + table,
"S3Bucket", "bucket", "ExportType", "INCREMENTAL_EXPORT"), null,
new DynamoDbService.IncrementalExportRequest(from, to, null), "us-east-1");
}
/** Every file the export uploaded, by key. */
private static Map<String, byte[]> uploadedFiles(S3Service s3) {
ArgumentCaptor<String> keys = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<byte[]> parts = ArgumentCaptor.forClass(byte[].class);
verify(s3, atLeastOnce()).uploadPart(eq("bucket"), keys.capture(), anyString(), eq(1), parts.capture());
String dir = "exports-ion/AWSDynamoDB/" + exportArn.substring(exportArn.lastIndexOf('/') + 1) + "/";
List<String> uploadedKeys = keys.getAllValues();
String dataKey = uploadedKeys.stream().filter(key -> key.endsWith(".ion.gz")).findFirst().orElseThrow();
assertTrue(dataKey.matches(dir + "data/[a-z2-7]{26}\\.ion\\.gz"), dataKey);
byte[] dataFile = parts.getAllValues().get(uploadedKeys.indexOf(dataKey));
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(dataFile))) {
assertEquals("$ion_1_0 {Item:{userId:\"u1\",total:15d1}}\n", new String(gzip.readAllBytes(), StandardCharsets.UTF_8));
Map<String, byte[]> files = new LinkedHashMap<>();
for (int i = 0; i < keys.getAllValues().size(); i++) {
files.put(keys.getAllValues().get(i), parts.getAllValues().get(i));
}
return files;
}
private static String gunzip(byte[] data) throws IOException {
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(data))) {
return new String(gzip.readAllBytes(), StandardCharsets.UTF_8);
}
byte[] summary = parts.getAllValues().get(uploadedKeys.indexOf(dir + "manifest-summary.json"));
assertEquals("ION", mapper.readTree(summary).get("outputFormat").asText());
}
/** A bucket that takes every upload, each completing with a one-part ETag. */
@@ -4599,6 +4777,12 @@ class DynamoDbServiceTest {
return svc;
}
/** Tables take their creation time from the system clock, so this clock starts after it. */
private DynamoDbService incrementalExportService(S3Service s3) {
clock.advance(Duration.between(clock.instant(), Instant.now()).plusSeconds(1));
return inlineExportService(s3);
}
@Test
void validateImportRequest_rejectsUnsupportedFormatWithoutUnsupportedOperationWording() {
AwsException e = assertThrows(AwsException.class,