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

@@ -176,21 +176,23 @@ class DynamoDbExportIntegrationTest {
}
@Test
void exportTableToPointInTime_ionFormat_returnsValidationException() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.ExportTableToPointInTime")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableArn": "%s",
"S3Bucket": "%s",
"ExportFormat": "ION"
}
""".formatted(TABLE_ARN, BUCKET_NAME))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"));
void exportFormatIsCheckedAsAwsChecksIt() {
String enumSet = "' at 'exportFormat' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [ION, DYNAMODB_JSON]";
expectError(ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "ExportFormat": "ion", "S3Prefix": "x"}
""".formatted(TABLE_ARN_PREFIX + "ExportFormatMissing", BUCKET_NAME)), "ValidationException",
"1 validation error detected: Value 'ion" + enumSet);
String over1024 = "a".repeat(1025);
expectError(ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "ExportFormat": "", "S3Prefix": "%s"}
""".formatted(TABLE_ARN, BUCKET_NAME, over1024)), "ValidationException",
"2 validation errors detected: Value '" + over1024 + "' at 's3Prefix' failed to satisfy constraint: "
+ "Member must have length less than or equal to 1024; Value '" + enumSet);
ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "S3Prefix": "exports-ion", "ExportFormat": "ION"}
""".formatted(TABLE_ARN, BUCKET_NAME)).statusCode(200)
.body("ExportDescription.ExportFormat", equalTo("ION"));
}
@Test
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.amazon.ion.IonType;
import com.amazon.ion.IonWriter;
import com.amazon.ion.system.IonTextWriterBuilder;
import com.amazon.ion.system.IonWriterBuilder.InitialIvmHandling;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DynamoDbIonTextTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void exportLineIsTheLineAwsWrites() throws IOException {
JsonNode item = MAPPER.readTree("""
{"pk": {"S": "types"}, "sk": {"N": "1"}, "b": {"B": "AAEC/w=="}, "n_lead": {"N": "007"},
"ns": {"NS": ["2.50", "1E+3", "3", "1"]}, "null": {"S": "kw null"}, "true": {"S": "kw true"},
"s_unicode": {"S": "日本語 é 😀"},
"l": {"L": [{"S": "x"}, {"N": "1"}, {"BOOL": true}, {"NULL": true}, {"L": []}, {"M": {}},
{"M": {"a": {"N": "1"}}}, {"SS": ["z"]}]},
"s_empty": {"S": ""}, "m": {"M": {"a-b": {"N": "1"}, "nested": {"M": {"deeper": {"S": "v"}}}}},
"bool_t": {"BOOL": true}, "n_int": {"N": "103"}, "bs": {"BS": ["AA==", "eA=="]}, "s": {"S": "hello"},
"a-b": {"S": "dash"}, "$x": {"S": "dollar"}, "n_zero": {"N": "0"},
"n_38": {"N": "12345678901234567890123456789012345678"}, "n_trail": {"N": "123.4500"},
"s_quote": {"S": "he said \\"hi\\"\\n\\ttab \\\\ back 'single'"}, "n_point": {"N": "10.0"},
"n_2000": {"N": "2000"}, "m_empty": {"M": {}}, "ss": {"SS": ["a", "b", "c d"]},
"n_big": {"N": "1E+125"}, "bool_f": {"BOOL": false}, "$10": {"S": "dollar digits"},
"with space": {"S": "sp"}, "n_frac": {"N": "0.5"}, "nul": {"NULL": true}, "n_small": {"N": "1E-130"},
"n_600": {"N": "600"}, "'q": {"S": "quote"}, "b_empty": {"B": ""}, "n_negfrac": {"N": "-0.001"},
"n_neg": {"N": "-1"}, "n_e": {"N": "1.5e3"}, "+inf": {"S": "inf"},
"s_ctrl": {"S": "\\u0001\\u001f\\u007f\\u0080"}, "a.b": {"N": "2"}, "日本": {"S": "jp"},
"Upper": {"S": "upper"}, "1abc": {"S": "digit"}, "_u": {"S": "underscore"}, "l_empty": {"L": []},
"nan": {"S": "kw nan"}, "false": {"S": "kw false"}}
""");
assertEquals("""
$ion_1_0 {Item:{pk:"types",sk:1.,b:{{AAEC/w==}},n_lead:7.,ns:$dynamodb_NS::[2.5,1d3,3.,1.],\
'null':"kw null",'true':"kw true",s_unicode:"日本語 é 😀",\
l:["x",1.,true,null,[],{},{a:1.},$dynamodb_SS::["z"]],s_empty:"",m:{'a-b':1.,nested:{deeper:"v"}},\
bool_t:true,n_int:103.,bs:$dynamodb_BS::[{{AA==}},{{eA==}}],s:"hello",'a-b':"dash",$x:"dollar",\
n_zero:0.,n_38:12345678901234567890123456789012345678.,n_trail:123.45,\
s_quote:"he said \\"hi\\"\\n\\ttab \\\\ back 'single'",n_point:1d1,n_2000:2d3,m_empty:{},\
ss:$dynamodb_SS::["a","b","c d"],n_big:1d125,bool_f:false,'$10':"dollar digits",'with space':"sp",\
n_frac:0.5,nul:null,n_small:1d-130,n_600:6d2,'\\'q':"quote",b_empty:{{}},n_negfrac:-0.001,n_neg:-1.,\
n_e:15d2,'+inf':"inf",s_ctrl:"\\x01\\x1f\\x7f\\x80",'a.b':2.,'日本':"jp",Upper:"upper",'1abc':"digit",\
_u:"underscore",l_empty:[],'nan':"kw nan",'false':"kw false"}}""", DynamoDbIonText.exportLine(item));
}
@Test
void exportLineIsWhatIonJavaWrites() throws IOException {
JsonNode item = MAPPER.readTree("""
{"pk": {"S": "edge"}, "$": {"S": "lone dollar"}, "$0": {"S": "symbol id"}, "nulls": {"S": "no keyword"},
"NULL": {"S": "upper case"}, "+-": {"S": "operators"}, "tab\\tname": {"S": "t"},
"quote\\"name": {"S": "q"}, "back\\\\slash": {"S": "b"}, "é": {"S": "latin"}, "😀": {"S": "emoji"},
"ctrl": {"S": "\\u0000\\u0007\\b\\t\\n\\u000b\\f\\r\\u001b\\u007f\\u009f\\u00a0\\u00ff\\u0100 😀 ' \\""},
"numbers": {"NS": ["0", "-0", "0.000001", "0.0000001", "123456.789", "-1E+125", "1E-130", "-1E-130",
"9.9999999999999999999999999999999999999E+125", "100", "0.1", "12.0", "-12.5"]},
"nested": {"L": [{"L": [{"M": {"x y": {"SS": ["'", "\\""]}}}]}, {"BS": ["", "AAEC/w=="]}]},
"blob": {"B": "////"}}
""");
assertEquals(ionJava(item), DynamoDbIonText.exportLine(item));
}
private static String ionJava(JsonNode item) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (IonWriter writer = IonTextWriterBuilder.standard().withInitialIvmHandling(InitialIvmHandling.ENSURE).build(out)) {
writer.stepIn(IonType.STRUCT);
writer.setFieldName("Item");
writeStruct(writer, item);
writer.stepOut();
}
return out.toString(StandardCharsets.UTF_8);
}
private static void writeStruct(IonWriter writer, JsonNode attributes) throws IOException {
writer.stepIn(IonType.STRUCT);
for (Map.Entry<String, JsonNode> attribute : attributes.properties()) {
writer.setFieldName(attribute.getKey());
writeValue(writer, attribute.getValue());
}
writer.stepOut();
}
private static void writeValue(IonWriter writer, JsonNode value) throws IOException {
Map.Entry<String, JsonNode> typed = value.properties().iterator().next();
JsonNode content = typed.getValue();
switch (typed.getKey()) {
case "S" -> writer.writeString(content.asText());
case "N" -> writer.writeDecimal(new BigDecimal(content.asText()).stripTrailingZeros());
case "B" -> writer.writeBlob(Base64.getDecoder().decode(content.asText()));
case "BOOL" -> writer.writeBool(content.asBoolean());
case "NULL" -> writer.writeNull();
case "SS", "NS", "BS" -> {
writer.setTypeAnnotations("$dynamodb_" + typed.getKey());
writer.stepIn(IonType.LIST);
for (JsonNode member : content) {
writeValue(writer, MAPPER.createObjectNode().set(typed.getKey().substring(0, 1), member));
}
writer.stepOut();
}
case "L" -> {
writer.stepIn(IonType.LIST);
for (JsonNode member : content) {
writeValue(writer, member);
}
writer.stepOut();
}
case "M" -> writeStruct(writer, content);
default -> throw new IllegalArgumentException(typed.getKey());
}
}
}
@@ -49,6 +49,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.*;
@@ -4532,11 +4533,7 @@ class DynamoDbServiceTest {
@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\""));
S3Service s3 = exportBucket();
DynamoDbService svc = inlineExportService(s3);
String longest = "a".repeat(948);
@@ -4554,6 +4551,43 @@ class DynamoDbServiceTest {
.mapToInt(key -> key.getBytes(StandardCharsets.UTF_8).length).max().orElseThrow());
}
@Test
void ionExportWritesIonLines() throws Exception {
S3Service s3 = exportBucket();
DynamoDbService svc = inlineExportService(s3);
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();
ExportDescription described = svc.describeExport(exportArn);
assertEquals("COMPLETED", described.getExportStatus());
assertEquals("ION", described.getExportFormat());
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));
}
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. */
private static S3Service exportBucket() {
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\""));
return s3;
}
/** 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<>(),