feat(dynamodb): import tables from S3 and report new exports as IN_PROGRESS (#3138)

* feat(dynamodb): import tables from S3 and report new exports as IN_PROGRESS

ExportTableToPointInTime handed its worker the same description object it
returned, so a small export could already read COMPLETED in the initial
response. The worker now mutates a copy and runs under the request account.

ImportTable creates the table in CREATING, loads DynamoDB JSON lines from
every object under the S3 prefix on a virtual thread, and flips the table
to ACTIVE when done. DescribeImport and ListImports report it. DYNAMODB_JSON
with NONE or GZIP compression is accepted. CSV, ION and ZSTD are rejected
with a ValidationException.

* fix(dynamodb): item calls on a CREATING table return ResourceNotFoundException

* fix(dynamodb): concurrent ImportTable calls with one ClientToken share one import

* fix(dynamodb): import reads S3 as the caller and denies another account's bucket
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-07 22:25:24 -05:00
1 parent fd21ac9a6d
commit cbec02df04
13 files changed
+1691 -55

No files matched your search

@@ -0,0 +1,46 @@
package io.github.hectorvent.floci.core.common;
import io.quarkus.arc.Arc;
import java.util.function.Supplier;
/** Runs work that happens outside an HTTP request, such as a background worker, as a given account. */
public final class RequestScopes {
private RequestScopes() {}
/**
* Account-aware storage and S3 read the account from the request context, so a worker on
* a fresh thread would otherwise fall back to the default account.
*/
public static void runAs(String accountId, Runnable body) {
callAs(accountId, () -> {
body.run();
return null;
});
}
public static <T> T callAs(String accountId, Supplier<T> body) {
var container = Arc.container();
if (accountId == null || container == null || !container.isRunning()) {
return body.get();
}
var requestContext = container.requestContext();
var alreadyActive = requestContext.isActive();
if (!alreadyActive) {
requestContext.activate();
}
var ctx = container.instance(RequestContext.class).get();
var previousAccountId = alreadyActive ? ctx.getAccountId() : null;
try {
ctx.setAccountId(accountId);
return body.get();
} finally {
if (!alreadyActive) {
requestContext.terminate();
} else {
ctx.setAccountId(previousAccountId);
}
}
}
}
@@ -31,6 +31,7 @@ public class DynamoDbJsonHandler {
private final KinesisService kinesisService;
private final ObjectMapper objectMapper;
private final DynamoDbPartiQLHandler partiQLHandler;
private final Object importLock = new Object();
@Inject
public DynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService,
@@ -75,6 +76,9 @@ public class DynamoDbJsonHandler {
case "ExportTableToPointInTime" -> handleExportTable(request, region);
case "DescribeExport" -> handleDescribeExport(request, region);
case "ListExports" -> handleListExports(request, region);
case "ImportTable" -> handleImportTable(request, region);
case "DescribeImport" -> handleDescribeImport(request, region);
case "ListImports" -> handleListImports(request, region);
case "ExecuteStatement" -> handleExecuteStatement(request, region);
case "ExecuteTransaction" -> handleExecuteTransaction(request, region);
case "BatchExecuteStatement" -> handleBatchExecuteStatement(request, region);
@@ -86,6 +90,15 @@ public class DynamoDbJsonHandler {
}
private Response handleCreateTable(JsonNode request, String region) {
var table = createTableFromSpec(request, region, "ACTIVE");
var response = objectMapper.createObjectNode();
response.set("TableDescription", tableToNode(table));
return Response.ok(response).build();
}
/** Shared by CreateTable and ImportTable, whose TableCreationParameters use the same keys. */
private TableDefinition createTableFromSpec(JsonNode request, String region, String initialStatus) {
// Distinguish missing (undefined) from empty ("") for TableName
String tableNameRaw = (request.has("TableName") && !request.path("TableName").isNull())
? request.path("TableName").asText() : null;
@@ -175,6 +188,7 @@ public class DynamoDbJsonHandler {
TableDefinition table = dynamoDbService.createTable(tableName, keySchema, attrDefs,
readCapacity, writeCapacity, gsis, lsis, region);
table.setTableStatus(initialStatus);
table.setDeletionProtectionEnabled(deletionProtection);
@@ -230,10 +244,7 @@ public class DynamoDbJsonHandler {
// stream, billing, class, tag and SSE settings survive a restart -- stream state
// especially, since startup rebuilds streams from the persisted table.
dynamoDbService.persistTable(tableName, table, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("TableDescription", tableToNode(table));
return Response.ok(response).build();
return table;
}
private Response handleDeleteTable(JsonNode request, String region) {
@@ -2401,6 +2412,51 @@ public class DynamoDbJsonHandler {
return Response.ok(response).build();
}
private Response handleImportTable(JsonNode request, String region) {
var response = objectMapper.createObjectNode();
response.set("ImportTableDescription", objectMapper.valueToTree(findOrStartImport(request, region)));
return Response.ok(response).build();
}
/** Held across the ClientToken lookup and the table creation so identical concurrent requests share one import. */
private ImportTableDescription findOrStartImport(JsonNode request, String region) {
synchronized (importLock) {
var existing = dynamoDbService.validateImportRequest(request);
if (existing != null) {
return existing;
}
return dynamoDbService.startImport(request,
createTableFromSpec(request.path("TableCreationParameters"), region, "CREATING"), region);
}
}
private Response handleDescribeImport(JsonNode request, String region) {
var desc = dynamoDbService.describeImport(request.path("ImportArn").asText());
var response = objectMapper.createObjectNode();
response.set("ImportTableDescription", objectMapper.valueToTree(desc));
return Response.ok(response).build();
}
private Response handleListImports(JsonNode request, String region) {
var tableArn = request.hasNonNull("TableArn") ? request.get("TableArn").asText() : null;
var pageSize = request.hasNonNull("PageSize") ? request.get("PageSize").asInt() : null;
var nextToken = request.hasNonNull("NextToken") ? request.get("NextToken").asText() : null;
var result = dynamoDbService.listImports(tableArn, pageSize, nextToken);
var response = objectMapper.createObjectNode();
var summaries = objectMapper.createArrayNode();
for (var summary : result.importSummaryList()) {
summaries.add(objectMapper.valueToTree(summary));
}
response.set("ImportSummaryList", summaries);
if (result.nextToken() != null) {
response.put("NextToken", result.nextToken());
}
return Response.ok(response).build();
}
private Response handleExecuteStatement(JsonNode request, String region) {
String statement = request.path("Statement").asText();
List<JsonNode> parameters = toPartiQLParams(request.path("Parameters"));
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -10,6 +11,8 @@ import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.ExportDescription;
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.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
@@ -27,8 +30,11 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -45,6 +51,7 @@ import java.util.LinkedHashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
@@ -53,8 +60,10 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
@@ -83,6 +92,7 @@ public class DynamoDbService implements ResourceProvider {
private final StorageBackend<String, TableDefinition> tableStore;
private final StorageBackend<String, Map<String, JsonNode>> itemStore;
private final StorageBackend<String, ExportDescription> exportStore;
private final StorageBackend<String, ImportTableDescription> importStore;
// 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<>();
@@ -121,22 +131,24 @@ public class DynamoDbService implements ResourceProvider {
new TypeReference<Map<String, Map<String, JsonNode>>>() {}),
storageFactory.create("dynamodb", "dynamodb-exports.json",
new TypeReference<Map<String, ExportDescription>>() {}),
storageFactory.create("dynamodb", "dynamodb-imports.json",
new TypeReference<Map<String, ImportTableDescription>>() {}),
regionResolver, streamService, kinesisForwarder, s3Service, objectMapper);
}
/** Package-private constructor for testing. */
DynamoDbService(StorageBackend<String, TableDefinition> tableStore) {
this(tableStore, null, null, new RegionResolver("us-east-1", "000000000000"), null, null, null, null);
this(tableStore, null, null, null, new RegionResolver("us-east-1", "000000000000"), null, null, null, null);
}
DynamoDbService(StorageBackend<String, TableDefinition> tableStore, RegionResolver regionResolver) {
this(tableStore, null, null, regionResolver, null, null, null, null);
this(tableStore, null, null, null, regionResolver, null, null, null, null);
}
DynamoDbService(StorageBackend<String, TableDefinition> tableStore,
StorageBackend<String, Map<String, JsonNode>> itemStore,
RegionResolver regionResolver) {
this(tableStore, itemStore, null, regionResolver, null, null, null, null);
this(tableStore, itemStore, null, null, regionResolver, null, null, null, null);
}
DynamoDbService(StorageBackend<String, TableDefinition> tableStore,
@@ -144,12 +156,13 @@ public class DynamoDbService implements ResourceProvider {
RegionResolver regionResolver,
DynamoDbStreamService streamService,
KinesisStreamingForwarder kinesisForwarder) {
this(tableStore, itemStore, null, regionResolver, streamService, kinesisForwarder, null, null);
this(tableStore, itemStore, null, null, regionResolver, streamService, kinesisForwarder, null, null);
}
DynamoDbService(StorageBackend<String, TableDefinition> tableStore,
StorageBackend<String, Map<String, JsonNode>> itemStore,
StorageBackend<String, ExportDescription> exportStore,
StorageBackend<String, ImportTableDescription> importStore,
RegionResolver regionResolver,
DynamoDbStreamService streamService,
KinesisStreamingForwarder kinesisForwarder,
@@ -158,12 +171,14 @@ public class DynamoDbService implements ResourceProvider {
this.tableStore = tableStore;
this.itemStore = itemStore;
this.exportStore = exportStore;
this.importStore = importStore;
this.regionResolver = regionResolver;
this.streamService = streamService;
this.kinesisForwarder = kinesisForwarder;
this.s3Service = s3Service;
this.objectMapper = objectMapper != null ? objectMapper : new ObjectMapper();
loadPersistedItems();
recoverInterruptedJobs();
}
private void loadPersistedItems() {
@@ -470,9 +485,9 @@ public class DynamoDbService implements ResourceProvider {
public void deleteTable(String tableName, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
if (tableStore.get(storageKey).isEmpty()) {
throw resourceNotFoundException(canonicalTableName);
}
var table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
requireNotCreating(table);
tableStore.delete(storageKey);
itemsByTable.remove(scopedItemsKey(storageKey));
itemLocks.remove(scopedItemsKey(storageKey));
@@ -541,6 +556,8 @@ public class DynamoDbService implements ResourceProvider {
String conditionExpression,
JsonNode exprAttrNames, JsonNode exprAttrValues,
String region, String returnValuesOnConditionCheckFailure) {
var canonicalTableName = canonicalTableName(region, tableName);
requireActiveTable(regionKey(region, canonicalTableName), canonicalTableName);
return putItemInternal(tableName, item, conditionExpression, exprAttrNames, exprAttrValues,
region, returnValuesOnConditionCheckFailure, true);
}
@@ -623,8 +640,7 @@ public class DynamoDbService implements ResourceProvider {
public JsonNode getItem(String tableName, JsonNode key, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var table = requireActiveTable(storageKey, canonicalTableName);
String itemKey = buildItemKey(table, key, true);
var items = currentItems(storageKey, false);
@@ -681,8 +697,7 @@ public class DynamoDbService implements ResourceProvider {
Map<String, ConcurrentSkipListMap<String, JsonNode>> stagedItems) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var table = requireActiveTable(storageKey, canonicalTableName);
String itemKey = buildItemKey(table, key, true);
@@ -778,8 +793,7 @@ public class DynamoDbService implements ResourceProvider {
Map<String, ConcurrentSkipListMap<String, JsonNode>> stagedItems) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var table = requireActiveTable(storageKey, canonicalTableName);
String itemKey = buildItemKey(table, key, true);
@@ -924,8 +938,7 @@ public class DynamoDbService implements ResourceProvider {
JsonNode exclusiveStartKey, JsonNode exprAttrNames, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var table = requireActiveTable(storageKey, canonicalTableName);
DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, indexName);
String partitionKeyValuePlaceholder = DynamoDbAccessPathValidator.validateQuery(
@@ -1083,8 +1096,7 @@ public class DynamoDbService implements ResourceProvider {
DynamoDbReservedWords.check(filterExpression, "FilterExpression");
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var table = requireActiveTable(storageKey, canonicalTableName);
DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, indexName);
@@ -1205,8 +1217,7 @@ public class DynamoDbService implements ResourceProvider {
for (Map.Entry<String, List<JsonNode>> entry : requestItems.entrySet()) {
String tableName = canonicalTableName(region, entry.getKey());
String storageKey = regionKey(region, tableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
var table = requireActiveTable(storageKey, tableName);
Set<String> seenKeys = new HashSet<>();
for (JsonNode writeRequest : entry.getValue()) {
String itemKey;
@@ -1484,8 +1495,7 @@ public class DynamoDbService implements ResourceProvider {
}
String storageKey = regionKey(region, tableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
var table = requireActiveTable(storageKey, tableName);
String itemKey = buildItemKey(table, keyOrItem);
return new TransactParticipant(storageKey, itemKey);
}
@@ -1525,8 +1535,7 @@ public class DynamoDbService implements ResourceProvider {
JsonNode exprAttrValues = target.has("ExpressionAttributeValues") ? target.get("ExpressionAttributeValues") : null;
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var table = requireActiveTable(storageKey, canonicalTableName);
String itemKey = buildItemKey(table, key);
var tableItems = itemsFor(storageKey, stagedItems, false);
@@ -1573,8 +1582,7 @@ public class DynamoDbService implements ResourceProvider {
JsonNode put = transactItem.get("Put");
String tableName = canonicalTableName(region, put.path("TableName").asText());
String storageKey = regionKey(region, tableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
var table = requireActiveTable(storageKey, tableName);
JsonNode item = put.get("Item");
if (item == null) {
throw new AwsException("ValidationException", "Item is required for Put", 400);
@@ -1587,8 +1595,7 @@ public class DynamoDbService implements ResourceProvider {
JsonNode del = transactItem.get("Delete");
String tableName = canonicalTableName(region, del.path("TableName").asText());
String storageKey = regionKey(region, tableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
var table = requireActiveTable(storageKey, tableName);
JsonNode key = del.get("Key");
if (key == null) {
throw new AwsException("ValidationException", "Key is required for Delete", 400);
@@ -1598,8 +1605,7 @@ public class DynamoDbService implements ResourceProvider {
JsonNode upd = transactItem.get("Update");
String tableName = canonicalTableName(region, upd.path("TableName").asText());
String storageKey = regionKey(region, tableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
var table = requireActiveTable(storageKey, tableName);
JsonNode key = upd.get("Key");
if (key == null) {
throw new AwsException("ValidationException", "Key is required for Update", 400);
@@ -1668,6 +1674,7 @@ public class DynamoDbService implements ResourceProvider {
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
requireNotCreating(table);
if (readCapacity != null && readCapacity <= 0) {
throw new AwsException("ValidationException",
@@ -3380,6 +3387,16 @@ public class DynamoDbService implements ResourceProvider {
"Requested resource not found: Table: " + tableName + " not found", 400);
}
/** Item calls treat a CREATING table as absent. AWS answers them without the table name. */
private TableDefinition requireActiveTable(String storageKey, String canonicalTableName) {
var table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
if ("CREATING".equals(table.getTableStatus())) {
throw new AwsException("ResourceNotFoundException", "Requested resource not found", 400);
}
return table;
}
public record UpdateResult(JsonNode newItem, JsonNode oldItem) {}
// scannedBytes carries the pre-filter size of the read items: DynamoDB bills a
@@ -3417,7 +3434,7 @@ public class DynamoDbService implements ResourceProvider {
.orElseThrow(() -> resourceNotFoundException(tableName));
long now = Instant.now().getEpochSecond();
String exportId = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().replace("-", "");
var exportId = newJobId();
String exportArn = AwsArnUtils.Arn.of("dynamodb", tableRegion, regionResolver.getAccountId(), "table/" + table.getTableName() + "/export/" + exportId).toString();
ExportDescription desc = new ExportDescription();
@@ -3439,13 +3456,16 @@ public class DynamoDbService implements ResourceProvider {
exportStore.put(exportArn, desc);
}
ExportDescription finalDesc = desc;
ConcurrentSkipListMap<String, JsonNode> tableItems = itemsByTable.get(scopedItemsKey(storageKey));
List<JsonNode> snapshot = tableItems != null
? List.copyOf(tableItems.values())
: List.of();
Thread.ofVirtual().start(() -> runExport(finalDesc, snapshot, exportArn));
// 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.
var accountId = regionResolver.getAccountId();
var worker = objectMapper.convertValue(desc, ExportDescription.class);
Thread.ofVirtual().start(() -> RequestScopes.runAs(accountId, () -> runExport(worker, snapshot, exportArn)));
return desc;
}
@@ -3615,33 +3635,313 @@ public class DynamoDbService implements ResourceProvider {
if (exportStore == null) {
return new ListExportsResult(List.of(), null);
}
int limit = maxResults != null ? Math.min(maxResults, 25) : 25;
List<ExportDescription> all = exportStore.keys().stream()
.map(k -> exportStore.get(k).orElse(null))
.filter(d -> d != null)
var all = exportStore.scan(k -> true).stream()
.filter(d -> tableArn == null || tableArn.equals(d.getTableArn()))
.sorted(Comparator.comparing(ExportDescription::getExportArn).reversed())
.toList();
requirePageSize(maxResults, "maxResults");
var page = pageByArn(all, ExportDescription::getExportArn, maxResults, nextToken);
return new ListExportsResult(page.items().stream().map(ExportSummary::new).toList(), page.nextToken());
}
int startIdx = 0;
private record Page<T>(List<T> items, String nextToken) {}
private static final int MAX_JOB_PAGE_SIZE = 25;
private static void requirePageSize(Integer pageSize, String field) {
if (pageSize == null) {
return;
}
if (pageSize < 1) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + pageSize + "' at '" + field
+ "' failed to satisfy constraint: Member must have value greater than or equal to 1", 400);
}
if (MAX_JOB_PAGE_SIZE < pageSize) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + pageSize + "' at '" + field
+ "' failed to satisfy constraint: Member must have value less than or equal to "
+ MAX_JOB_PAGE_SIZE, 400);
}
}
private static <T> Page<T> pageByArn(List<T> all, Function<T, String> arnOf, Integer pageSize, String nextToken) {
var limit = pageSize != null ? pageSize : MAX_JOB_PAGE_SIZE;
var sorted = all.stream().sorted(Comparator.comparing(arnOf).reversed()).toList();
var startIdx = 0;
if (nextToken != null) {
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getExportArn().equals(nextToken)) {
for (var i = 0; i < sorted.size(); i++) {
if (nextToken.equals(arnOf.apply(sorted.get(i)))) {
startIdx = i + 1;
break;
}
}
}
var end = Math.min(startIdx + limit, sorted.size());
var newNextToken = end < sorted.size() ? arnOf.apply(sorted.get(end - 1)) : null;
return new Page<>(sorted.subList(startIdx, end), newNextToken);
}
List<ExportDescription> page = all.subList(startIdx, Math.min(startIdx + limit, all.size()));
String newNextToken = (startIdx + limit < all.size()) ? all.get(startIdx + limit - 1).getExportArn() : null;
private static String newJobId() {
return System.currentTimeMillis() + "-" + UUID.randomUUID().toString().replace("-", "");
}
List<ExportSummary> summaries = page.stream()
.map(ExportSummary::new)
// --- Import Operations ---
/**
* Checks an ImportTable request before the target table exists, so a rejected request
* leaves nothing behind. Returns the import already started with the same ClientToken,
* or null when this is a new import.
*/
public ImportTableDescription validateImportRequest(JsonNode request) {
if (request.path("S3BucketSource").path("S3Bucket").asText("").isBlank()) {
throw new AwsException("ValidationException", "S3BucketSource.S3Bucket is required", 400);
}
var inputFormat = request.path("InputFormat").asText("");
switch (inputFormat) {
case "DYNAMODB_JSON" -> { }
case "" -> throw new AwsException("ValidationException", "InputFormat is required", 400);
case "CSV", "ION" -> throw new AwsException("ValidationException",
"Unsupported InputFormat: " + inputFormat + ". Floci imports DYNAMODB_JSON only", 400);
default -> throw new AwsException("ValidationException",
"1 validation error detected: Value '" + inputFormat
+ "' at 'inputFormat' failed to satisfy constraint: Member must satisfy enum value set: [ION, CSV, DYNAMODB_JSON]", 400);
}
var compression = request.path("InputCompressionType").asText("NONE");
switch (compression) {
case "NONE", "GZIP" -> { }
case "ZSTD" -> throw new AwsException("ValidationException",
"Unsupported InputCompressionType: ZSTD. Floci accepts NONE or GZIP", 400);
default -> throw new AwsException("ValidationException",
"1 validation error detected: Value '" + compression
+ "' at 'inputCompressionType' failed to satisfy constraint: Member must satisfy enum value set: [GZIP, ZSTD, NONE]", 400);
}
DynamoDbTableNames.requireShortName(request.path("TableCreationParameters").path("TableName").asText(null));
var clientToken = request.path("ClientToken").asText(null);
if (clientToken != null && clientToken.isBlank()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + clientToken
+ "' at 'clientToken' failed to satisfy constraint: Member must have length greater than or equal to 1", 400);
}
if (clientToken == null || importStore == null) {
return null;
}
var existing = importStore.scan(k -> true).stream()
.filter(d -> clientToken.equals(d.getClientToken()))
.findFirst()
.orElse(null);
if (existing != null && !sameImportParameters(existing, request)) {
throw new AwsException("ImportConflictException",
"There was a conflict when importing from the specified S3 source. This can occur when "
+ "the current import conflicts with a previous import request that had the same client token.", 400);
}
return existing;
}
private static boolean sameImportParameters(ImportTableDescription existing, JsonNode request) {
var options = request.hasNonNull("InputFormatOptions") ? request.get("InputFormatOptions") : null;
return Objects.equals(existing.getS3BucketSource(), request.get("S3BucketSource"))
&& Objects.equals(existing.getInputFormat(), request.path("InputFormat").asText())
&& Objects.equals(existing.getInputFormatOptions(), options)
&& Objects.equals(existing.getInputCompressionType(), request.path("InputCompressionType").asText("NONE"))
&& Objects.equals(existing.getTableCreationParameters(), request.get("TableCreationParameters"));
}
public ImportTableDescription startImport(JsonNode request, TableDefinition table, String region) {
var tableName = table.getTableName();
var accountId = regionResolver.getAccountId();
var importArn = AwsArnUtils.Arn.of("dynamodb", region, accountId,
"table/" + tableName + "/import/" + newJobId()).toString();
var desc = new ImportTableDescription();
desc.setImportArn(importArn);
desc.setImportStatus("IN_PROGRESS");
desc.setTableArn(table.getTableArn());
desc.setTableId(table.getTableId());
desc.setClientToken(request.path("ClientToken").asText(null));
desc.setS3BucketSource(request.get("S3BucketSource"));
desc.setInputFormat(request.path("InputFormat").asText());
if (request.hasNonNull("InputFormatOptions")) {
desc.setInputFormatOptions(request.get("InputFormatOptions"));
}
desc.setInputCompressionType(request.path("InputCompressionType").asText("NONE"));
desc.setTableCreationParameters(request.get("TableCreationParameters"));
desc.setCloudWatchLogGroupArn(AwsArnUtils.Arn.of("logs", region, accountId,
"log-group:/aws-dynamodb/imports:*").toString());
desc.setStartTime(Instant.now().getEpochSecond());
if (importStore != null) {
importStore.put(importArn, desc);
}
// 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.
var worker = objectMapper.convertValue(desc, ImportTableDescription.class);
Thread.ofVirtual().start(() -> RequestScopes.runAs(accountId, () -> runImport(worker, tableName, region)));
return desc;
}
void runImport(ImportTableDescription desc, String tableName, String region) {
var source = desc.getS3BucketSource();
var bucket = source.path("S3Bucket").asText();
var prefix = source.path("S3KeyPrefix").asText("");
var bucketOwner = source.path("S3BucketOwner").asText(null);
try {
// AWS reads another account's bucket only when its policy grants it. floci has no bucket policies.
if (bucketOwner != null && !bucketOwner.equals(regionResolver.getAccountId())) {
throw new AwsException("AccessDenied",
"Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied)", 403);
}
var objects = s3Service.listObjects(bucket, prefix, null, 0);
if (objects.isEmpty()) {
failImport(desc, "S3NoSuchKey", "No objects found under s3://" + bucket + "/" + prefix);
} else {
for (var object : objects) {
try {
importObject(desc, tableName, region, bucket, object.getKey());
} catch (IOException | RuntimeException e) {
desc.setErrorCount(desc.getErrorCount() + 1);
LOG.warnv("Import {0} skipped object {1}: {2}", desc.getImportArn(), object.getKey(), e.getMessage());
}
}
desc.setImportStatus("COMPLETED");
}
} catch (AwsException e) {
switch (e.getErrorCode()) {
case "NoSuchBucket" -> failImport(desc, "S3NoSuchBucket", "The specified bucket does not exist: " + bucket);
case "AccessDenied" -> failImport(desc, "S3AccessDenied", e.getMessage());
default -> {
LOG.errorv(e, "Import failed: {0}", desc.getImportArn());
failImport(desc, "S3" + e.getErrorCode(), e.getMessage());
}
}
} catch (Exception e) {
LOG.errorv(e, "Import failed: {0}", desc.getImportArn());
failImport(desc, "UNKNOWN", e.getMessage());
}
persistItems(regionKey(region, tableName));
desc.setEndTime(Instant.now().getEpochSecond());
activateTable(tableName, region);
if (importStore != null) {
importStore.put(desc.getImportArn(), desc);
}
LOG.infov("Import {0} {1}: imported={2}, errors={3}", desc.getImportArn(),
desc.getImportStatus(), desc.getImportedItemCount(), desc.getErrorCount());
}
private void importObject(ImportTableDescription desc, String tableName, String region,
String bucket, String key) throws IOException {
var size = s3Service.getObjectMetadata(bucket, key, null).getSize();
desc.setProcessedSizeBytes(desc.getProcessedSizeBytes() + size);
try (var raw = s3Service.openObjectStream(bucket, key, null);
var reader = new BufferedReader(new InputStreamReader(decompress(desc, raw), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.isBlank()) {
continue;
}
desc.setProcessedItemCount(desc.getProcessedItemCount() + 1);
try {
var item = objectMapper.readTree(line).path("Item");
if (!item.isObject()) {
throw new IOException("line has no Item object");
}
putItemInternal(tableName, item, null, null, null, region, "NONE", false, event -> { });
desc.setImportedItemCount(desc.getImportedItemCount() + 1);
} catch (IOException | RuntimeException e) {
desc.setErrorCount(desc.getErrorCount() + 1);
LOG.debugv("Import {0} skipped a line of {1}: {2}", desc.getImportArn(), key, e.getMessage());
}
}
}
}
private static InputStream decompress(ImportTableDescription desc, InputStream raw) throws IOException {
return "GZIP".equals(desc.getInputCompressionType()) ? new GZIPInputStream(raw) : raw;
}
private static void requireNotCreating(TableDefinition table) {
if ("CREATING".equals(table.getTableStatus())) {
throw new AwsException("ResourceInUseException",
"Attempt to change a resource which is still in use: Table is being created: "
+ table.getTableName(), 400);
}
}
private static void failImport(ImportTableDescription desc, String code, String message) {
desc.setImportStatus("FAILED");
desc.setFailureCode(code);
desc.setFailureMessage(message);
}
private void activateTable(String tableName, String region) {
var storageKey = regionKey(region, tableName);
tableStore.get(storageKey).ifPresent(table -> {
if ("CREATING".equals(table.getTableStatus())) {
table.setTableStatus("ACTIVE");
tableStore.put(storageKey, table);
}
});
}
/**
* A job interrupted by a restart would otherwise stay IN_PROGRESS forever, since no
* worker survives the process. An import also leaves its table stuck in CREATING.
*/
private void recoverInterruptedJobs() {
var now = Instant.now().getEpochSecond();
if (exportStore instanceof AccountAwareStorageBackend<ExportDescription> exports) {
for (var entry : exports.scanAllAccountEntries(k -> true)) {
var desc = entry.value();
if (!"IN_PROGRESS".equals(desc.getExportStatus())) {
continue;
}
desc.setExportStatus("FAILED");
desc.setFailureCode("InterruptedByRestart");
desc.setFailureMessage("The emulator restarted before the export finished");
desc.setEndTime(now);
exports.putForAccount(entry.accountId(), entry.key(), desc);
}
}
if (importStore instanceof AccountAwareStorageBackend<ImportTableDescription> imports) {
for (var entry : imports.scanAllAccountEntries(k -> true)) {
var desc = entry.value();
if (!"IN_PROGRESS".equals(desc.getImportStatus())) {
continue;
}
failImport(desc, "InterruptedByRestart", "The emulator restarted before the import finished");
desc.setEndTime(now);
imports.putForAccount(entry.accountId(), entry.key(), desc);
}
}
if (tableStore instanceof AccountAwareStorageBackend<TableDefinition> tables) {
for (var entry : tables.scanAllAccountEntries(k -> true)) {
var table = entry.value();
if ("CREATING".equals(table.getTableStatus())) {
table.setTableStatus("ACTIVE");
tables.putForAccount(entry.accountId(), entry.key(), table);
}
}
}
}
public ImportTableDescription describeImport(String importArn) {
return Optional.ofNullable(importStore)
.flatMap(store -> store.get(importArn))
.orElseThrow(() -> new AwsException("ImportNotFoundException",
"The specified import was not found.", 400));
}
public record ListImportsResult(List<ImportSummary> importSummaryList, String nextToken) {}
public ListImportsResult listImports(String tableArn, Integer pageSize, String nextToken) {
if (importStore == null) {
return new ListImportsResult(List.of(), null);
}
var all = importStore.scan(k -> true).stream()
.filter(d -> tableArn == null || tableArn.equals(d.getTableArn()))
.toList();
return new ListExportsResult(summaries, newNextToken);
requirePageSize(pageSize, "pageSize");
var page = pageByArn(all, ImportTableDescription::getImportArn, pageSize, nextToken);
return new ListImportsResult(page.items().stream().map(ImportSummary::new).toList(), page.nextToken());
}
@Override
@@ -0,0 +1,74 @@
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 com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ImportSummary {
@JsonProperty("ImportArn")
private String importArn;
@JsonProperty("ImportStatus")
private String importStatus;
@JsonProperty("TableArn")
private String tableArn;
@JsonProperty("S3BucketSource")
private JsonNode s3BucketSource;
@JsonProperty("CloudWatchLogGroupArn")
private String cloudWatchLogGroupArn;
@JsonProperty("InputFormat")
private String inputFormat;
@JsonProperty("StartTime")
private Long startTime;
@JsonProperty("EndTime")
private Long endTime;
public ImportSummary() {}
public ImportSummary(ImportTableDescription desc) {
this.importArn = desc.getImportArn();
this.importStatus = desc.getImportStatus();
this.tableArn = desc.getTableArn();
this.s3BucketSource = desc.getS3BucketSource();
this.cloudWatchLogGroupArn = desc.getCloudWatchLogGroupArn();
this.inputFormat = desc.getInputFormat();
this.startTime = desc.getStartTime();
this.endTime = desc.getEndTime();
}
public String getImportArn() { return importArn; }
public void setImportArn(String importArn) { this.importArn = importArn; }
public String getImportStatus() { return importStatus; }
public void setImportStatus(String importStatus) { this.importStatus = importStatus; }
public String getTableArn() { return tableArn; }
public void setTableArn(String tableArn) { this.tableArn = tableArn; }
public JsonNode getS3BucketSource() { return s3BucketSource; }
public void setS3BucketSource(JsonNode s3BucketSource) { this.s3BucketSource = s3BucketSource; }
public String getCloudWatchLogGroupArn() { return cloudWatchLogGroupArn; }
public void setCloudWatchLogGroupArn(String cloudWatchLogGroupArn) { this.cloudWatchLogGroupArn = cloudWatchLogGroupArn; }
public String getInputFormat() { return inputFormat; }
public void setInputFormat(String inputFormat) { this.inputFormat = inputFormat; }
public Long getStartTime() { return startTime; }
public void setStartTime(Long startTime) { this.startTime = startTime; }
public Long getEndTime() { return endTime; }
public void setEndTime(Long endTime) { this.endTime = endTime; }
}
@@ -0,0 +1,127 @@
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 com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ImportTableDescription {
@JsonProperty("ImportArn")
private String importArn;
@JsonProperty("ImportStatus")
private String importStatus;
@JsonProperty("TableArn")
private String tableArn;
@JsonProperty("TableId")
private String tableId;
@JsonProperty("ClientToken")
private String clientToken;
@JsonProperty("S3BucketSource")
private JsonNode s3BucketSource;
@JsonProperty("ErrorCount")
private Long errorCount = 0L;
@JsonProperty("CloudWatchLogGroupArn")
private String cloudWatchLogGroupArn;
@JsonProperty("InputFormat")
private String inputFormat;
@JsonProperty("InputFormatOptions")
private JsonNode inputFormatOptions;
@JsonProperty("InputCompressionType")
private String inputCompressionType;
@JsonProperty("TableCreationParameters")
private JsonNode tableCreationParameters;
@JsonProperty("StartTime")
private Long startTime;
@JsonProperty("EndTime")
private Long endTime;
@JsonProperty("ProcessedSizeBytes")
private Long processedSizeBytes = 0L;
@JsonProperty("ProcessedItemCount")
private Long processedItemCount = 0L;
@JsonProperty("ImportedItemCount")
private Long importedItemCount = 0L;
@JsonProperty("FailureCode")
private String failureCode;
@JsonProperty("FailureMessage")
private String failureMessage;
public String getImportArn() { return importArn; }
public void setImportArn(String importArn) { this.importArn = importArn; }
public String getImportStatus() { return importStatus; }
public void setImportStatus(String importStatus) { this.importStatus = importStatus; }
public String getTableArn() { return tableArn; }
public void setTableArn(String tableArn) { this.tableArn = tableArn; }
public String getTableId() { return tableId; }
public void setTableId(String tableId) { this.tableId = tableId; }
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
public JsonNode getS3BucketSource() { return s3BucketSource; }
public void setS3BucketSource(JsonNode s3BucketSource) { this.s3BucketSource = s3BucketSource; }
public Long getErrorCount() { return errorCount; }
public void setErrorCount(Long errorCount) { this.errorCount = errorCount; }
public String getCloudWatchLogGroupArn() { return cloudWatchLogGroupArn; }
public void setCloudWatchLogGroupArn(String cloudWatchLogGroupArn) { this.cloudWatchLogGroupArn = cloudWatchLogGroupArn; }
public String getInputFormat() { return inputFormat; }
public void setInputFormat(String inputFormat) { this.inputFormat = inputFormat; }
public JsonNode getInputFormatOptions() { return inputFormatOptions; }
public void setInputFormatOptions(JsonNode inputFormatOptions) { this.inputFormatOptions = inputFormatOptions; }
public String getInputCompressionType() { return inputCompressionType; }
public void setInputCompressionType(String inputCompressionType) { this.inputCompressionType = inputCompressionType; }
public JsonNode getTableCreationParameters() { return tableCreationParameters; }
public void setTableCreationParameters(JsonNode tableCreationParameters) { this.tableCreationParameters = tableCreationParameters; }
public Long getStartTime() { return startTime; }
public void setStartTime(Long startTime) { this.startTime = startTime; }
public Long getEndTime() { return endTime; }
public void setEndTime(Long endTime) { this.endTime = endTime; }
public Long getProcessedSizeBytes() { return processedSizeBytes; }
public void setProcessedSizeBytes(Long processedSizeBytes) { this.processedSizeBytes = processedSizeBytes; }
public Long getProcessedItemCount() { return processedItemCount; }
public void setProcessedItemCount(Long processedItemCount) { this.processedItemCount = processedItemCount; }
public Long getImportedItemCount() { return importedItemCount; }
public void setImportedItemCount(Long importedItemCount) { this.importedItemCount = importedItemCount; }
public String getFailureCode() { return failureCode; }
public void setFailureCode(String failureCode) { this.failureCode = failureCode; }
public String getFailureMessage() { return failureMessage; }
public void setFailureMessage(String failureMessage) { this.failureMessage = failureMessage; }
}
@@ -143,6 +143,12 @@ public class ResourceArnBuilder {
return List.of(toDynamoDbTableArn(tableName, region, accountId));
}
}
if (json.path("TableCreationParameters").hasNonNull("TableName")) {
var tableName = json.path("TableCreationParameters").get("TableName").asText().trim();
if (!tableName.isEmpty()) {
return List.of(toDynamoDbTableArn(tableName, region, accountId));
}
}
if (json.hasNonNull("ResourceArn")) {
String resourceArn = json.get("ResourceArn").asText().trim();
if (!resourceArn.isEmpty()) {
@@ -167,6 +173,12 @@ public class ResourceArnBuilder {
return List.of(exportArn);
}
}
if (json.hasNonNull("ImportArn")) {
var importArn = json.get("ImportArn").asText().trim();
if (!importArn.isEmpty()) {
return List.of(importArn);
}
}
if (json.hasNonNull("RequestItems") && json.get("RequestItems").isObject()) {
Set<String> arns = new LinkedHashSet<>();
var fieldNames = json.get("RequestItems").fieldNames();