feat(dynamodb): export tables in the ION format (#6429)

* feat(dynamodb): export tables in the ION format

* chore(dynamodb): check the ION export file without polling

* chore(dynamodb): share the export file reader in the compatibility test
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-24 18:25:41 -04:00
1 parent 72bbc809b4
commit ed21e67cd4
7 files changed
+400 -69

No files matched your search

@@ -0,0 +1,140 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import java.math.BigDecimal;
import java.util.HexFormat;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
/**
* Writes items as the Ion text of an ION export. AWS prints them with the standard text writer of
* ion-java, so this follows its quoting, escapes and decimal forms.
*/
final class DynamoDbIonText {
private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_$][A-Za-z0-9_$]*");
/** Ion reads these as symbol ids, so they are quoted like the keywords. */
private static final Pattern SYMBOL_ID = Pattern.compile("\\$[0-9]+");
private static final Set<String> KEYWORDS = Set.of("null", "true", "false", "nan");
private DynamoDbIonText() {}
/** One line of a full export, without its newline. */
static String exportLine(JsonNode item) {
StringBuilder out = new StringBuilder("$ion_1_0 {Item:");
appendStruct(out, item);
return out.append('}').toString();
}
private static void appendStruct(StringBuilder out, JsonNode attributes) {
out.append('{');
String separator = "";
for (Map.Entry<String, JsonNode> attribute : attributes.properties()) {
out.append(separator);
separator = ",";
appendFieldName(out, attribute.getKey());
out.append(':');
appendValue(out, attribute.getValue());
}
out.append('}');
}
private static void appendValue(StringBuilder out, JsonNode value) {
Map.Entry<String, JsonNode> typed = value.properties().iterator().next();
JsonNode content = typed.getValue();
switch (typed.getKey()) {
case "S" -> appendString(out, content);
case "N" -> appendDecimal(out, content);
case "B" -> appendBlob(out, content);
case "BOOL" -> out.append(content.asBoolean());
case "NULL" -> out.append("null");
case "SS" -> appendList(out.append("$dynamodb_SS::"), content, DynamoDbIonText::appendString);
case "NS" -> appendList(out.append("$dynamodb_NS::"), content, DynamoDbIonText::appendDecimal);
case "BS" -> appendList(out.append("$dynamodb_BS::"), content, DynamoDbIonText::appendBlob);
case "L" -> appendList(out, content, DynamoDbIonText::appendValue);
case "M" -> appendStruct(out, content);
default -> throw new IllegalArgumentException("Unknown attribute type: " + typed.getKey());
}
}
private static void appendList(StringBuilder out, JsonNode members, BiConsumer<StringBuilder, JsonNode> appendMember) {
out.append('[');
String separator = "";
for (JsonNode member : members) {
out.append(separator);
separator = ",";
appendMember.accept(out, member);
}
out.append(']');
}
private static void appendFieldName(StringBuilder out, String name) {
if (IDENTIFIER.matcher(name).matches() && !KEYWORDS.contains(name) && !SYMBOL_ID.matcher(name).matches()) {
out.append(name);
} else {
out.append('\'');
appendEscaped(out, name, '\'');
out.append('\'');
}
}
private static void appendString(StringBuilder out, JsonNode text) {
out.append('"');
appendEscaped(out, text.asText(), '"');
out.append('"');
}
private static void appendEscaped(StringBuilder out, String text, char quote) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
switch (c) {
case 0 -> out.append("\\0");
case 7 -> out.append("\\a");
case '\b' -> out.append("\\b");
case '\t' -> out.append("\\t");
case '\n' -> out.append("\\n");
case 0x0B -> out.append("\\v");
case '\f' -> out.append("\\f");
case '\r' -> out.append("\\r");
case '\\' -> out.append("\\\\");
default -> {
if (c == quote) {
out.append('\\').append(c);
} else if (c < 0x20 || (0x7F <= c && c <= 0x9F)) {
out.append("\\x").append(HexFormat.of().toHexDigits((byte) c));
} else {
out.append(c);
}
}
}
}
}
private static void appendDecimal(StringBuilder out, JsonNode number) {
BigDecimal value = new BigDecimal(number.asText()).stripTrailingZeros();
if (value.signum() < 0) {
out.append('-');
}
String digits = value.unscaledValue().abs().toString();
int scale = value.scale();
if (scale < 0) {
out.append(digits).append('d').append(-scale);
} else if (scale == 0) {
out.append(digits).append('.');
} else if (scale < digits.length()) {
int whole = digits.length() - scale;
out.append(digits, 0, whole).append('.').append(digits, whole, digits.length());
} else if (scale <= digits.length() + 5) {
out.append("0.").append("0".repeat(scale - digits.length())).append(digits);
} else {
out.append(digits).append("d-").append(scale);
}
}
private static void appendBlob(StringBuilder out, JsonNode base64) {
out.append("{{").append(base64.asText()).append("}}");
}
}
@@ -4918,37 +4918,39 @@ public class DynamoDbService {
// --- Export Operations ---
private static final List<String> EXPORT_FORMATS = List.of("ION", "DYNAMODB_JSON");
/** As on AWS, an ExportTime after LatestRestorableDateTime is accepted up to now. */
public ExportDescription exportTable(Map<String, Object> request, Instant exportTime, String region) {
String tableArn = (String) request.get("TableArn");
String s3Bucket = (String) request.get("S3Bucket");
String s3Prefix = request.containsKey("S3Prefix") ? (String) request.get("S3Prefix") : null;
String exportFormat = request.containsKey("ExportFormat") ? (String) request.get("ExportFormat") : "DYNAMODB_JSON";
String exportFormat = request.get("ExportFormat") != null ? (String) request.get("ExportFormat") : "DYNAMODB_JSON";
String exportType = request.containsKey("ExportType") ? (String) request.get("ExportType") : "FULL_EXPORT";
String clientToken = request.containsKey("ClientToken") ? (String) request.get("ClientToken") : null;
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);
}
List<String> violations = new ArrayList<>();
if (s3Prefix != null && 1024 < s3Prefix.codePointCount(0, s3Prefix.length())) {
violations.add("Value '" + s3Prefix
+ "' at 's3Prefix' failed to satisfy constraint: Member must have length less than or equal to 1024");
}
if (!EXPORT_FORMATS.contains(exportFormat)) {
violations.add(SmithyValidationErrors.notInEnum(exportFormat, "exportFormat", EXPORT_FORMATS));
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
if (s3Prefix != null && s3Prefix.codePointCount(0, s3Prefix.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);
}
if ("ION".equals(exportFormat)) {
throw new AwsException("ValidationException",
"ExportFormat ION is not supported", 400);
}
DynamoDbTableNames.ResolvedTableRef ref = DynamoDbTableNames.resolveWithRegion(tableArn, region);
String tableName = ref.name();
@@ -5037,8 +5039,9 @@ public class DynamoDbService {
throw e;
}
byte[] gzipData = buildGzipNdjson(snapshot);
String dataKey = exportDir + "data/" + exportFileName() + ".json.gz";
boolean ion = "ION".equals(desc.getExportFormat());
byte[] gzipData = buildGzipExportData(snapshot, ion);
String dataKey = exportDir + "data/" + exportFileName() + (ion ? ".ion.gz" : ".json.gz");
ObjectNode dataFile = objectMapper.createObjectNode();
dataFile.put("itemCount", snapshot.size());
dataFile.put("md5Checksum", Base64.getEncoder().encodeToString(Digests.md5(gzipData)));
@@ -5072,14 +5075,18 @@ public class DynamoDbService {
}
}
private byte[] buildGzipNdjson(List<JsonNode> items) throws IOException {
private byte[] buildGzipExportData(List<JsonNode> items, boolean ion) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(baos)) {
for (JsonNode item : items) {
ObjectNode line = objectMapper.createObjectNode();
line.set("Item", item);
byte[] lineBytes = objectMapper.writeValueAsBytes(line);
gzip.write(lineBytes);
if (ion) {
gzip.write(DynamoDbIonText.exportLine(item).getBytes(StandardCharsets.UTF_8));
} else {
ObjectNode line = objectMapper.createObjectNode();
line.set("Item", item);
byte[] lineBytes = objectMapper.writeValueAsBytes(line);
gzip.write(lineBytes);
}
gzip.write('\n');
}
}