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

@@ -1,5 +1,7 @@
package com.floci.test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -117,7 +119,7 @@ class DynamoDbExportTest {
assertThat(desc.tableArn()).isEqualTo(tableArn);
assertThat(desc.s3Bucket()).isEqualTo(BUCKET_NAME);
assertThat(desc.exportFormat()).isEqualTo(ExportFormat.DYNAMODB_JSON);
assertThat(desc.exportType()).isEqualTo(ExportType.FULL_EXPORT);
assertThat(desc.exportType()).isNull();
exportArn = desc.exportArn();
}
@@ -184,15 +186,19 @@ class DynamoDbExportTest {
// Verify manifest-summary.json exists
ResponseBytes<GetObjectResponse> manifestSummary = s3.getObjectAsBytes(
GetObjectRequest.builder().bucket(BUCKET_NAME).key(manifestSummaryKey).build());
assertThat(manifestSummary.asByteArray().length).isGreaterThan(0);
assertThat(new ObjectMapper().readTree(manifestSummary.asByteArray()).get("outputFormat").asText())
.isEqualTo("DYNAMODB_JSON");
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
String manifestFilesKey = "exports/AWSDynamoDB/" + exportId + "/manifest-files.json";
ResponseBytes<GetObjectResponse> manifestFiles = s3.getObjectAsBytes(
GetObjectRequest.builder().bucket(BUCKET_NAME).key(manifestFilesKey).build());
String dataKey = new String(manifestFiles.asByteArray(), StandardCharsets.UTF_8).trim();
JsonNode dataFileEntry = new ObjectMapper().readTree(manifestFiles.asByteArray());
String dataKey = dataFileEntry.get("dataFileS3Key").asText();
assertThat(dataKey).endsWith(".json.gz");
HeadObjectResponse head = s3.headObject(HeadObjectRequest.builder().bucket(BUCKET_NAME).key(dataKey).build());
assertThat(head.eTag()).isEqualTo("\"" + dataFileEntry.get("etag").asText() + "\"").endsWith("-1\"");
// Download and decompress the data file
ResponseBytes<GetObjectResponse> dataFile = s3.getObjectAsBytes(
+1 -1
View File
@@ -440,7 +440,7 @@ aws dynamodb list-exports \
--endpoint-url $AWS_ENDPOINT_URL
```
The export writes to `s3://<bucket>/<prefix>/AWSDynamoDB/<exportId>/data/` as one or more `.json.gz` files, along with `manifest-summary.json` and `manifest-files.json`, the same layout as real AWS DynamoDB exports.
The export writes `_started`, `manifest-summary.json`, `manifest-files.json` and an `.md5` file for each manifest to `s3://<bucket>/<prefix>/AWSDynamoDB/<exportId>/`, and the items to a `.json.gz` file in its `data/` folder, the layout AWS uses. AWS writes one data file per partition. Floci writes one. As on AWS, every file is a multipart upload of one part, so its ETag ends in `-1`. As on AWS, an `S3Prefix` shorter than 3 characters or longer than 948 UTF-8 bytes is refused, and no slash is added after a prefix that ends with one.
The export holds the items as they were at `ExportTime`, or at the request time when `ExportTime` is not set. As on AWS, `ExportTime` must not be before `EarliestRestorableDateTime` or the table creation, and must not be in the future. A time after `LatestRestorableDateTime` is accepted.
@@ -11,6 +11,14 @@ public final class Digests {
private Digests() {
}
public static byte[] md5(byte[] data) {
try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 is not available", e);
}
}
public static byte[] sha1(byte[] data) {
try {
return MessageDigest.getInstance("SHA-1").digest(data);
@@ -111,7 +111,7 @@ public final class Totp {
actual.getBytes(StandardCharsets.US_ASCII));
}
static String base32Encode(byte[] data) {
public static String base32Encode(byte[] data) {
StringBuilder encoded = new StringBuilder();
int buffer = 0;
int bitsLeft = 0;
@@ -63,8 +63,12 @@ final class DynamoDbBackupArns {
}
static String mint(String tableArn, Instant creationDateTime) {
return tableArn + "/backup/" + String.format("%014d", creationDateTime.toEpochMilli())
+ "-" + UUID.randomUUID().toString().substring(0, 8);
return tableArn + "/backup/" + timedId(creationDateTime);
}
/** AWS ids a backup and an export by their time in milliseconds and 8 random hex digits. */
static String timedId(Instant time) {
return String.format("%014d", time.toEpochMilli()) + "-" + UUID.randomUUID().toString().substring(0, 8);
}
/** AWS ends the id of a system backup with zeros instead of random hex digits. */
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
@@ -46,24 +47,28 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -74,6 +79,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -112,6 +118,7 @@ public class DynamoDbService {
private final StorageBackend<String, TableBackup> backupStore;
private final DynamoDbPointInTimeRecovery pointInTimeRecovery;
private final Clock clock;
private final Executor exportExecutor;
// Items stored per table: storageKey -> Map<itemKey, item>
// itemKey is "pk" or "pk#sk" depending on table schema
private final ConcurrentHashMap<String, ConcurrentSkipListMap<String, JsonNode>> itemsByTable = new ConcurrentHashMap<>();
@@ -284,6 +291,27 @@ public class DynamoDbService {
int vectorIndexBackfillSeconds,
int latestRestorableLagSeconds,
Clock clock) {
this(tableStore, itemStore, exportStore, importStore, backupStore, pointInTimeStore, regionResolver,
streamService, kinesisForwarder, s3Service, objectMapper, vectorIndexAllocationSeconds,
vectorIndexBackfillSeconds, latestRestorableLagSeconds, clock, command -> Thread.ofVirtual().start(command));
}
DynamoDbService(StorageBackend<String, TableDefinition> tableStore,
StorageBackend<String, Map<String, JsonNode>> itemStore,
StorageBackend<String, ExportDescription> exportStore,
StorageBackend<String, ImportTableDescription> importStore,
StorageBackend<String, TableBackup> backupStore,
StorageBackend<String, PointInTimeChange> pointInTimeStore,
RegionResolver regionResolver,
DynamoDbStreamService streamService,
KinesisStreamingForwarder kinesisForwarder,
S3Service s3Service,
ObjectMapper objectMapper,
int vectorIndexAllocationSeconds,
int vectorIndexBackfillSeconds,
int latestRestorableLagSeconds,
Clock clock,
Executor exportExecutor) {
this.tableStore = tableStore;
this.itemStore = itemStore;
this.exportStore = exportStore;
@@ -292,6 +320,7 @@ public class DynamoDbService {
this.pointInTimeRecovery = new DynamoDbPointInTimeRecovery(pointInTimeStore, regionResolver.getAccountId(),
Duration.ofSeconds(latestRestorableLagSeconds), clock);
this.clock = clock;
this.exportExecutor = exportExecutor;
this.regionResolver = regionResolver;
this.streamService = streamService;
this.kinesisForwarder = kinesisForwarder;
@@ -4901,6 +4930,18 @@ public class DynamoDbService {
String s3SseAlgorithm = request.containsKey("S3SseAlgorithm") ? (String) request.get("S3SseAlgorithm") : null;
String s3BucketOwner = request.containsKey("S3BucketOwner") ? (String) request.get("S3BucketOwner") : null;
if (s3Prefix != null) {
int length = s3Prefix.codePointCount(0, s3Prefix.length());
if (1024 < length) {
throw SmithyValidationErrors.validationException("Value '" + s3Prefix
+ "' at 's3Prefix' failed to satisfy constraint: Member must have length less than or equal to 1024");
}
if (length < 3) {
throw new AwsException("ValidationException", "Invalid Request: " + SmithyValidationErrors.message(
List.of("Value '" + s3Prefix + "' at 's3Prefix' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 3")), 400);
}
}
if ("INCREMENTAL_EXPORT".equals(exportType)) {
throw new AwsException("ValidationException",
"ExportType INCREMENTAL_EXPORT is not supported", 400);
@@ -4916,6 +4957,9 @@ public class DynamoDbService {
String storageKey = regionKey(tableRegion, tableName);
TableDefinition table = requireBackupSource(storageKey, tableArn);
if (s3Prefix != null && 948 < s3Prefix.getBytes(StandardCharsets.UTF_8).length) {
throw new AwsException("ValidationException", "Invalid Request: S3 Prefix is too long", 400);
}
Instant startTime = clock.instant().truncatedTo(ChronoUnit.MILLIS);
// AWS cannot enable point-in-time recovery until seconds after the creation, so its
// EarliestRestorableDateTime is never in the creation second.
@@ -4934,22 +4978,22 @@ public class DynamoDbService {
}
Instant time = exportTime != null ? exportTime : startTime;
var exportId = newJobId();
String exportId = DynamoDbBackupArns.timedId(startTime);
String exportArn = AwsArnUtils.Arn.of("dynamodb", tableRegion, regionResolver.getAccountId(), "table/" + table.getTableName() + "/export/" + exportId).toString();
ExportDescription desc = new ExportDescription();
desc.setExportArn(exportArn);
desc.setExportStatus("IN_PROGRESS");
desc.setTableArn(table.getTableArn());
desc.setTableId(table.getTableName());
desc.setTableId(table.getTableId());
desc.setS3Bucket(s3Bucket);
desc.setS3Prefix(s3Prefix);
desc.setExportFormat(exportFormat);
desc.setExportType("FULL_EXPORT");
desc.setExportType((String) request.get("ExportType"));
desc.setExportTime(epochSeconds(time));
desc.setStartTime(epochSeconds(startTime));
desc.setClientToken(clientToken);
desc.setS3SseAlgorithm(s3SseAlgorithm);
desc.setS3SseAlgorithm(s3SseAlgorithm != null ? s3SseAlgorithm : "AES256");
desc.setS3BucketOwner(s3BucketOwner);
if (exportStore != null) {
@@ -4964,7 +5008,7 @@ public class DynamoDbService {
// changes underneath the handler, and the request account so its writes land there.
var accountId = regionResolver.getAccountId();
var worker = objectMapper.convertValue(desc, ExportDescription.class);
Thread.ofVirtual().start(() -> RequestScopes.runAs(accountId, () -> runExport(worker, snapshot, exportArn)));
exportExecutor.execute(() -> RequestScopes.runAs(accountId, () -> runExport(worker, snapshot, exportArn)));
return desc;
}
@@ -4972,20 +5016,14 @@ public class DynamoDbService {
private void runExport(ExportDescription desc, List<JsonNode> snapshot, String exportArn) {
try {
String s3Bucket = desc.getS3Bucket();
String s3Prefix = desc.getS3Prefix() != null ? desc.getS3Prefix() : "";
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
String dataFileUuid = UUID.randomUUID().toString();
String dataKey = (s3Prefix.isEmpty() ? "" : s3Prefix + "/")
+ "AWSDynamoDB/" + exportId + "/data/" + dataFileUuid + ".json.gz";
String manifestFilesKey = (s3Prefix.isEmpty() ? "" : s3Prefix + "/")
+ "AWSDynamoDB/" + exportId + "/manifest-files.json";
String manifestSummaryKey = (s3Prefix.isEmpty() ? "" : s3Prefix + "/")
+ "AWSDynamoDB/" + exportId + "/manifest-summary.json";
byte[] gzipData = buildGzipNdjson(snapshot);
String prefix = desc.getS3Prefix();
// AWS adds no slash after a prefix that ends with one.
String exportDir = (prefix == null ? "" : prefix.endsWith("/") ? prefix : prefix + "/")
+ "AWSDynamoDB/" + exportId + "/";
try {
s3Service.putObject(s3Bucket, dataKey, gzipData, "application/octet-stream", Map.of());
writeExportFile(s3Bucket, exportDir + "_started", new byte[0]);
} catch (AwsException e) {
if ("NoSuchBucket".equals(e.getErrorCode())) {
desc.setExportStatus("FAILED");
@@ -5000,33 +5038,28 @@ public class DynamoDbService {
throw e;
}
String md5 = computeMd5Hex(gzipData);
String etag = md5;
byte[] gzipData = buildGzipNdjson(snapshot);
String dataKey = exportDir + "data/" + exportFileName() + ".json.gz";
ObjectNode dataFile = objectMapper.createObjectNode();
dataFile.put("itemCount", snapshot.size());
dataFile.put("md5Checksum", Base64.getEncoder().encodeToString(Digests.md5(gzipData)));
dataFile.put("etag", writeExportFile(s3Bucket, dataKey, gzipData));
dataFile.put("dataFileS3Key", dataKey);
String manifestFilesKey = exportDir + "manifest-files.json";
writeExportManifest(s3Bucket, manifestFilesKey, objectMapper.writeValueAsString(dataFile) + "\n");
String manifestFilesContent = dataKey + "\n";
s3Service.putObject(s3Bucket, manifestFilesKey,
manifestFilesContent.getBytes(StandardCharsets.UTF_8),
"application/json", Map.of());
long billedSize = gzipData.length;
long itemCount = snapshot.size();
String manifestSummaryContent = buildManifestSummary(
desc, exportId, dataKey, itemCount, billedSize, md5, etag, manifestSummaryKey);
s3Service.putObject(s3Bucket, manifestSummaryKey,
manifestSummaryContent.getBytes(StandardCharsets.UTF_8),
"application/json", Map.of());
desc.setEndTime(epochSeconds(clock.instant()));
desc.setItemCount((long) snapshot.size());
desc.setBilledSizeBytes((long) gzipData.length);
String manifestSummaryKey = exportDir + "manifest-summary.json";
writeExportManifest(s3Bucket, manifestSummaryKey, manifestSummary(desc, manifestFilesKey));
desc.setExportStatus("COMPLETED");
desc.setEndTime(epochSeconds(clock.instant()));
desc.setItemCount(itemCount);
desc.setBilledSizeBytes(billedSize);
desc.setExportManifest(manifestSummaryKey);
if (exportStore != null) {
exportStore.put(exportArn, desc);
}
LOG.infov("Export completed: {0}, items={1}", exportArn, itemCount);
LOG.infov("Export completed: {0}, items={1}", exportArn, snapshot.size());
} catch (Exception e) {
LOG.errorv(e, "Export failed: {0}", exportArn);
@@ -5054,50 +5087,60 @@ public class DynamoDbService {
return baos.toByteArray();
}
private String computeMd5Hex(byte[] data) {
private static final DateTimeFormatter MANIFEST_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
/** AWS names a data file with 26 lower-case base32 characters. */
private static String exportFileName() {
UUID uuid = UUID.randomUUID();
byte[] bytes = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits()).array();
return Totp.base32Encode(bytes).toLowerCase(Locale.ROOT);
}
/** AWS uploads every export file in one part, so each ETag ends in "-1". */
private String writeExportFile(String bucket, String key, byte[] data) {
String uploadId = s3Service.initiateMultipartUpload(bucket, key, "application/octet-stream").getUploadId();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(data);
return HexFormat.of().formatHex(digest);
} catch (NoSuchAlgorithmException e) {
return "unknown";
s3Service.uploadPart(bucket, key, uploadId, 1, data);
String etag = s3Service.completeMultipartUpload(bucket, key, uploadId, List.of(1), null, null).getETag();
return etag.substring(1, etag.length() - 1);
} catch (RuntimeException e) {
try {
s3Service.abortMultipartUpload(bucket, key, uploadId);
} catch (RuntimeException abortFailure) {
LOG.warnv(abortFailure, "Could not abort the export upload of {0}/{1}", bucket, key);
}
throw e;
}
}
private String buildManifestSummary(ExportDescription desc, String exportId,
String dataKey, long itemCount, long billedSize,
String md5, String etag, String manifestSummaryKey) {
try {
ObjectNode root = objectMapper.createObjectNode();
root.put("version", "2020-06-30");
root.put("exportArn", desc.getExportArn());
root.put("startTime", instantOf(desc.getStartTime()).toString());
root.put("endTime", Instant.now().toString());
root.put("tableArn", desc.getTableArn());
root.put("tableId", desc.getTableId());
root.put("exportTime", instantOf(desc.getExportTime()).toString());
root.put("s3Bucket", desc.getS3Bucket());
root.putNull("s3Prefix");
if (desc.getS3Prefix() != null) {
root.put("s3Prefix", desc.getS3Prefix());
}
root.put("s3SseAlgorithm", desc.getS3SseAlgorithm() != null ? desc.getS3SseAlgorithm() : "AES256");
root.putNull("s3SseKmsKeyId");
root.put("exportFormat", desc.getExportFormat());
root.put("billedSizeBytes", billedSize);
root.put("itemCount", itemCount);
/** AWS writes the base64 MD5 of each manifest next to it. */
private void writeExportManifest(String bucket, String key, String content) {
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
writeExportFile(bucket, key, bytes);
writeExportFile(bucket, key.substring(0, key.length() - ".json".length()) + ".md5",
Base64.getEncoder().encodeToString(Digests.md5(bytes)).getBytes(StandardCharsets.UTF_8));
}
ArrayNode outputFiles = root.putArray("outputFiles");
ObjectNode fileEntry = outputFiles.addObject();
fileEntry.put("itemCount", itemCount);
fileEntry.put("md5Checksum", md5);
fileEntry.put("etag", etag);
fileEntry.put("dataFileS3Key", dataKey);
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
} catch (JsonProcessingException e) {
return "{}";
}
private String manifestSummary(ExportDescription desc, String manifestFilesKey) throws JsonProcessingException {
ObjectNode root = objectMapper.createObjectNode();
root.put("version", "2020-06-30");
root.put("exportArn", desc.getExportArn());
root.put("startTime", MANIFEST_TIME.format(instantOf(desc.getStartTime())));
root.put("endTime", MANIFEST_TIME.format(instantOf(desc.getEndTime())));
root.put("tableArn", desc.getTableArn());
root.put("tableId", desc.getTableId());
root.put("exportTime", MANIFEST_TIME.format(instantOf(desc.getExportTime())));
root.put("s3Bucket", desc.getS3Bucket());
root.put("s3Prefix", desc.getS3Prefix());
root.put("s3SseAlgorithm", desc.getS3SseAlgorithm());
root.putNull("s3SseKmsKeyId");
root.put("manifestFilesS3Key", manifestFilesKey);
root.put("billedSizeBytes", desc.getBilledSizeBytes());
root.put("itemCount", desc.getItemCount());
root.put("outputFormat", desc.getExportFormat());
return objectMapper.writeValueAsString(root);
}
public ExportDescription describeExport(String exportArn) {
@@ -69,6 +69,9 @@ public class ExportDescription {
@JsonProperty("FailureMessage")
private String failureMessage;
@JsonProperty("DestinationType")
private String destinationType = "S3";
public String getExportArn() { return exportArn; }
public void setExportArn(String exportArn) { this.exportArn = exportArn; }
@@ -125,4 +128,7 @@ public class ExportDescription {
public String getFailureMessage() { return failureMessage; }
public void setFailureMessage(String failureMessage) { this.failureMessage = failureMessage; }
public String getDestinationType() { return destinationType; }
public void setDestinationType(String destinationType) { this.destinationType = destinationType; }
}
@@ -19,12 +19,16 @@ public class ExportSummary {
@JsonProperty("ExportType")
private String exportType;
@JsonProperty("DestinationType")
private String destinationType;
public ExportSummary() {}
public ExportSummary(ExportDescription desc) {
this.exportArn = desc.getExportArn();
this.exportStatus = desc.getExportStatus();
this.exportType = desc.getExportType();
this.exportType = desc.getExportType() != null ? desc.getExportType() : "FULL_EXPORT";
this.destinationType = desc.getDestinationType();
}
public String getExportArn() { return exportArn; }
@@ -35,4 +39,7 @@ public class ExportSummary {
public String getExportType() { return exportType; }
public void setExportType(String exportType) { this.exportType = exportType; }
public String getDestinationType() { return destinationType; }
public void setDestinationType(String destinationType) { this.destinationType = destinationType; }
}
@@ -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,