mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
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:
1 parent
9242c7003a
commit
3dc5d356d0
13 files changed
+796
-60
No files matched your search
@@ -0,0 +1,98 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPointInTimeRecovery.ItemChange;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** The records of an incremental export. AWS sorts the attribute names and set members in them. */
|
||||
final class DynamoDbExportRecords {
|
||||
|
||||
private static final JsonNodeFactory NODES = JsonNodeFactory.instance;
|
||||
/** AWS sorts by code point, which String.compareTo does not do above U+FFFF. */
|
||||
private static final Comparator<String> CODE_POINT_ORDER =
|
||||
(a, b) -> Arrays.compare(a.codePoints().toArray(), b.codePoints().toArray());
|
||||
|
||||
private DynamoDbExportRecords() {}
|
||||
|
||||
/** A record for each item whose value at the end differs from its value at the start. */
|
||||
static List<JsonNode> records(List<ItemChange> changes, TableDefinition table, boolean newImageOnly) {
|
||||
List<String> keyNames = new ArrayList<>();
|
||||
keyNames.add(table.getPartitionKeyName());
|
||||
if (table.getSortKeyName() != null) {
|
||||
keyNames.add(table.getSortKeyName());
|
||||
}
|
||||
List<JsonNode> records = new ArrayList<>();
|
||||
for (ItemChange change : changes) {
|
||||
ObjectNode oldImage = change.oldItem() != null ? sortedAttributes(change.oldItem()) : null;
|
||||
ObjectNode newImage = change.newItem() != null ? sortedAttributes(change.newItem()) : null;
|
||||
if (Objects.equals(oldImage, newImage)) {
|
||||
continue;
|
||||
}
|
||||
JsonNode item = newImage != null ? newImage : oldImage;
|
||||
ObjectNode record = NODES.objectNode();
|
||||
record.putObject("Metadata").putObject("WriteTimestampMicros")
|
||||
.put("N", String.valueOf(ChronoUnit.MICROS.between(Instant.EPOCH, change.lastWrite())));
|
||||
ObjectNode keys = NODES.objectNode();
|
||||
for (String keyName : keyNames) {
|
||||
keys.set(keyName, item.get(keyName));
|
||||
}
|
||||
record.set("Keys", sortedAttributes(keys));
|
||||
if (oldImage != null && !newImageOnly) {
|
||||
record.set("OldImage", oldImage);
|
||||
}
|
||||
if (newImage != null) {
|
||||
record.set("NewImage", newImage);
|
||||
}
|
||||
records.add(record);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
private static ObjectNode sortedAttributes(JsonNode attributes) {
|
||||
Map<String, JsonNode> byName = new TreeMap<>(CODE_POINT_ORDER);
|
||||
attributes.properties().forEach(attribute -> byName.put(attribute.getKey(), attribute.getValue()));
|
||||
ObjectNode sorted = NODES.objectNode();
|
||||
byName.forEach((name, value) -> sorted.set(name, sortedValue(value)));
|
||||
return sorted;
|
||||
}
|
||||
|
||||
private static JsonNode sortedValue(JsonNode value) {
|
||||
Map.Entry<String, JsonNode> typed = value.properties().iterator().next();
|
||||
JsonNode content = typed.getValue();
|
||||
return switch (typed.getKey()) {
|
||||
case "M" -> NODES.objectNode().set("M", sortedAttributes(content));
|
||||
case "L" -> {
|
||||
ArrayNode members = NODES.arrayNode();
|
||||
content.forEach(member -> members.add(sortedValue(member)));
|
||||
yield NODES.objectNode().set("L", members);
|
||||
}
|
||||
case "SS" -> sortedSet("SS", content, Comparator.comparing(JsonNode::asText, CODE_POINT_ORDER));
|
||||
case "NS" -> sortedSet("NS", content, Comparator.comparing(member -> new BigDecimal(member.asText())));
|
||||
case "BS" -> sortedSet("BS", content, (a, b) -> Arrays.compareUnsigned(
|
||||
Base64.getDecoder().decode(a.asText()), Base64.getDecoder().decode(b.asText())));
|
||||
default -> value;
|
||||
};
|
||||
}
|
||||
|
||||
private static JsonNode sortedSet(String type, JsonNode members, Comparator<JsonNode> order) {
|
||||
List<JsonNode> sorted = new ArrayList<>();
|
||||
members.forEach(sorted::add);
|
||||
sorted.sort(order);
|
||||
return NODES.objectNode().set(type, NODES.arrayNode().addAll(sorted));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
@@ -19,6 +20,7 @@ final class DynamoDbIonText {
|
||||
/** 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 static final List<String> RECORD_PARTS = List.of("Keys", "Metadata", "OldImage", "NewImage");
|
||||
|
||||
private DynamoDbIonText() {}
|
||||
|
||||
@@ -29,6 +31,20 @@ final class DynamoDbIonText {
|
||||
return out.append('}').toString();
|
||||
}
|
||||
|
||||
/** One line of an incremental export, without its newline. AWS puts Keys before Metadata here. */
|
||||
static String recordLine(JsonNode record) {
|
||||
StringBuilder out = new StringBuilder("$ion_1_0 {Record:{");
|
||||
String separator = "";
|
||||
for (String part : RECORD_PARTS) {
|
||||
if (record.has(part)) {
|
||||
out.append(separator).append(part).append(':');
|
||||
separator = ",";
|
||||
appendStruct(out, record.get(part));
|
||||
}
|
||||
}
|
||||
return out.append("}}").toString();
|
||||
}
|
||||
|
||||
private static void appendStruct(StringBuilder out, JsonNode attributes) {
|
||||
out.append('{');
|
||||
String separator = "";
|
||||
|
||||
+61
@@ -14,10 +14,13 @@ import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The change history behind point-in-time recovery. A change keeps what it replaced, so a table at
|
||||
@@ -28,6 +31,9 @@ final class DynamoDbPointInTimeRecovery {
|
||||
|
||||
record RestoreWindow(Instant earliest, Instant latest) {}
|
||||
|
||||
/** {@code oldItem} or {@code newItem} is null when the item did not exist then. */
|
||||
record ItemChange(JsonNode oldItem, JsonNode newItem, Instant lastWrite) {}
|
||||
|
||||
/** The changes of one table, oldest first. */
|
||||
private static final class Changes {
|
||||
private final List<PointInTimeChange> list = new ArrayList<>();
|
||||
@@ -139,6 +145,61 @@ final class DynamoDbPointInTimeRecovery {
|
||||
return new ArrayList<>(items.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Each item written from {@code from} until before {@code to}, in the order of its first write
|
||||
* there, with its values before and after those writes. {@code underItemLock} runs a read under
|
||||
* the lock that a writer of the item holds from recording its change until the item is written.
|
||||
*/
|
||||
List<ItemChange> changesBetween(String accountId, String storageKey, Map<String, JsonNode> liveItems,
|
||||
Instant from, Instant to,
|
||||
BiFunction<String, Supplier<JsonNode>, JsonNode> underItemLock) {
|
||||
Changes changes = changesByTable.get(key(accountId, storageKey));
|
||||
if (changes == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, JsonNode> before = new LinkedHashMap<>();
|
||||
Map<String, Instant> lastWrites = new HashMap<>();
|
||||
Map<String, JsonNode> after = new HashMap<>();
|
||||
long seen;
|
||||
synchronized (changes) {
|
||||
seen = changes.nextSequence;
|
||||
for (PointInTimeChange change : changes.list) {
|
||||
String itemKey = change.getItemKey();
|
||||
if (change.getTime().isBefore(from)) {
|
||||
continue;
|
||||
}
|
||||
if (change.getTime().isBefore(to)) {
|
||||
if (!before.containsKey(itemKey)) {
|
||||
before.put(itemKey, change.getOldItem());
|
||||
}
|
||||
lastWrites.put(itemKey, change.getTime());
|
||||
} else if (before.containsKey(itemKey) && !after.containsKey(itemKey)) {
|
||||
after.put(itemKey, change.getOldItem());
|
||||
}
|
||||
}
|
||||
}
|
||||
List<ItemChange> result = new ArrayList<>();
|
||||
before.forEach((itemKey, oldItem) -> {
|
||||
JsonNode newItem = after.containsKey(itemKey) ? after.get(itemKey)
|
||||
: underItemLock.apply(itemKey, () -> valueBefore(changes, itemKey, seen, liveItems));
|
||||
result.add(new ItemChange(oldItem, newItem, lastWrites.get(itemKey)));
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The value that the first change of the item from sequence {@code since} replaced, or the live item. */
|
||||
private static JsonNode valueBefore(Changes changes, String itemKey, long since, Map<String, JsonNode> liveItems) {
|
||||
synchronized (changes) {
|
||||
JsonNode value = liveItems.get(itemKey);
|
||||
for (int i = changes.list.size() - 1; 0 <= i && since <= changes.list.get(i).getSequence(); i--) {
|
||||
if (changes.list.get(i).getItemKey().equals(itemKey)) {
|
||||
value = changes.list.get(i).getOldItem();
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
private void put(String accountId, String storageKey, PointInTimeChange change) {
|
||||
String key = storageKey + "#" + change.getSequence();
|
||||
if (store instanceof AccountAwareStorageBackend<PointInTimeChange> aware) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.json.JsonWriteFeature;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
@@ -29,6 +31,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.ExportSummary;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.ImportSummary;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.ImportTableDescription;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.IncrementalExportSpecification;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.PointInTimeChange;
|
||||
@@ -4921,24 +4924,43 @@ public class DynamoDbService {
|
||||
// --- Export Operations ---
|
||||
|
||||
private static final List<String> EXPORT_FORMATS = List.of("ION", "DYNAMODB_JSON");
|
||||
private static final List<String> EXPORT_TYPES = List.of("FULL_EXPORT", "INCREMENTAL_EXPORT");
|
||||
private static final List<String> EXPORT_VIEW_TYPES = List.of("NEW_AND_OLD_IMAGES", "NEW_IMAGE");
|
||||
private static final List<String> S3_SSE_ALGORITHMS = List.of("AES256", "KMS");
|
||||
private static final Duration MIN_INCREMENTAL_EXPORT_PERIOD = Duration.ofMinutes(15);
|
||||
private static final Duration MAX_INCREMENTAL_EXPORT_PERIOD = Duration.ofHours(24);
|
||||
|
||||
/** The IncrementalExportSpecification of a request. A member it leaves out is null. */
|
||||
public record IncrementalExportRequest(Instant from, Instant to, String viewType) {}
|
||||
|
||||
/** As on AWS, an ExportTime after LatestRestorableDateTime is accepted up to now. */
|
||||
public ExportDescription exportTable(Map<String, Object> request, Instant exportTime, String region) {
|
||||
public ExportDescription exportTable(Map<String, Object> request, Instant exportTime,
|
||||
IncrementalExportRequest incremental, 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.get("ExportFormat") != null ? (String) request.get("ExportFormat") : "DYNAMODB_JSON";
|
||||
String exportType = request.containsKey("ExportType") ? (String) request.get("ExportType") : "FULL_EXPORT";
|
||||
String exportType = (String) request.get("ExportType");
|
||||
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;
|
||||
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (s3SseAlgorithm != null && !S3_SSE_ALGORITHMS.contains(s3SseAlgorithm)) {
|
||||
violations.add(SmithyValidationErrors.notInEnum(s3SseAlgorithm, "s3SseAlgorithm", S3_SSE_ALGORITHMS));
|
||||
}
|
||||
String prefixLengthViolation = s3Prefix == null ? null
|
||||
: SmithyValidationErrors.lengthOutOfRange("s3Prefix", s3Prefix, 0, 1024);
|
||||
if (prefixLengthViolation != null) {
|
||||
violations.add(prefixLengthViolation);
|
||||
}
|
||||
if (exportType != null && !EXPORT_TYPES.contains(exportType)) {
|
||||
violations.add(SmithyValidationErrors.notInEnum(exportType, "exportType", EXPORT_TYPES));
|
||||
}
|
||||
if (incremental != null && incremental.viewType() != null && !EXPORT_VIEW_TYPES.contains(incremental.viewType())) {
|
||||
violations.add(SmithyValidationErrors.notInEnum(incremental.viewType(),
|
||||
"incrementalExportSpecification.exportViewType", EXPORT_VIEW_TYPES));
|
||||
}
|
||||
if (!EXPORT_FORMATS.contains(exportFormat)) {
|
||||
violations.add(SmithyValidationErrors.notInEnum(exportFormat, "exportFormat", EXPORT_FORMATS));
|
||||
}
|
||||
@@ -4951,10 +4973,6 @@ public class DynamoDbService {
|
||||
throw new AwsException("ValidationException", "Invalid Request: "
|
||||
+ SmithyValidationErrors.message(List.of(prefixLengthViolation)), 400);
|
||||
}
|
||||
if ("INCREMENTAL_EXPORT".equals(exportType)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"ExportType INCREMENTAL_EXPORT is not supported", 400);
|
||||
}
|
||||
|
||||
DynamoDbTableNames.ResolvedTableRef ref = DynamoDbTableNames.resolveWithRegion(tableArn, region);
|
||||
String tableName = ref.name();
|
||||
@@ -4962,24 +4980,49 @@ public class DynamoDbService {
|
||||
String storageKey = regionKey(tableRegion, tableName);
|
||||
|
||||
TableDefinition table = requireBackupSource(storageKey, tableArn);
|
||||
boolean incrementalExport = "INCREMENTAL_EXPORT".equals(exportType);
|
||||
if (incrementalExport && incremental == null) {
|
||||
throw invalidExportRequest("Incremental Export Specification expected when export type is set as Incremental Export");
|
||||
}
|
||||
if (!incrementalExport && incremental != null) {
|
||||
throw invalidExportRequest(exportType == null
|
||||
? "Export Type expected to be Incremental Export when incremental export specification is provided"
|
||||
: "When Export Type is Full Export , Incremental Export Specification should not be provided");
|
||||
}
|
||||
if (incrementalExport && incremental.from() == null) {
|
||||
throw invalidExportRequest("ExportFromTime must be provided in IncrementalExportSpecification");
|
||||
}
|
||||
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);
|
||||
Instant now = clock.instant();
|
||||
// AWS cannot enable point-in-time recovery until seconds after the creation, so its
|
||||
// EarliestRestorableDateTime is never in the creation second.
|
||||
if (exportTime != null && (exportTime.isBefore(table.getCreationDateTime().truncatedTo(ChronoUnit.SECONDS))
|
||||
|| startTime.isBefore(exportTime))) {
|
||||
throw new AwsException("InvalidExportTimeException", "Export Time is invalid", 400);
|
||||
Instant creationSecond = table.getCreationDateTime().truncatedTo(ChronoUnit.SECONDS);
|
||||
Instant startTime;
|
||||
Instant exportFromTime = null;
|
||||
Instant exportToTime = null;
|
||||
if (incrementalExport) {
|
||||
startTime = now.truncatedTo(ChronoUnit.SECONDS);
|
||||
exportFromTime = incremental.from();
|
||||
exportToTime = incremental.to() != null ? incremental.to() : startTime;
|
||||
checkIncrementalExportPeriod(exportFromTime, exportToTime, creationSecond, now);
|
||||
} else {
|
||||
startTime = now.truncatedTo(ChronoUnit.MILLIS);
|
||||
if (exportTime != null && (exportTime.isBefore(creationSecond) || startTime.isBefore(exportTime))) {
|
||||
throw new AwsException("InvalidExportTimeException", "Export Time is invalid", 400);
|
||||
}
|
||||
}
|
||||
if (!table.isPointInTimeRecoveryEnabled()) {
|
||||
throw new AwsException("PointInTimeRecoveryUnavailableException",
|
||||
"Point in time recovery is not enabled for table '" + table.getTableName() + "'", 400);
|
||||
}
|
||||
if (exportTime != null
|
||||
&& exportTime.isBefore(pointInTimeRecovery.window(withPointInTimeStart(storageKey, table)).earliest())) {
|
||||
throw new AwsException("InvalidExportTimeException",
|
||||
"Point in Time Recovery is not available for specified export time", 400);
|
||||
Instant readFrom = incrementalExport ? exportFromTime : exportTime;
|
||||
if (readFrom != null
|
||||
&& readFrom.isBefore(pointInTimeRecovery.window(withPointInTimeStart(storageKey, table)).earliest())) {
|
||||
throw new AwsException("InvalidExportTimeException", incrementalExport
|
||||
? "Export period from time cannot be earlier than the Point in Time Recovery window"
|
||||
: "Point in Time Recovery is not available for specified export time", 400);
|
||||
}
|
||||
Instant time = exportTime != null ? exportTime : startTime;
|
||||
|
||||
@@ -4994,8 +5037,13 @@ public class DynamoDbService {
|
||||
desc.setS3Bucket(s3Bucket);
|
||||
desc.setS3Prefix(s3Prefix);
|
||||
desc.setExportFormat(exportFormat);
|
||||
desc.setExportType((String) request.get("ExportType"));
|
||||
desc.setExportTime(epochSeconds(time));
|
||||
desc.setExportType(exportType);
|
||||
if (incrementalExport) {
|
||||
desc.setIncrementalExportSpecification(new IncrementalExportSpecification(epochSeconds(exportFromTime),
|
||||
epochSeconds(exportToTime), incremental.viewType() != null ? incremental.viewType() : "NEW_AND_OLD_IMAGES"));
|
||||
} else {
|
||||
desc.setExportTime(epochSeconds(time));
|
||||
}
|
||||
desc.setStartTime(epochSeconds(startTime));
|
||||
desc.setClientToken(clientToken);
|
||||
desc.setS3SseAlgorithm(s3SseAlgorithm != null ? s3SseAlgorithm : "AES256");
|
||||
@@ -5006,8 +5054,13 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
ConcurrentSkipListMap<String, JsonNode> tableItems = itemsByTable.get(scopedItemsKey(storageKey));
|
||||
List<JsonNode> snapshot = pointInTimeRecovery.itemsAt(regionResolver.getAccountId(), storageKey,
|
||||
tableItems != null ? tableItems : Map.of(), time);
|
||||
Map<String, JsonNode> liveItems = tableItems != null ? tableItems : Map.of();
|
||||
List<JsonNode> snapshot = incrementalExport
|
||||
? DynamoDbExportRecords.records(pointInTimeRecovery.changesBetween(regionResolver.getAccountId(),
|
||||
storageKey, liveItems, exportFromTime, exportToTime,
|
||||
(itemKey, read) -> withItemLock(storageKey, itemKey, read)), table,
|
||||
"NEW_IMAGE".equals(incremental.viewType()))
|
||||
: pointInTimeRecovery.itemsAt(regionResolver.getAccountId(), storageKey, liveItems, time);
|
||||
|
||||
// The worker gets its own copy so the object serialized into this response never
|
||||
// changes underneath the handler, and the request account so its writes land there.
|
||||
@@ -5018,14 +5071,16 @@ public class DynamoDbService {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/** AWS puts an incremental export's data files in a data folder that all its exports share. */
|
||||
private void runExport(ExportDescription desc, List<JsonNode> snapshot, String exportArn) {
|
||||
try {
|
||||
String s3Bucket = desc.getS3Bucket();
|
||||
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
|
||||
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 + "/";
|
||||
String exportRoot = (prefix == null ? "" : prefix.endsWith("/") ? prefix : prefix + "/") + "AWSDynamoDB/";
|
||||
String exportDir = exportRoot + exportId + "/";
|
||||
boolean incremental = desc.getIncrementalExportSpecification() != null;
|
||||
|
||||
try {
|
||||
writeExportFile(s3Bucket, exportDir + "_started", new byte[0]);
|
||||
@@ -5044,8 +5099,9 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
boolean ion = "ION".equals(desc.getExportFormat());
|
||||
byte[] gzipData = buildGzipExportData(snapshot, ion);
|
||||
String dataKey = exportDir + "data/" + exportFileName() + (ion ? ".ion.gz" : ".json.gz");
|
||||
byte[] gzipData = buildGzipExportData(snapshot, ion, incremental);
|
||||
String dataKey = (incremental ? exportRoot : 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)));
|
||||
@@ -5056,7 +5112,8 @@ public class DynamoDbService {
|
||||
|
||||
desc.setEndTime(epochSeconds(clock.instant()));
|
||||
desc.setItemCount((long) snapshot.size());
|
||||
desc.setBilledSizeBytes((long) gzipData.length);
|
||||
// AWS bills an incremental export for at least 10 MB.
|
||||
desc.setBilledSizeBytes(incremental ? Math.max(10_000_000L, gzipData.length) : gzipData.length);
|
||||
String manifestSummaryKey = exportDir + "manifest-summary.json";
|
||||
writeExportManifest(s3Bucket, manifestSummaryKey, manifestSummary(desc, manifestFilesKey));
|
||||
|
||||
@@ -5079,16 +5136,21 @@ public class DynamoDbService {
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] buildGzipExportData(List<JsonNode> items, boolean ion) throws IOException {
|
||||
private byte[] buildGzipExportData(List<JsonNode> items, boolean ion, boolean incremental) throws IOException {
|
||||
// AWS writes a character above U+FFFF as UTF-8, where Jackson writes two escapes by default.
|
||||
ObjectWriter lineWriter = objectMapper.writer().with(JsonWriteFeature.COMBINE_UNICODE_SURROGATES_IN_UTF8);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(baos)) {
|
||||
for (JsonNode item : items) {
|
||||
if (ion) {
|
||||
gzip.write(DynamoDbIonText.exportLine(item).getBytes(StandardCharsets.UTF_8));
|
||||
String line = incremental ? DynamoDbIonText.recordLine(item) : DynamoDbIonText.exportLine(item);
|
||||
gzip.write(line.getBytes(StandardCharsets.UTF_8));
|
||||
} else if (incremental) {
|
||||
gzip.write(lineWriter.writeValueAsBytes(item));
|
||||
} else {
|
||||
ObjectNode line = objectMapper.createObjectNode();
|
||||
line.set("Item", item);
|
||||
byte[] lineBytes = objectMapper.writeValueAsBytes(line);
|
||||
byte[] lineBytes = lineWriter.writeValueAsBytes(line);
|
||||
gzip.write(lineBytes);
|
||||
}
|
||||
gzip.write('\n');
|
||||
@@ -5134,14 +5196,20 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
private String manifestSummary(ExportDescription desc, String manifestFilesKey) throws JsonProcessingException {
|
||||
IncrementalExportSpecification incremental = desc.getIncrementalExportSpecification();
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("version", "2020-06-30");
|
||||
root.put("version", incremental != null ? "2023-08-01" : "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())));
|
||||
if (incremental != null) {
|
||||
root.put("exportFromTime", MANIFEST_TIME.format(instantOf(incremental.getExportFromTime())));
|
||||
root.put("exportToTime", MANIFEST_TIME.format(instantOf(incremental.getExportToTime())));
|
||||
} else {
|
||||
root.put("exportTime", MANIFEST_TIME.format(instantOf(desc.getExportTime())));
|
||||
}
|
||||
root.put("s3Bucket", desc.getS3Bucket());
|
||||
root.put("s3Prefix", desc.getS3Prefix());
|
||||
root.put("s3SseAlgorithm", desc.getS3SseAlgorithm());
|
||||
@@ -5150,9 +5218,42 @@ public class DynamoDbService {
|
||||
root.put("billedSizeBytes", desc.getBilledSizeBytes());
|
||||
root.put("itemCount", desc.getItemCount());
|
||||
root.put("outputFormat", desc.getExportFormat());
|
||||
if (incremental != null) {
|
||||
root.put("outputView", incremental.getExportViewType());
|
||||
root.put("exportType", desc.getExportType());
|
||||
}
|
||||
return objectMapper.writeValueAsString(root);
|
||||
}
|
||||
|
||||
private static void checkIncrementalExportPeriod(Instant from, Instant to, Instant creationSecond, Instant now) {
|
||||
if (from.isBefore(creationSecond)) {
|
||||
throw new AwsException("InvalidExportTimeException",
|
||||
"Incremental export period from time cannot be less than the table creation time : " + from, 400);
|
||||
}
|
||||
if (to.isAfter(now)) {
|
||||
throw new AwsException("InvalidExportTimeException",
|
||||
"Incremental export period to time cannot be greater than the current time : " + to, 400);
|
||||
}
|
||||
if (!from.isBefore(to)) {
|
||||
throw new AwsException("InvalidExportTimeException",
|
||||
"Incremental export period from time should not be greater or equal to incremental export period to time",
|
||||
400);
|
||||
}
|
||||
if (Duration.between(from, to).compareTo(MIN_INCREMENTAL_EXPORT_PERIOD) < 0) {
|
||||
throw new AwsException("InvalidExportTimeException",
|
||||
"Difference between export period from time and export period to time is less than 15 minutes", 400);
|
||||
}
|
||||
// AWS takes 24 h + 1 ms but not 24 h + 1 s.
|
||||
if (Duration.between(from, to).toSeconds() > MAX_INCREMENTAL_EXPORT_PERIOD.toSeconds()) {
|
||||
throw new AwsException("InvalidExportTimeException",
|
||||
"Difference between export period from time and export period to time is greater than 24 hours", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalidExportRequest(String message) {
|
||||
return new AwsException("ValidationException", "Invalid Request: " + message, 400);
|
||||
}
|
||||
|
||||
public ExportDescription describeExport(String exportArn) {
|
||||
if (exportStore == null) {
|
||||
throw new AwsException("ExportNotFoundException",
|
||||
|
||||
+6
-1
@@ -3405,8 +3405,13 @@ public class NativeDynamoDbJsonHandler {
|
||||
request.fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().isTextual()
|
||||
? e.getValue().asText() : e.getValue()));
|
||||
|
||||
JsonNode spec = request.path("IncrementalExportSpecification");
|
||||
DynamoDbService.IncrementalExportRequest incremental = spec.isObject()
|
||||
? new DynamoDbService.IncrementalExportRequest(timestampOrNull(spec, "ExportFromTime"),
|
||||
timestampOrNull(spec, "ExportToTime"), spec.path("ExportViewType").textValue())
|
||||
: null;
|
||||
io.github.hectorvent.floci.services.dynamodb.model.ExportDescription desc =
|
||||
dynamoDbService.exportTable(params, timestampOrNull(request, "ExportTime"), region);
|
||||
dynamoDbService.exportTable(params, timestampOrNull(request, "ExportTime"), incremental, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("ExportDescription", objectMapper.valueToTree(desc));
|
||||
|
||||
+8
@@ -39,6 +39,9 @@ public class ExportDescription {
|
||||
@JsonProperty("ExportTime")
|
||||
private BigDecimal exportTime;
|
||||
|
||||
@JsonProperty("IncrementalExportSpecification")
|
||||
private IncrementalExportSpecification incrementalExportSpecification;
|
||||
|
||||
@JsonProperty("StartTime")
|
||||
private BigDecimal startTime;
|
||||
|
||||
@@ -99,6 +102,11 @@ public class ExportDescription {
|
||||
public BigDecimal getExportTime() { return exportTime; }
|
||||
public void setExportTime(BigDecimal exportTime) { this.exportTime = exportTime; }
|
||||
|
||||
public IncrementalExportSpecification getIncrementalExportSpecification() { return incrementalExportSpecification; }
|
||||
public void setIncrementalExportSpecification(IncrementalExportSpecification incrementalExportSpecification) {
|
||||
this.incrementalExportSpecification = incrementalExportSpecification;
|
||||
}
|
||||
|
||||
public BigDecimal getStartTime() { return startTime; }
|
||||
public void setStartTime(BigDecimal startTime) { this.startTime = startTime; }
|
||||
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class IncrementalExportSpecification {
|
||||
|
||||
@JsonProperty("ExportFromTime")
|
||||
private BigDecimal exportFromTime;
|
||||
|
||||
@JsonProperty("ExportToTime")
|
||||
private BigDecimal exportToTime;
|
||||
|
||||
@JsonProperty("ExportViewType")
|
||||
private String exportViewType;
|
||||
|
||||
public IncrementalExportSpecification() {}
|
||||
|
||||
public IncrementalExportSpecification(BigDecimal exportFromTime, BigDecimal exportToTime, String exportViewType) {
|
||||
this.exportFromTime = exportFromTime;
|
||||
this.exportToTime = exportToTime;
|
||||
this.exportViewType = exportViewType;
|
||||
}
|
||||
|
||||
public BigDecimal getExportFromTime() { return exportFromTime; }
|
||||
public void setExportFromTime(BigDecimal exportFromTime) { this.exportFromTime = exportFromTime; }
|
||||
|
||||
public BigDecimal getExportToTime() { return exportToTime; }
|
||||
public void setExportToTime(BigDecimal exportToTime) { this.exportToTime = exportToTime; }
|
||||
|
||||
public String getExportViewType() { return exportViewType; }
|
||||
public void setExportViewType(String exportViewType) { this.exportViewType = exportViewType; }
|
||||
}
|
||||
Reference in new issue
Block a user