feat(dynamodb): write export files and descriptions as AWS does (#6400)

* feat(dynamodb): write export files and descriptions as AWS does

* fix(dynamodb): check export prefixes as AWS does

* fix(dynamodb): abort the upload of an export file that fails

* chore(dynamodb): share the timed id of backups and exports

* chore(dynamodb): let tests run exports on the calling thread
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-24 08:38:15 -04:00
1 parent 4e0bf080ed
commit 023cb8341b
11 files changed
+328 -121

No files matched your search

@@ -9,9 +9,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
class DigestsTest {
private static final String ABC_MD5 = "900150983cd24fb0d6963f7d28e17f72";
private static final String ABC_SHA1 = "a9993e364706816aba3e25717850c26c9cd0d89d";
private static final String ABC_SHA256 = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
@Test
void md5MatchesTheRfc1321TestVector() {
assertEquals(ABC_MD5, HexFormat.of().formatHex(Digests.md5("abc".getBytes(StandardCharsets.UTF_8))));
}
@Test
void sha1MatchesTheFipsTestVector() {
assertEquals(ABC_SHA1, HexFormat.of().formatHex(Digests.sha1("abc".getBytes(StandardCharsets.UTF_8))));
@@ -1,5 +1,8 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
@@ -14,7 +17,9 @@ import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.zip.GZIPInputStream;
@@ -94,12 +99,15 @@ class DynamoDbExportIntegrationTest {
.when().post("/")
.then()
.statusCode(200)
.body("ExportDescription.ExportArn", notNullValue())
.body("ExportDescription.ExportArn", matchesPattern(TABLE_ARN + "/export/\\d{14}-[0-9a-f]{8}"))
.body("ExportDescription.ExportStatus", equalTo("IN_PROGRESS"))
.body("ExportDescription.TableArn", equalTo(TABLE_ARN))
.body("ExportDescription.S3Bucket", equalTo(BUCKET_NAME))
.body("ExportDescription.ExportFormat", equalTo("DYNAMODB_JSON"))
.body("ExportDescription.ExportType", equalTo("FULL_EXPORT"))
.body("ExportDescription", not(hasKey("ExportType")))
.body("ExportDescription.DestinationType", equalTo("S3"))
.body("ExportDescription.S3SseAlgorithm", equalTo("AES256"))
.body("ExportDescription.TableId", equalTo(tableId(TABLE_NAME)))
.extract().path("ExportDescription.ExportArn");
assertNotNull(exportArn);
@@ -145,7 +153,8 @@ class DynamoDbExportIntegrationTest {
.body("ExportSummaries", hasSize(greaterThanOrEqualTo(1)))
.body("ExportSummaries[0].ExportArn", notNullValue())
.body("ExportSummaries[0].ExportStatus", notNullValue())
.body("ExportSummaries[0].ExportType", equalTo("FULL_EXPORT"));
.body("ExportSummaries[0].ExportType", equalTo("FULL_EXPORT"))
.body("ExportSummaries[0].DestinationType", equalTo("S3"));
}
@Test
@@ -220,36 +229,46 @@ class DynamoDbExportIntegrationTest {
String exportArn = startExport("exports-data");
pollUntilCompleted(exportArn, 10_000);
String manifestKey = given()
.header("X-Amz-Target", "DynamoDB_20120810.DescribeExport")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{\"ExportArn\": \"" + exportArn + "\"}")
.when().post("/")
.then().statusCode(200)
.extract().path("ExportDescription.ExportManifest");
assertNotNull(manifestKey, "ExportManifest key should be set");
// Extract bucket prefix from the manifest key
// manifestKey is like: exports-data/AWSDynamoDB/<exportId>/manifest-summary.json
ValidatableResponse describe = ddb("DescribeExport", "{\"ExportArn\": \"" + exportArn + "\"}").statusCode(200);
JsonPath described = describe.extract().jsonPath();
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
String manifestFilesKey = "exports-data/AWSDynamoDB/" + exportId + "/manifest-files.json";
String dir = "exports-data/AWSDynamoDB/" + exportId + "/";
assertEquals(dir + "manifest-summary.json", described.getString("ExportDescription.ExportManifest"));
// Download manifest-files.json and find the data key
byte[] manifestFiles = given()
.when().get("/" + BUCKET_NAME + "/" + manifestFilesKey)
assertEquals(0, s3Object(dir + "_started").length);
byte[] manifestFiles = s3Object(dir + "manifest-files.json");
assertEquals(md5Base64(manifestFiles), new String(s3Object(dir + "manifest-files.md5"), StandardCharsets.UTF_8));
String manifestLine = new String(manifestFiles, StandardCharsets.UTF_8);
assertTrue(manifestLine.endsWith("}\n"), manifestLine);
JsonPath dataFile = JsonPath.from(manifestLine);
String dataKey = dataFile.getString("dataFileS3Key");
assertTrue(dataKey.matches(dir + "data/[a-z2-7]{26}\\.json\\.gz"), dataKey);
byte[] gzipData = s3Object(dataKey);
assertEquals(3, dataFile.getInt("itemCount"));
assertEquals(md5Base64(gzipData), dataFile.getString("md5Checksum"));
given().when().head("/" + BUCKET_NAME + "/" + dataKey)
.then().statusCode(200)
.extract().asByteArray();
.header("ETag", equalTo("\"" + dataFile.getString("etag") + "\""))
.header("ETag", endsWith("-1\""))
.header("Content-Type", equalTo("application/octet-stream"));
String dataKey = new String(manifestFiles, StandardCharsets.UTF_8).trim();
assertFalse(dataKey.isEmpty(), "manifest-files.json should contain the data file key");
assertTrue(dataKey.endsWith(".json.gz"), "Data file should be a .json.gz file");
// Download and decompress the data file
byte[] gzipData = given()
.when().get("/" + BUCKET_NAME + "/" + dataKey)
.then().statusCode(200)
.extract().asByteArray();
byte[] summaryBytes = s3Object(dir + "manifest-summary.json");
assertEquals(md5Base64(summaryBytes), new String(s3Object(dir + "manifest-summary.md5"), StandardCharsets.UTF_8));
JsonNode summary = new ObjectMapper().readTree(summaryBytes);
List<String> fields = new ArrayList<>();
summary.fieldNames().forEachRemaining(fields::add);
assertEquals(List.of("version", "exportArn", "startTime", "endTime", "tableArn", "tableId", "exportTime",
"s3Bucket", "s3Prefix", "s3SseAlgorithm", "s3SseKmsKeyId", "manifestFilesS3Key", "billedSizeBytes",
"itemCount", "outputFormat"), fields);
assertEquals("2020-06-30", summary.get("version").asText());
assertEquals(manifestTime(decimalAt(describe, "/ExportDescription/StartTime")), summary.get("startTime").asText());
assertEquals(manifestTime(decimalAt(describe, "/ExportDescription/EndTime")), summary.get("endTime").asText());
assertEquals(tableId(TABLE_NAME), summary.get("tableId").asText());
assertEquals("exports-data", summary.get("s3Prefix").asText());
assertTrue(summary.get("s3SseKmsKeyId").isNull());
assertEquals(dir + "manifest-files.json", summary.get("manifestFilesS3Key").asText());
assertEquals(3, summary.get("itemCount").asInt());
assertEquals("DYNAMODB_JSON", summary.get("outputFormat").asText());
String ndjson = decompressGzip(gzipData);
String[] lines = ndjson.split("\n");
@@ -289,6 +308,7 @@ class DynamoDbExportIntegrationTest {
assertEquals("COMPLETED", pollUntilCompleted(atT1Arn, 10_000));
assertEquals(List.of("k1=v1"), exportedItems(atT1Arn, "export-time-t1"));
String noTimeArn = noTime.extract().path("ExportDescription.ExportArn");
assertTrue(noTimeArn.contains("/export/" + String.format("%014d", startMillis) + "-"), noTimeArn);
assertEquals("COMPLETED", pollUntilCompleted(noTimeArn, 10_000));
assertEquals(List.of("k1=v2", "k2=v1"), exportedItems(noTimeArn, "export-time-now"));
}
@@ -339,8 +359,39 @@ class DynamoDbExportIntegrationTest {
"InvalidExportTimeException", "Export Time is invalid");
}
@Test
void s3PrefixIsCheckedAsAwsChecksIt() {
String atLeast3 = "' at 's3Prefix' failed to satisfy constraint: Member must have length greater than or equal to 3";
expectError(exportWithPrefix("ExportPrefixMissing", ""), "ValidationException",
"Invalid Request: 1 validation error detected: Value '" + atLeast3);
expectError(exportWithPrefix("ExportPrefixMissing", "éé"), "ValidationException",
"Invalid Request: 1 validation error detected: Value 'éé" + atLeast3);
String over1024 = "a".repeat(1025);
expectError(exportWithPrefix(TABLE_NAME, over1024), "ValidationException", "1 validation error detected: Value '"
+ over1024 + "' at 's3Prefix' failed to satisfy constraint: Member must have length less than or equal to 1024");
expectError(exportWithPrefix("ExportPrefixMissing", "a".repeat(949)), "TableNotFoundException",
"Table not found: " + TABLE_ARN_PREFIX + "ExportPrefixMissing");
expectError(exportWithPrefix(TABLE_NAME, "é".repeat(475)), "ValidationException",
"Invalid Request: S3 Prefix is too long");
expectError(exportWithPrefix(TABLE_NAME, "a".repeat(949)), "ValidationException",
"Invalid Request: S3 Prefix is too long");
exportWithPrefix(TABLE_NAME, "ends-with/").statusCode(200)
.body("ExportDescription.S3Prefix", equalTo("ends-with/"));
}
// --- Helpers ---
private static ValidatableResponse exportWithPrefix(String table, String prefix) {
return given()
.header("X-Amz-Target", "DynamoDB_20120810.ExportTableToPointInTime")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableArn": "%s", "S3Bucket": "%s", "S3Prefix": "%s"}
""".formatted(TABLE_ARN_PREFIX + table, BUCKET_NAME, prefix).getBytes(StandardCharsets.UTF_8))
.when().post("/")
.then();
}
/** Returns a time between the writes before and after the call, in epoch seconds with milliseconds. */
private static BigDecimal pause() {
long now = System.currentTimeMillis();
@@ -372,14 +423,9 @@ class DynamoDbExportIntegrationTest {
private List<String> exportedItems(String exportArn, String prefix) throws Exception {
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
String dataKey = given()
.when().get("/" + BUCKET_NAME + "/" + prefix + "/AWSDynamoDB/" + exportId + "/manifest-files.json")
.then().statusCode(200)
.extract().asString().trim();
byte[] gzipData = given()
.when().get("/" + BUCKET_NAME + "/" + dataKey)
.then().statusCode(200)
.extract().asByteArray();
String dataKey = JsonPath.from(new String(s3Object(prefix + "/AWSDynamoDB/" + exportId + "/manifest-files.json"),
StandardCharsets.UTF_8)).getString("dataFileS3Key");
byte[] gzipData = s3Object(dataKey);
List<String> items = new ArrayList<>();
for (String line : decompressGzip(gzipData).split("\n")) {
JsonPath item = JsonPath.from(line);
@@ -388,6 +434,28 @@ class DynamoDbExportIntegrationTest {
return items.stream().sorted().toList();
}
private static byte[] s3Object(String key) {
return given().when().get("/" + BUCKET_NAME + "/" + key)
.then().statusCode(200)
.extract().asByteArray();
}
private static String md5Base64(byte[] data) {
return Base64.getEncoder().encodeToString(Digests.md5(data));
}
/** A DescribeExport time in epoch seconds, as the manifest writes it. */
private static String manifestTime(BigDecimal epochSeconds) {
return Instant.ofEpochMilli(epochSeconds.movePointRight(3).longValueExact()).toString()
.replaceFirst("(:\\d{2})Z$", "$1.000Z");
}
private static String tableId(String table) {
return ddb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.extract().path("Table.TableId");
}
private static void expectError(ValidatableResponse response, String type, String message) {
response.statusCode(400)
.body("__type", containsString(type))
@@ -22,12 +22,14 @@ import io.github.hectorvent.floci.services.dynamodb.model.PointInTimeChange;
import io.github.hectorvent.floci.services.dynamodb.model.TableBackup;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.MultipartUpload;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -51,7 +53,11 @@ import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.endsWith;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -62,6 +68,8 @@ import static org.mockito.Mockito.when;
class DynamoDbServiceTest {
private static final String USERS_ARN = "arn:aws:dynamodb:us-east-1:000000000000:table/Users";
private DynamoDbService service;
private ObjectMapper mapper;
// Moves on by a millisecond each time it is read, so a read falls between two writes.
@@ -4506,6 +4514,57 @@ class DynamoDbServiceTest {
assertEquals("Table not found: " + tableArn, e.getMessage());
}
@Test
void exportAbortsTheUploadOfAFileItCannotWrite() {
S3Service s3 = mock(S3Service.class);
MultipartUpload upload = new MultipartUpload("bucket", "_started", "application/octet-stream");
when(s3.initiateMultipartUpload(eq("bucket"), anyString(), eq("application/octet-stream"))).thenReturn(upload);
when(s3.uploadPart(eq("bucket"), anyString(), eq(upload.getUploadId()), eq(1), any(byte[].class)))
.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")
.getExportArn();
verify(s3).abortMultipartUpload(eq("bucket"), endsWith("/_started"), eq(upload.getUploadId()));
assertEquals("FAILED", svc.describeExport(exportArn).getExportStatus());
}
@Test
void exportPutsItsFilesUnderThePrefix() {
S3Service s3 = mock(S3Service.class);
when(s3.initiateMultipartUpload(eq("bucket"), anyString(), eq("application/octet-stream")))
.thenAnswer(invocation -> new MultipartUpload("bucket", invocation.getArgument(1), "application/octet-stream"));
when(s3.completeMultipartUpload(eq("bucket"), anyString(), anyString(), eq(List.of(1)), isNull(), isNull()))
.thenReturn(new S3Object("bucket", "file", new byte[0], "application/octet-stream", "\"0123-1\""));
DynamoDbService svc = inlineExportService(s3);
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");
String slashedId = slashed.substring(slashed.lastIndexOf('/') + 1);
verify(s3).initiateMultipartUpload("bucket", "ends-with/AWSDynamoDB/" + slashedId + "/_started",
"application/octet-stream");
assertEquals("COMPLETED", svc.describeExport(slashed).getExportStatus());
ArgumentCaptor<String> keys = ArgumentCaptor.forClass(String.class);
verify(s3, atLeastOnce()).initiateMultipartUpload(eq("bucket"), keys.capture(), eq("application/octet-stream"));
assertEquals(1024, keys.getAllValues().stream().filter(key -> key.startsWith(longest))
.mapToInt(key -> key.getBytes(StandardCharsets.UTF_8).length).max().orElseThrow());
}
/** Runs each export on the calling thread, with Users created and point-in-time recovery on. */
private DynamoDbService inlineExportService(S3Service s3) {
DynamoDbService svc = new DynamoDbService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), null, null, s3, mapper, 0, 0, 0, clock, Runnable::run);
svc.createTable("Users", List.of(new KeySchemaElement("userId", "HASH")),
List.of(new AttributeDefinition("userId", "S")), 5L, 5L, "us-east-1");
svc.updateContinuousBackups("Users", true, null, "us-east-1");
return svc;
}
@Test
void validateImportRequest_rejectsUnsupportedFormatWithoutUnsupportedOperationWording() {
AwsException e = assertThrows(AwsException.class,