mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(dynamodb): support legacy table discovery and batch cleanup (#5986)
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
e5a206554f
commit
0a37ea830b
27 files changed
+1003
-24
No files matched your search
@@ -396,7 +396,7 @@ public class AwsJsonCborController {
|
||||
// dispatch is an unknown operation, not an empty 204. The 204 fallback now applies
|
||||
// only to a resolved service whose action this handler does not dispatch.
|
||||
ServiceCatalog.TargetMatch targetMatch = catalog.matchTarget(target).orElse(null);
|
||||
if (targetMatch == null) {
|
||||
if (targetMatch == null || targetMatch.jsonOnly()) {
|
||||
return cborUnknownOperationError("Unknown operation: " + target, httpHeaders);
|
||||
}
|
||||
|
||||
|
||||
@@ -160,6 +160,9 @@ public class AwsJsonController {
|
||||
if (targetMatch.prefix().startsWith("DynamoDBStreams_")) {
|
||||
yield dynamoDbStreamsJsonHandler.handle(action, request, region);
|
||||
}
|
||||
if (targetMatch.jsonOnly()) {
|
||||
yield dynamoDbJsonHandler.handleLegacy(action, request, region);
|
||||
}
|
||||
DynamoDbRequestShapes.check(action, request);
|
||||
yield dynamoDbJsonHandler.handle(action, request, region);
|
||||
}
|
||||
@@ -197,6 +200,9 @@ public class AwsJsonController {
|
||||
// boundary so other callers of DynamoDbJsonHandler (CBOR, API Gateway proxy,
|
||||
// Step Functions tasks) keep their original ObjectNode entity.
|
||||
if ("dynamodb".equals(serviceKey)) {
|
||||
if (targetMatch.jsonOnly()) {
|
||||
response = DynamoDbResponses.withLegacyErrorNamespace(response, objectMapper);
|
||||
}
|
||||
return DynamoDbResponses.withCrc32(response, objectMapper);
|
||||
}
|
||||
return response;
|
||||
|
||||
+24
-6
@@ -90,6 +90,7 @@ public class IamConditionContextResolver {
|
||||
private final EmulatorConfig config;
|
||||
private final CurrentVertxRequest currentVertxRequest;
|
||||
private final Clock clock;
|
||||
private final ResolvedServiceCatalog serviceCatalog;
|
||||
|
||||
/**
|
||||
* The system clock, not the CDI one: Object Lock's remaining retention days has to count from the
|
||||
@@ -102,9 +103,10 @@ public class IamConditionContextResolver {
|
||||
Instance<CloudWatchLogsService> logsService,
|
||||
RequestContext requestContext,
|
||||
EmulatorConfig config,
|
||||
CurrentVertxRequest currentVertxRequest) {
|
||||
CurrentVertxRequest currentVertxRequest,
|
||||
ResolvedServiceCatalog serviceCatalog) {
|
||||
this(dynamoDbFacade, ec2Service, s3Service, logsService, requestContext, config, currentVertxRequest,
|
||||
Clock.systemUTC());
|
||||
serviceCatalog, Clock.systemUTC());
|
||||
}
|
||||
|
||||
IamConditionContextResolver(Instance<DynamoDbFacade> dynamoDbFacade,
|
||||
@@ -114,7 +116,7 @@ public class IamConditionContextResolver {
|
||||
RequestContext requestContext,
|
||||
EmulatorConfig config,
|
||||
CurrentVertxRequest currentVertxRequest,
|
||||
Clock clock) {
|
||||
ResolvedServiceCatalog serviceCatalog, Clock clock) {
|
||||
this.dynamoDbFacade = dynamoDbFacade;
|
||||
this.ec2Service = ec2Service;
|
||||
this.s3Service = s3Service;
|
||||
@@ -123,6 +125,7 @@ public class IamConditionContextResolver {
|
||||
this.config = config;
|
||||
this.currentVertxRequest = currentVertxRequest;
|
||||
this.clock = clock;
|
||||
this.serviceCatalog = serviceCatalog;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> resolve(String credentialScope, String action,
|
||||
@@ -739,7 +742,7 @@ public class IamConditionContextResolver {
|
||||
return dynamoDbBatchConditionContext(action, ctx, null);
|
||||
}
|
||||
TableDefinition table = describeTargetTable(targetTableName(body));
|
||||
DynamoDbConditionKeys.Result keys = DynamoDbConditionKeys.extract(action, body, table);
|
||||
DynamoDbConditionKeys.Result keys = dynamoDbKeys(action, body, table, ctx);
|
||||
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
if (!keys.leadingKeys().isEmpty()) {
|
||||
@@ -850,8 +853,8 @@ public class IamConditionContextResolver {
|
||||
ObjectNode single = ((ObjectNode) body).objectNode();
|
||||
single.setAll((ObjectNode) body);
|
||||
single.putObject("RequestItems").set(entry.getKey(), entry.getValue());
|
||||
DynamoDbConditionKeys.Result keys = DynamoDbConditionKeys.extract(
|
||||
action, single, describeTargetTable(reference));
|
||||
DynamoDbConditionKeys.Result keys = dynamoDbKeys(
|
||||
action, single, describeTargetTable(reference), ctx);
|
||||
leadingKeys.addAll(keys.leadingKeys());
|
||||
attributes.addAll(keys.attributes());
|
||||
});
|
||||
@@ -880,6 +883,21 @@ public class IamConditionContextResolver {
|
||||
return cached instanceof JsonNode node ? node : null;
|
||||
}
|
||||
|
||||
private DynamoDbConditionKeys.Result dynamoDbKeys(
|
||||
String action, JsonNode body, TableDefinition table, ContainerRequestContext ctx) {
|
||||
String target = ctx.getHeaderString("X-Amz-Target");
|
||||
boolean legacy = action != null && action.startsWith("dynamodb:")
|
||||
&& serviceCatalog.matchTarget(target)
|
||||
.filter(ServiceCatalog.TargetMatch::jsonOnly)
|
||||
.filter(match -> "dynamodb".equals(match.descriptor().externalKey()))
|
||||
.filter(match -> match.action().equals(action.substring("dynamodb:".length())))
|
||||
.isPresent()
|
||||
&& ctx.getMediaType() != null
|
||||
&& ctx.getMediaType().isCompatible(MediaType.valueOf("application/x-amz-json-1.0"));
|
||||
return legacy ? DynamoDbConditionKeys.extractLegacy(action, body, table)
|
||||
: DynamoDbConditionKeys.extract(action, body, table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up the table whose key schema names the partition key. Resolved lazily through
|
||||
* Instance so core.common keeps no hard dependency on the DynamoDB facade, and via
|
||||
|
||||
@@ -88,6 +88,7 @@ import jakarta.inject.Inject;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -135,7 +136,8 @@ public class ResolvedServiceCatalog {
|
||||
config.storage().services().dynamodb().flushIntervalMs(), null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON, ServiceProtocol.CBOR),
|
||||
Set.of("DynamoDB_20120810.", "DynamoDBStreams_20120810."),
|
||||
Set.of("dynamodb"), Set.of("DynamoDB", "DynamoDB Streams"), Set.of()),
|
||||
Set.of("dynamodb"), Set.of("DynamoDB", "DynamoDB Streams"), Set.of(),
|
||||
"DynamoDB_20111205."),
|
||||
descriptor("sns", "sns", config.services().sns().enabled(), true,
|
||||
"sns", storageMode(config.storage().services().sns().mode(), config.storage().mode()),
|
||||
config.storage().services().sns().flushIntervalMs(), AwsNamespaces.SNS, ServiceProtocol.QUERY,
|
||||
@@ -850,8 +852,11 @@ public class ResolvedServiceCatalog {
|
||||
Set<String> targetPrefixes,
|
||||
Set<String> credentialScopes,
|
||||
Set<String> cborSdkServiceIds,
|
||||
Set<Class<?>> resourceClasses
|
||||
Set<Class<?>> resourceClasses,
|
||||
String... jsonOnlyTargetPrefixes
|
||||
) {
|
||||
Set<String> resolvedTargetPrefixes = new HashSet<>(targetPrefixes);
|
||||
resolvedTargetPrefixes.addAll(Set.of(jsonOnlyTargetPrefixes));
|
||||
return new ServiceDescriptor(
|
||||
externalKey,
|
||||
configKey,
|
||||
@@ -863,10 +868,11 @@ public class ResolvedServiceCatalog {
|
||||
xmlNamespace,
|
||||
defaultProtocol,
|
||||
Set.copyOf(supportedProtocols),
|
||||
Set.copyOf(targetPrefixes),
|
||||
Set.copyOf(resolvedTargetPrefixes),
|
||||
Set.copyOf(credentialScopes),
|
||||
Set.copyOf(cborSdkServiceIds),
|
||||
Set.copyOf(resourceClasses)
|
||||
Set.copyOf(resourceClasses),
|
||||
Set.of(jsonOnlyTargetPrefixes)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,9 @@ public class ServiceCatalog {
|
||||
String rpcV2ServiceName = prefix.endsWith(".")
|
||||
? prefix.substring(0, prefix.length() - 1)
|
||||
: prefix;
|
||||
cborSdkServiceIds.putIfAbsent(rpcV2ServiceName, descriptor);
|
||||
if (!descriptor.jsonOnlyTargetPrefixes().contains(prefix)) {
|
||||
cborSdkServiceIds.putIfAbsent(rpcV2ServiceName, descriptor);
|
||||
}
|
||||
}
|
||||
}
|
||||
targets.sort(Comparator.comparingInt((Map.Entry<String, ServiceDescriptor> entry) -> entry.getKey().length())
|
||||
@@ -126,5 +128,8 @@ public class ServiceCatalog {
|
||||
}
|
||||
|
||||
public record TargetMatch(ServiceDescriptor descriptor, String prefix, String action) {
|
||||
public boolean jsonOnly() {
|
||||
return descriptor.jsonOnlyTargetPrefixes().contains(prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@ public record ServiceDescriptor(
|
||||
Set<String> targetPrefixes,
|
||||
Set<String> credentialScopes,
|
||||
Set<String> cborSdkServiceIds,
|
||||
Set<Class<?>> resourceClasses
|
||||
Set<Class<?>> resourceClasses,
|
||||
Set<String> jsonOnlyTargetPrefixes
|
||||
) {
|
||||
|
||||
public boolean supportsStorage() {
|
||||
|
||||
+51
-1
@@ -138,6 +138,56 @@ public final class DynamoDbConditionKeys {
|
||||
textOrNull(body.get("Select")));
|
||||
}
|
||||
|
||||
/** Condition keys for the separately routed 2011-12-05 JSON requests. */
|
||||
public static Result extractLegacy(String action, JsonNode body, TableDefinition table) {
|
||||
if (body == null || !body.isObject()) {
|
||||
return new Result(List.of(), List.of(), null);
|
||||
}
|
||||
String pkName = partitionKeyName(table);
|
||||
List<String> leadingKeys = new ArrayList<>();
|
||||
Set<String> attributes = new LinkedHashSet<>();
|
||||
if ("dynamodb:Query".equals(action)) {
|
||||
addLegacyKey(leadingKeys, attributes, body.get("HashKeyValue"), pkName);
|
||||
if (body.hasNonNull("RangeKeyCondition") && table != null && table.getKeySchema() != null) {
|
||||
table.getKeySchema().stream().filter(key -> "RANGE".equals(key.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName).forEach(attributes::add);
|
||||
}
|
||||
addAttributesToGet(attributes, body.get("AttributesToGet"));
|
||||
} else if ("dynamodb:BatchWriteItem".equals(action)) {
|
||||
for (JsonNode tableRequest : requestItemsFor(body, table)) {
|
||||
if (!tableRequest.isArray()) {
|
||||
continue;
|
||||
}
|
||||
for (JsonNode write : tableRequest) {
|
||||
JsonNode put = write.path("PutRequest").get("Item");
|
||||
addAttributeNames(attributes, put);
|
||||
addLeadingKey(leadingKeys, put, pkName);
|
||||
JsonNode key = write.path("DeleteRequest").path("Key");
|
||||
addLegacyKey(leadingKeys, attributes, key.get("HashKeyElement"), pkName);
|
||||
if (key.hasNonNull("RangeKeyElement") && table != null && table.getKeySchema() != null) {
|
||||
table.getKeySchema().stream().filter(element -> "RANGE".equals(element.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName).forEach(attributes::add);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Result(List.copyOf(leadingKeys), List.copyOf(attributes),
|
||||
"dynamodb:Query".equals(action) && body.path("Count").isBoolean()
|
||||
&& body.path("Count").booleanValue() ? "COUNT" : null);
|
||||
}
|
||||
|
||||
private static void addLegacyKey(List<String> leadingKeys, Set<String> attributes, JsonNode value, String name) {
|
||||
if (value != null) {
|
||||
if (name != null) {
|
||||
attributes.add(name);
|
||||
}
|
||||
String scalar = scalarValue(value);
|
||||
if (scalar != null) {
|
||||
leadingKeys.add(scalar);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The extracted keys. {@code leadingKeys} holds partition-key values in request order
|
||||
* (duplicates preserved), {@code attributes} holds attribute names in first-seen order
|
||||
@@ -395,4 +445,4 @@ public final class DynamoDbConditionKeys {
|
||||
String text = node.asText();
|
||||
return text.isEmpty() ? null : text;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,12 @@ public class DynamoDbJsonHandler {
|
||||
return toResponse(operations.execute(new Call(scope, Api.DYNAMODB, action, request)));
|
||||
}
|
||||
|
||||
public Response handleLegacy(String action, JsonNode request, String region) throws Exception {
|
||||
Scope scope = new Scope(regionResolver.getAccountId(),
|
||||
region != null ? region : regionResolver.getDefaultRegion());
|
||||
return toResponse(new DynamoDbLegacyProtocol(operations, scope).execute(action, request));
|
||||
}
|
||||
|
||||
static Response toResponse(Reply reply) {
|
||||
Response.ResponseBuilder builder = Response.status(reply.status()).entity(reply.body());
|
||||
for (Map.Entry<String, List<String>> header : reply.headers().entrySet()) {
|
||||
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
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.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Call;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/** The 2011-12-05 wire shapes for table discovery, queries and batch writes. */
|
||||
final class DynamoDbLegacyProtocol {
|
||||
|
||||
private final DynamoDbOperations operations;
|
||||
private final Scope scope;
|
||||
private final Map<String, JsonNode> tables = new HashMap<>();
|
||||
|
||||
DynamoDbLegacyProtocol(DynamoDbOperations operations, Scope scope) {
|
||||
this.operations = operations;
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
Reply execute(String action, JsonNode request) throws Exception {
|
||||
return switch (action) {
|
||||
case "DescribeTable" -> describe(request);
|
||||
case "Query" -> query(request);
|
||||
case "BatchWriteItem" -> batchWrite(request);
|
||||
default -> throw new AwsException("UnknownOperationException",
|
||||
"Unknown operation: DynamoDB_20111205." + action, 400);
|
||||
};
|
||||
}
|
||||
|
||||
private Reply describe(JsonNode request) throws Exception {
|
||||
Reply reply = call("DescribeTable", request);
|
||||
if (reply.status() >= 300) {
|
||||
return reply;
|
||||
}
|
||||
ObjectNode table = fields(reply.body().path("Table"), "TableName", "TableStatus", "CreationDateTime",
|
||||
"ItemCount", "TableSizeBytes", "ProvisionedThroughput");
|
||||
table.set("KeySchema", legacySchema(reply.body().path("Table")));
|
||||
ObjectNode body = object();
|
||||
body.set("Table", table);
|
||||
return body(reply, body);
|
||||
}
|
||||
|
||||
private Reply query(JsonNode request) throws Exception {
|
||||
String tableName = tableName(request);
|
||||
JsonNode table = table(tableName);
|
||||
String hashName = keyName(table, "HASH");
|
||||
String rangeName = keyName(table, "RANGE");
|
||||
if (rangeName == null) {
|
||||
throw invalid("Query requires a table with a hash and range key");
|
||||
}
|
||||
ObjectNode converted = fields(request, "TableName", "AttributesToGet", "Limit",
|
||||
"ConsistentRead", "ScanIndexForward");
|
||||
ObjectNode conditions = object();
|
||||
ObjectNode hashCondition = object().put("ComparisonOperator", "EQ");
|
||||
hashCondition.putArray("AttributeValueList").add(requiredObject(request, "HashKeyValue"));
|
||||
conditions.set(hashName, hashCondition);
|
||||
if (request.hasNonNull("RangeKeyCondition")) {
|
||||
conditions.set(rangeName, requiredObject(request, "RangeKeyCondition"));
|
||||
}
|
||||
converted.set("KeyConditions", conditions);
|
||||
if (request.hasNonNull("ExclusiveStartKey")) {
|
||||
converted.set("ExclusiveStartKey", modernKey(request.get("ExclusiveStartKey"), table));
|
||||
}
|
||||
if (request.hasNonNull("Count")) {
|
||||
if (!request.get("Count").isBoolean()) {
|
||||
throw invalid("Count must be a boolean");
|
||||
}
|
||||
if (request.get("Count").booleanValue()) {
|
||||
converted.put("Select", "COUNT");
|
||||
}
|
||||
}
|
||||
converted.put("ReturnConsumedCapacity", "TOTAL");
|
||||
Reply reply = call("Query", converted);
|
||||
if (reply.status() >= 300) {
|
||||
return reply;
|
||||
}
|
||||
ObjectNode result = fields(reply.body(), "Items", "Count");
|
||||
JsonNode lastKey = reply.body().get("LastEvaluatedKey");
|
||||
if (lastKey != null && !lastKey.isEmpty()) {
|
||||
result.set("LastEvaluatedKey", legacyKey(lastKey, table));
|
||||
}
|
||||
JsonNode capacity = reply.body().path("ConsumedCapacity").get("CapacityUnits");
|
||||
if (capacity != null) {
|
||||
result.set("ConsumedCapacityUnits", capacity);
|
||||
}
|
||||
return body(reply, result);
|
||||
}
|
||||
|
||||
private Reply batchWrite(JsonNode request) throws Exception {
|
||||
ObjectNode converted = object();
|
||||
converted.set("RequestItems", writes(requiredObject(request, "RequestItems"), false));
|
||||
converted.put("ReturnConsumedCapacity", "TOTAL");
|
||||
Reply reply = call("BatchWriteItem", converted);
|
||||
if (reply.status() >= 300) {
|
||||
return reply;
|
||||
}
|
||||
ObjectNode result = object();
|
||||
ObjectNode capacities = object();
|
||||
for (JsonNode capacity : reply.body().path("ConsumedCapacity")) {
|
||||
ObjectNode units = object();
|
||||
units.set("ConsumedCapacityUnits", capacity.get("CapacityUnits"));
|
||||
capacities.set(capacity.path("TableName").asText(), units);
|
||||
}
|
||||
result.set("Responses", capacities);
|
||||
JsonNode unprocessed = reply.body().get("UnprocessedItems");
|
||||
if (unprocessed != null) {
|
||||
result.set("UnprocessedItems", writes(unprocessed, true));
|
||||
}
|
||||
return body(reply, result);
|
||||
}
|
||||
|
||||
private ObjectNode writes(JsonNode requestItems, boolean legacy) throws Exception {
|
||||
ObjectNode result = object();
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = requestItems.fields();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
if (!entry.getValue().isArray()) {
|
||||
throw invalid("RequestItems values must be arrays");
|
||||
}
|
||||
JsonNode table = table(entry.getKey());
|
||||
ArrayNode writes = result.putArray(entry.getKey());
|
||||
for (JsonNode write : entry.getValue()) {
|
||||
if (!write.isObject() || write.hasNonNull("PutRequest") == write.hasNonNull("DeleteRequest")) {
|
||||
throw invalid("A write must contain exactly one PutRequest or DeleteRequest");
|
||||
}
|
||||
ObjectNode converted = object();
|
||||
if (write.hasNonNull("DeleteRequest")) {
|
||||
JsonNode key = requiredObject(requiredObject(write, "DeleteRequest"), "Key");
|
||||
ObjectNode delete = object();
|
||||
delete.set("Key", legacy ? legacyKey(key, table) : modernKey(key, table));
|
||||
converted.set("DeleteRequest", delete);
|
||||
} else {
|
||||
ObjectNode put = object();
|
||||
put.set("Item", requiredObject(requiredObject(write, "PutRequest"), "Item"));
|
||||
converted.set("PutRequest", put);
|
||||
}
|
||||
writes.add(converted);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private JsonNode table(String name) throws Exception {
|
||||
JsonNode table = tables.get(name);
|
||||
if (table == null) {
|
||||
table = call("DescribeTable", object().put("TableName", name)).successBody().path("Table");
|
||||
tables.put(name, table);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
private Reply call(String action, JsonNode request) throws Exception {
|
||||
DynamoDbRequestShapes.check(action, request);
|
||||
return operations.execute(new Call(scope, Api.DYNAMODB, action, request));
|
||||
}
|
||||
|
||||
private static ObjectNode modernKey(JsonNode key, JsonNode table) {
|
||||
ObjectNode converted = object();
|
||||
converted.set(keyName(table, "HASH"), requiredObject(key, "HashKeyElement"));
|
||||
String rangeName = keyName(table, "RANGE");
|
||||
if (rangeName != null) {
|
||||
converted.set(rangeName, requiredObject(key, "RangeKeyElement"));
|
||||
} else if (key.hasNonNull("RangeKeyElement")) {
|
||||
throw invalid("The provided key does not match the table schema");
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
private static ObjectNode legacyKey(JsonNode key, JsonNode table) {
|
||||
ObjectNode converted = object();
|
||||
converted.set("HashKeyElement", key.get(keyName(table, "HASH")));
|
||||
String rangeName = keyName(table, "RANGE");
|
||||
if (rangeName != null) {
|
||||
converted.set("RangeKeyElement", key.get(rangeName));
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
private static ObjectNode legacySchema(JsonNode table) {
|
||||
ObjectNode result = object();
|
||||
for (JsonNode key : table.path("KeySchema")) {
|
||||
String name = key.path("AttributeName").asText();
|
||||
for (JsonNode definition : table.path("AttributeDefinitions")) {
|
||||
if (name.equals(definition.path("AttributeName").asText())) {
|
||||
result.set("HASH".equals(key.path("KeyType").asText()) ? "HashKeyElement" : "RangeKeyElement",
|
||||
fields(definition, "AttributeName", "AttributeType"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String keyName(JsonNode table, String type) {
|
||||
for (JsonNode key : table.path("KeySchema")) {
|
||||
if (type.equals(key.path("KeyType").asText())) {
|
||||
return key.path("AttributeName").asText();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String tableName(JsonNode request) {
|
||||
JsonNode value = request.get("TableName");
|
||||
if (value == null || !value.isTextual() || value.asText().isBlank()) {
|
||||
throw invalid("TableName is required");
|
||||
}
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
private static JsonNode requiredObject(JsonNode parent, String name) {
|
||||
JsonNode value = parent.get(name);
|
||||
if (value == null || !value.isObject()) {
|
||||
throw invalid(name + " must be an object");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static ObjectNode fields(JsonNode source, String... names) {
|
||||
ObjectNode result = object();
|
||||
for (String name : names) {
|
||||
if (source.hasNonNull(name)) {
|
||||
result.set(name, source.get(name).deepCopy());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ObjectNode object() {
|
||||
return JsonNodeFactory.instance.objectNode();
|
||||
}
|
||||
|
||||
private static Reply body(Reply reply, ObjectNode body) {
|
||||
return new Reply(reply.status(), body, reply.headers());
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("com.amazon.coral.validate#ValidationException", message, 400);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
@@ -19,6 +21,23 @@ public final class DynamoDbResponses {
|
||||
|
||||
private DynamoDbResponses() {}
|
||||
|
||||
public static Response withLegacyErrorNamespace(Response response, ObjectMapper objectMapper) {
|
||||
if (response.getStatus() < 400 || response.getEntity() == null) {
|
||||
return response;
|
||||
}
|
||||
JsonNode body = objectMapper.valueToTree(response.getEntity());
|
||||
if (!(body instanceof ObjectNode error) || !error.path("__type").isTextual()) {
|
||||
return response;
|
||||
}
|
||||
String type = error.path("__type").asText();
|
||||
if (type.startsWith("com.amazon.coral.")) {
|
||||
return response;
|
||||
}
|
||||
ObjectNode legacyError = error.deepCopy();
|
||||
legacyError.put("__type", "com.amazonaws.dynamodb.v20111205#" + type.substring(type.lastIndexOf('#') + 1));
|
||||
return Response.fromResponse(response).entity(legacyError).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-serialize the response entity and attach an {@code X-Amz-Crc32} header whose value
|
||||
* is the decimal CRC32 of the serialized bytes.
|
||||
|
||||
Reference in new issue
Block a user