From 5bad6774f64beb9debec2629b860a6fe68be0865 Mon Sep 17 00:00:00 2001 From: Mario Toffia Date: Fri, 25 Sep 2026 20:57:13 +0200 Subject: [PATCH] refactor(dynamodb): isolate backend operation execution (#4379) * refactor(dynamodb): route wire operations through a backend seam Rename the native wire handlers to NativeDynamoDbJsonHandler and NativeDynamoDbStreamsJsonHandler. Add DynamoDbOperations as the raw operation seam, plus typed DynamoDbItemAccess and DynamoDbTableAccess contracts. Add NativeDynamoDbBackend behind the seam and DynamoDbBackendSelector as the one immutable selection. Keep DynamoDbJsonHandler and DynamoDbStreamsJsonHandler as thin entry points that resolve account and region. Add RequestScopes.callAsChecked and let AslExecutor delegate to it. * refactor(dynamodb): route Java consumers through DynamoDbFacade DynamoDbFacade hands out the selected item and table capabilities and is now the one DynamoDB Resource Explorer provider in place of DynamoDbService. CloudFormation, Step Functions, the IAM condition context and the Redshift backfill call it with an explicit scope; the IoT dynamoDBv2 action writes as the rule's owning account. --- docs/services/iot.md | 2 +- .../common/IamConditionContextResolver.java | 15 +- .../floci/core/common/RequestScopes.java | 35 +- .../provisioners/DynamoDbCfnProvisioner.java | 43 +- .../services/dynamodb/DynamoDbFacade.java | 57 + .../dynamodb/DynamoDbJsonHandler.java | 3155 +--------------- .../dynamodb/DynamoDbPartiQLHandler.java | 4 +- .../services/dynamodb/DynamoDbService.java | 12 +- .../dynamodb/DynamoDbStreamsJsonHandler.java | 175 +- .../dynamodb/NativeDynamoDbJsonHandler.java | 3171 +++++++++++++++++ .../NativeDynamoDbStreamsJsonHandler.java | 183 + .../backend/DynamoDbBackendSelector.java | 36 + .../dynamodb/backend/DynamoDbItemAccess.java | 28 + .../dynamodb/backend/DynamoDbOperations.java | 49 + .../dynamodb/backend/DynamoDbTableAccess.java | 49 + .../backend/NativeDynamoDbBackend.java | 185 + .../floci/services/iot/IotService.java | 18 +- .../RedshiftDynamoDbZeroEtlConsumer.java | 25 +- .../services/stepfunctions/AslExecutor.java | 82 +- .../IamConditionContextResolverTest.java | 14 +- .../cloudformation/CfnProvisionerFixture.java | 7 +- .../DynamoDbCfnProvisionerTest.java | 7 +- .../DynamoDbGsiSortKeyRestartTest.java | 6 +- .../dynamodb/DynamoDbItemSizeServiceTest.java | 4 +- .../DynamoDbStreamViewTypeDurabilityTest.java | 6 +- ...ava => NativeDynamoDbJsonHandlerTest.java} | 8 +- .../backend/DynamoDbBackendSelectionTest.java | 90 + .../dynamodb/backend/DynamoDbFacadeTest.java | 199 ++ .../backend/DynamoDbNativeBackendTest.java | 195 + .../backend/RecordingDynamoDbBackend.java | 151 + .../floci/services/iot/IotServiceTest.java | 13 +- .../services/iot/IotServiceTestSupport.java | 4 +- .../RedshiftDynamoDbZeroEtlConsumerTest.java | 30 +- ...AslExecutorArrayAndMathIntrinsicsTest.java | 4 +- .../AslExecutorBranchHistoryEventsTest.java | 4 +- .../stepfunctions/AslExecutorCatchTest.java | 4 +- .../AslExecutorChoiceRuntimeTest.java | 4 +- ...AslExecutorCustomResourceLivenessTest.java | 4 +- .../AslExecutorEcsRunTaskModeTest.java | 4 +- .../AslExecutorErrorTerminationTest.java | 4 +- .../AslExecutorFailStateErrorCauseTest.java | 4 +- .../AslExecutorHistoryEventLimitTest.java | 4 +- .../AslExecutorHttpInvokeTest.java | 4 +- .../AslExecutorIntrinsicFunctionsTest.java | 4 +- ...lExecutorIntrinsicMissingArgumentTest.java | 4 +- .../AslExecutorJsonMergeTest.java | 4 +- .../AslExecutorLambdaInvokeResultTest.java | 4 +- .../AslExecutorMockedResponsesTest.java | 4 +- .../AslExecutorNestedQueryLanguageTest.java | 4 +- .../AslExecutorNestedStartExecutionTest.java | 4 +- .../AslExecutorPathIntrinsicsTest.java | 4 +- .../AslExecutorResultPathTest.java | 4 +- .../AslExecutorResultWriterTest.java | 4 +- .../stepfunctions/AslExecutorRetryTest.java | 4 +- .../AslExecutorStatePathTest.java | 4 +- .../AslExecutorTaskHistoryEventsTest.java | 46 +- .../AslExecutorTerminalStateTest.java | 4 +- .../AslExecutorWaitStateTest.java | 4 +- tools/docs/services.yaml | 4 +- 59 files changed, 4716 insertions(+), 3488 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbFacade.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelector.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbItemAccess.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbOperations.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java rename src/test/java/io/github/hectorvent/floci/services/dynamodb/{DynamoDbJsonHandlerTest.java => NativeDynamoDbJsonHandlerTest.java} (99%) create mode 100644 src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelectionTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java diff --git a/docs/services/iot.md b/docs/services/iot.md index 1a17698f91..8a1524641c 100644 --- a/docs/services/iot.md +++ b/docs/services/iot.md @@ -219,7 +219,7 @@ Supported rule behavior: - `sqs` action sends to an SQS queue through Floci's SQS service boundary. - `sns` action publishes to an SNS topic through Floci's SNS service boundary. - `s3` action writes to the configured bucket/key through Floci's S3 service boundary. -- `dynamoDBv2` action writes JSON object fields as DynamoDB attribute values through Floci's DynamoDB service boundary. +- `dynamoDBv2` action writes JSON object fields as DynamoDB attribute values through Floci's DynamoDB service boundary, as the account that owns the rule. - `kinesis` action puts the document into a Kinesis stream through Floci's Kinesis service boundary. - `lambda` action invokes the configured function ARN through Floci's Lambda service boundary. - `firehose` action puts the document into a Kinesis Data Firehose delivery stream through Floci's Firehose service boundary, with `separator` appended to each record; the separator must be `\n`, `\t`, `\r\n` or `,`, as the API model requires, or the rule is rejected with `InvalidRequestException`. With `batchMode`, a JSON array document becomes one record per element. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java index af9867c9a0..f468af4554 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java @@ -3,7 +3,7 @@ package io.github.hectorvent.floci.core.common; import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.dynamodb.DynamoDbConditionKeys; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Tag; @@ -54,19 +54,19 @@ public class IamConditionContextResolver { public static final String EXISTING_OBJECT_TAG_PREFIX = "s3:ExistingObjectTag/"; public static final String REQUEST_OBJECT_TAG_PREFIX = "s3:RequestObjectTag/"; - private final Instance dynamoDbService; + private final Instance dynamoDbFacade; private final Instance ec2Service; private final Instance s3Service; private final RequestContext requestContext; private final EmulatorConfig config; @Inject - public IamConditionContextResolver(Instance dynamoDbService, + public IamConditionContextResolver(Instance dynamoDbFacade, Instance ec2Service, Instance s3Service, RequestContext requestContext, EmulatorConfig config) { - this.dynamoDbService = dynamoDbService; + this.dynamoDbFacade = dynamoDbFacade; this.ec2Service = ec2Service; this.s3Service = s3Service; this.requestContext = requestContext; @@ -529,18 +529,19 @@ public class IamConditionContextResolver { /** * 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 service, and via + * Instance so core.common keeps no hard dependency on the DynamoDB facade, and via * {@code findTable} rather than {@code describeTable} so the O(items) item-count refresh * never runs on the enforcement hot path. */ private TableDefinition describeTargetTable(JsonNode body) { String tableName = targetTableName(body); - if (tableName == null || !dynamoDbService.isResolvable()) { + if (tableName == null || !dynamoDbFacade.isResolvable()) { return null; } String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); - return dynamoDbService.get().findTable(tableName, region).orElse(null); + DynamoDbFacade dynamoDb = dynamoDbFacade.get(); + return dynamoDb.tables().findTable(dynamoDb.scope(region), tableName).orElse(null); } /** diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java index d8f575de26..539b868f30 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java @@ -1,7 +1,10 @@ package io.github.hectorvent.floci.core.common; import io.quarkus.arc.Arc; +import io.quarkus.arc.ArcContainer; +import io.quarkus.arc.ManagedContext; +import java.util.concurrent.Callable; import java.util.function.Supplier; /** Runs work that happens outside an HTTP request, such as a background worker, as a given account. */ @@ -21,20 +24,36 @@ public final class RequestScopes { } public static T callAs(String accountId, Supplier body) { - var container = Arc.container(); - if (accountId == null || container == null || !container.isRunning()) { - return body.get(); + try { + return callAsChecked(accountId, body::get); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + // A Supplier cannot throw a checked exception, so this is unreachable in practice. + throw new IllegalStateException(e); } - var requestContext = container.requestContext(); - var alreadyActive = requestContext.isActive(); + } + + /** + * {@link #callAs} for a body that throws checked exceptions, which propagate unchanged. Runs + * the body directly when {@code accountId} is null or Arc is not running; restores the previous + * account when the request scope was already active, and terminates the scope it activated. + */ + public static T callAsChecked(String accountId, Callable body) throws Exception { + ArcContainer container = Arc.container(); + if (accountId == null || container == null || !container.isRunning()) { + return body.call(); + } + ManagedContext requestContext = container.requestContext(); + boolean alreadyActive = requestContext.isActive(); if (!alreadyActive) { requestContext.activate(); } - var ctx = container.instance(RequestContext.class).get(); - var previousAccountId = alreadyActive ? ctx.getAccountId() : null; + RequestContext ctx = container.instance(RequestContext.class).get(); + String previousAccountId = alreadyActive ? ctx.getAccountId() : null; try { ctx.setAccountId(accountId); - return body.get(); + return body.call(); } finally { if (!alreadyActive) { requestContext.terminate(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java index d1f31a04ad..477fe2edeb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java @@ -4,7 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex; import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; @@ -49,11 +50,11 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { private static final String REPLICA_SKIP_DELETION_ATTR = "__FlociDynamoDbReplicaSkipDeletion"; private static final int TABLE_NAME_MAX_LENGTH = 255; - private final DynamoDbService dynamoDbService; + private final DynamoDbFacade dynamoDb; @Inject - public DynamoDbCfnProvisioner(DynamoDbService dynamoDbService) { - this.dynamoDbService = dynamoDbService; + public DynamoDbCfnProvisioner(DynamoDbFacade dynamoDb) { + this.dynamoDb = dynamoDb; } @Override @@ -88,7 +89,8 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { switch (resourceType) { case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" -> CfnDeletes.safeDelete( "DynamoDB table", physicalId, - () -> dynamoDbService.deleteTable(physicalId, region), + // Deletes get no ProvisionContext; the engine and Cloud Control run them as the stack account. + () -> dynamoDb.tables().deleteTable(dynamoDb.scope(region), physicalId), "ResourceNotFoundException"); // Nothing to derive from the id alone once the attributes are gone; the replica stays. case "Custom::DynamoDBReplica" -> LOG.warnv( @@ -180,24 +182,25 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { attrDefs.add(new AttributeDefinition("id", "S")); } + Scope scope = new Scope(ctx.accountId(), region); TableDefinition table; try { - table = dynamoDbService.createTable(tableName, keySchema, attrDefs, null, null, gsis, lsis, region); + table = dynamoDb.tables().createTable(scope, tableName, keySchema, attrDefs, null, null, gsis, lsis); } catch (AwsException e) { if (!"ResourceInUseException".equals(e.getErrorCode())) { throw e; } - table = dynamoDbService.describeTable(tableName, region); + table = dynamoDb.tables().describeTable(scope, tableName); } Map tags = parseCfnTags(props != null ? props.get("Tags") : null, engine); List staleTags = ProvisionContext.staleTagKeys( - dynamoDbService.listTagsOfResource(table.getTableArn(), region), tags); + dynamoDb.tables().listTagsOfResource(scope, table.getTableArn()), tags); if (!staleTags.isEmpty()) { - dynamoDbService.untagResource(table.getTableArn(), staleTags, region); + dynamoDb.tables().untagResource(scope, table.getTableArn(), staleTags); } if (!tags.isEmpty()) { - dynamoDbService.tagResource(table.getTableArn(), tags, region); + dynamoDb.tables().tagResource(scope, table.getTableArn(), tags); } // A template that declares StreamSpecification wants a stream. Unlike the DynamoDB API, @@ -213,9 +216,9 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { String viewType = streamSpec.has("StreamViewType") ? engine.resolve(streamSpec.get("StreamViewType")) : null; - table = dynamoDbService.enableStream(tableName, viewType, region); + table = dynamoDb.tables().enableStream(scope, tableName, viewType); } else if (table.isStreamEnabled()) { - table = dynamoDbService.disableStream(tableName, region); + table = dynamoDb.tables().disableStream(scope, tableName); } r.setPhysicalId(tableName); @@ -263,11 +266,12 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { } } - TableDefinition table = dynamoDbService.describeTable(tableName, localRegion); + Scope scope = new Scope(ctx.accountId(), localRegion); + TableDefinition table = dynamoDb.tables().describeTable(scope, tableName); // This resource is a global table, so mark it homed in the deployment region even when it // declares no other replica: DescribeTable then lists the home region as an ACTIVE replica, // the single-region global table AWS reports (and CDK TableV2 emits by default). - dynamoDbService.ensureGlobalTable(tableName, localRegion); + dynamoDb.tables().ensureGlobalTable(scope, tableName); List existing = table.getReplicaRegions(); List toAdd = new ArrayList<>(); for (String replicaRegion : declared) { @@ -284,7 +288,7 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { if (toAdd.isEmpty() && toRemove.isEmpty()) { return; } - dynamoDbService.applyReplicaUpdates(tableName, toAdd, toRemove, localRegion); + dynamoDb.tables().applyReplicaUpdates(scope, tableName, toAdd, toRemove); } private void provisionReplica(StackResource r, JsonNode props, ProvisionContext ctx) { @@ -311,8 +315,8 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { : List.of(); // Validate and persist replacement as one operation so an old-replica removal failure // cannot leave the new replica applied while the resource still points at the old region. - dynamoDbService.applyReplicaUpdates( - tableName, List.of(replicaRegion), removeRegions, ctx.region()); + dynamoDb.tables().applyReplicaUpdates( + new Scope(ctx.accountId(), ctx.region()), tableName, List.of(replicaRegion), removeRegions); r.setPhysicalId(tableName + "-" + replicaRegion); r.getAttributes().put(REPLICA_TABLE_NAME_ATTR, tableName); r.getAttributes().put(REPLICA_REGION_ATTR, replicaRegion); @@ -340,8 +344,9 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { String removedTableName = tableName; String removedRegion = replicaRegion; CfnDeletes.safeDelete("DynamoDB replica", removedTableName + "-" + removedRegion, - () -> dynamoDbService.applyReplicaUpdates( - removedTableName, List.of(), List.of(removedRegion), region), + () -> dynamoDb.tables().applyReplicaUpdates( + // Ambient stack account, as in delete(String, String, String). + dynamoDb.scope(region), removedTableName, List.of(), List.of(removedRegion)), "ResourceNotFoundException"); } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbFacade.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbFacade.java new file mode 100644 index 0000000000..77fc27d0d2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbFacade.java @@ -0,0 +1,57 @@ +package io.github.hectorvent.floci.services.dynamodb; + +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.resource.ExplorerResource; +import io.github.hectorvent.floci.core.resource.ResourceProvider; +import io.github.hectorvent.floci.core.resource.SupportedResourceType; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbItemAccess; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbTableAccess; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Set; + +/** + * The injection boundary for Java consumers of DynamoDB: CloudFormation, IoT, Step Functions + * optimized integrations, the IAM condition context, the Redshift zero-ETL backfill and Resource + * Explorer. It hands out the selected backend capabilities and never touches native storage itself. + */ +@ApplicationScoped +public class DynamoDbFacade implements ResourceProvider { + + private final DynamoDbItemAccess items; + private final DynamoDbTableAccess tables; + private final RegionResolver regionResolver; + + @Inject + public DynamoDbFacade(DynamoDbItemAccess items, DynamoDbTableAccess tables, RegionResolver regionResolver) { + this.items = items; + this.tables = tables; + this.regionResolver = regionResolver; + } + + /** The ambient request account in {@code region}. */ + public Scope scope(String region) { + return new Scope(regionResolver.getAccountId(), region); + } + + public DynamoDbItemAccess items() { + return items; + } + + public DynamoDbTableAccess tables() { + return tables; + } + + @Override + public List getResources() { + return tables.resources(regionResolver.getAccountId()); + } + + @Override + public Set getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java index 1022df9496..3f30b316a0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java @@ -1,3154 +1,49 @@ 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.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import io.github.hectorvent.floci.core.common.AwsArnUtils; -import io.github.hectorvent.floci.core.common.AwsErrorResponse; -import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.common.AwsJsonController; -import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.CreateTableRequest; -import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.GsiThroughputUpdate; -import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.OnDemandThroughput; -import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.TableSettings; -import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.Throughput; -import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.UpdateTableRequest; -import io.github.hectorvent.floci.services.dynamodb.model.*; -import io.github.hectorvent.floci.services.kinesis.KinesisService; +import io.github.hectorvent.floci.core.common.RegionResolver; +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 jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; -import java.util.*; -import java.util.function.Supplier; +import java.util.List; +import java.util.Map; /** - * DynamoDB JSON protocol handler. - * Called by {@link AwsJsonController} for DynamoDB-targeted requests. + * The public DynamoDB entry point used by the JSON and CBOR controllers, API Gateway AWS + * integrations, AppSync and Step Functions. It resolves the caller's account and region and + * dispatches through the selected backend. CRC32, JSON 1.0 and CBOR conversion stay in the controllers. */ @ApplicationScoped public class DynamoDbJsonHandler { - private static final String SSE_TYPE_KMS = "KMS"; - - private final DynamoDbService dynamoDbService; - private final NativeDynamoDbTableService tableService; - private final ObjectMapper objectMapper; - private final DynamoDbPartiQLHandler partiQLHandler; - private final Object importLock = new Object(); + private final DynamoDbOperations operations; + private final RegionResolver regionResolver; @Inject - public DynamoDbJsonHandler(DynamoDbService dynamoDbService, NativeDynamoDbTableService tableService, - ObjectMapper objectMapper) { - this.dynamoDbService = dynamoDbService; - this.tableService = tableService; - this.objectMapper = objectMapper; - this.partiQLHandler = new DynamoDbPartiQLHandler(dynamoDbService, objectMapper); - } - - /** Package-private constructor for testing. */ - DynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService, - KinesisService kinesisService, ObjectMapper objectMapper) { - this(dynamoDbService, new NativeDynamoDbTableService(dynamoDbService, dynamoDbStreamService, kinesisService), - objectMapper); + public DynamoDbJsonHandler(DynamoDbOperations operations, RegionResolver regionResolver) { + this.operations = operations; + this.regionResolver = regionResolver; } public Response handle(String action, JsonNode request, String region) throws Exception { - return switch (action) { - case "CreateTable" -> handleCreateTable(request, region); - case "DeleteTable" -> handleDeleteTable(request, region); - case "DescribeTable" -> handleDescribeTable(request, region); - case "ListTables" -> handleListTables(request, region); - case "PutItem" -> handlePutItem(request, region); - case "GetItem" -> handleGetItem(request, region); - case "DeleteItem" -> handleDeleteItem(request, region); - case "UpdateItem" -> handleUpdateItem(request, region); - case "Query" -> handleQuery(request, region); - case "Scan" -> handleScan(request, region); - case "SearchVectors" -> handleSearchVectors(request, region); - case "BatchWriteItem" -> handleBatchWriteItem(request, region); - case "BatchGetItem" -> handleBatchGetItem(request, region); - case "UpdateTable" -> handleUpdateTable(request, region); - case "DescribeTimeToLive" -> handleDescribeTimeToLive(request, region); - case "UpdateTimeToLive" -> handleUpdateTimeToLive(request, region); - case "DescribeContinuousBackups" -> handleDescribeContinuousBackups(request, region); - case "UpdateContinuousBackups" -> handleUpdateContinuousBackups(request, region); - case "TransactWriteItems" -> handleTransactWriteItems(request, region); - case "TransactGetItems" -> handleTransactGetItems(request, region); - case "TagResource" -> handleTagResource(request, region); - case "UntagResource" -> handleUntagResource(request, region); - case "ListTagsOfResource" -> handleListTagsOfResource(request, region); - case "PutResourcePolicy" -> handlePutResourcePolicy(request, region); - case "GetResourcePolicy" -> handleGetResourcePolicy(request, region); - case "DeleteResourcePolicy" -> handleDeleteResourcePolicy(request, region); - case "EnableKinesisStreamingDestination" -> handleEnableKinesisStreamingDestination(request, region); - case "DisableKinesisStreamingDestination" -> handleDisableKinesisStreamingDestination(request, region); - case "DescribeKinesisStreamingDestination" -> handleDescribeKinesisStreamingDestination(request, region); - case "ExportTableToPointInTime" -> handleExportTable(request, region); - case "CreateGlobalTable" -> handleCreateGlobalTable(request, region); - case "DescribeGlobalTable" -> handleDescribeGlobalTable(request, region); - case "UpdateGlobalTable" -> handleUpdateGlobalTable(request, region); - case "ListGlobalTables" -> handleListGlobalTables(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); - default -> Response.status(400) - .entity(new AwsErrorResponse("UnknownOperationException", "Operation " + action + " is not supported.")) - .build(); - - }; - } - - 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; - String tableName = DynamoDbTableNames.requireShortName(tableNameRaw); - - List keySchema = new ArrayList<>(); - request.path("KeySchema").forEach(ks -> - keySchema.add(new KeySchemaElement( - ks.path("AttributeName").asText(), - ks.path("KeyType").asText()))); - - List attrDefs = new ArrayList<>(); - request.path("AttributeDefinitions").forEach(ad -> - attrDefs.add(new AttributeDefinition( - ad.path("AttributeName").asText(), - ad.path("AttributeType").asText()))); - - JsonNode pt = request.path("ProvisionedThroughput"); - Throughput throughput = null; - if (!pt.isMissingNode()) { - throughput = new Throughput( - pt.path("ReadCapacityUnits").asLong(5), pt.path("WriteCapacityUnits").asLong(5)); - } - - List gsis = new ArrayList<>(); - JsonNode gsiArray = request.path("GlobalSecondaryIndexes"); - if (!gsiArray.isMissingNode() && gsiArray.isArray()) { - var gsiPosition = 0; - for (JsonNode gsiNode : gsiArray) { - gsiPosition++; - String indexName = gsiNode.path("IndexName").asText(); - List gsiKeySchema = new ArrayList<>(); - gsiNode.path("KeySchema").forEach(ks -> - gsiKeySchema.add(new KeySchemaElement( - ks.path("AttributeName").asText(), - ks.path("KeyType").asText()))); - String projectionType = gsiNode.path("Projection").path("ProjectionType").asText("ALL"); - JsonNode nonKeyAttrArray = gsiNode.path("Projection").path("NonKeyAttributes"); - List nonKeyAttributes = new ArrayList<>(); - if (!nonKeyAttrArray.isMissingNode() && nonKeyAttrArray.isArray()){ - for (JsonNode nonKeyAttr : nonKeyAttrArray){ - nonKeyAttributes.add(nonKeyAttr.asText()); - } - } - rejectEmptyNonKeyAttributes(nonKeyAttrArray, "globalSecondaryIndexes." + gsiPosition + ".member"); - validateProjectionSpec(projectionType, nonKeyAttributes); - GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes); - JsonNode gsiPt = gsiNode.path("ProvisionedThroughput"); - if (!gsiPt.isMissingNode()) { - gsi.getProvisionedThroughput().setReadCapacityUnits(gsiPt.path("ReadCapacityUnits").asLong(0)); - gsi.getProvisionedThroughput().setWriteCapacityUnits(gsiPt.path("WriteCapacityUnits").asLong(0)); - } - JsonNode gsiOnDemand = gsiNode.path("OnDemandThroughput"); - if (gsiOnDemand.isObject()) { - if (gsiOnDemand.has("MaxReadRequestUnits")) { - gsi.setOnDemandMaxReadRequestUnits(gsiOnDemand.get("MaxReadRequestUnits").asInt()); - } - if (gsiOnDemand.has("MaxWriteRequestUnits")) { - gsi.setOnDemandMaxWriteRequestUnits(gsiOnDemand.get("MaxWriteRequestUnits").asInt()); - } - } - gsis.add(gsi); - } - } - - List lsis = new ArrayList<>(); - JsonNode lsiArray = request.path("LocalSecondaryIndexes"); - if (!lsiArray.isMissingNode() && lsiArray.isArray()) { - var lsiPosition = 0; - for (JsonNode lsiNode : lsiArray) { - lsiPosition++; - String indexName = lsiNode.path("IndexName").asText(); - List lsiKeySchema = new ArrayList<>(); - lsiNode.path("KeySchema").forEach(ks -> - lsiKeySchema.add(new KeySchemaElement( - ks.path("AttributeName").asText(), - ks.path("KeyType").asText()))); - String projectionType = lsiNode.path("Projection").path("ProjectionType").asText("ALL"); - JsonNode lsiNonKeyAttrArray = lsiNode.path("Projection").path("NonKeyAttributes"); - List lsiNonKeyAttributes = new ArrayList<>(); - if (!lsiNonKeyAttrArray.isMissingNode() && lsiNonKeyAttrArray.isArray()) { - lsiNonKeyAttrArray.forEach(a -> lsiNonKeyAttributes.add(a.asText())); - } - rejectEmptyNonKeyAttributes(lsiNonKeyAttrArray, "localSecondaryIndexes." + lsiPosition + ".member"); - validateProjectionSpec(projectionType, lsiNonKeyAttributes); - lsis.add(new LocalSecondaryIndex(indexName, lsiKeySchema, null, projectionType, lsiNonKeyAttributes)); - } - } - - List vectorIndexes = new ArrayList<>(); - JsonNode vectorIndexArray = request.path("VectorIndexes"); - if (vectorIndexArray.isArray()) { - int vectorPosition = 0; - for (JsonNode vectorIndexNode : vectorIndexArray) { - vectorPosition++; - String memberPath = "vectorIndexes." + vectorPosition + ".member"; - vectorIndexes.add(new DynamoDbService.VectorIndexCreate( - parseVectorIndex(vectorIndexNode, memberPath), memberPath)); - } - } - - Map tags = new LinkedHashMap<>(); - JsonNode tagsNode = request.path("Tags"); - if (tagsNode.isArray()) { - for (JsonNode tag : tagsNode) { - tags.put(tag.path("Key").asText(), tag.path("Value").asText()); - } - } - - return tableService.createTable(new CreateTableRequest(tableName, keySchema, attrDefs, - throughput, gsis, lsis, vectorIndexes, tags, parseTableSettings(request)), initialStatus, region); - } - - /** - * The table-level settings CreateTable and UpdateTable share. A member absent from the request - * is null; the service applies the per-operation defaults. - */ - private static TableSettings parseTableSettings(JsonNode request) { - String billingMode = request.has("BillingMode") ? request.get("BillingMode").asText() : null; - - JsonNode deletionProtectionNode = request.path("DeletionProtectionEnabled"); - Boolean deletionProtection = deletionProtectionNode.isMissingNode() - ? null : deletionProtectionNode.asBoolean(); - - String tableClass = request.has("TableClass") ? request.get("TableClass").asText() : null; - - JsonNode streamSpec = request.path("StreamSpecification"); - Boolean streamEnabled = streamSpec.isMissingNode() - ? null : streamSpec.path("StreamEnabled").asBoolean(false); - String streamViewType = streamSpec.hasNonNull("StreamViewType") - ? streamSpec.get("StreamViewType").asText() : null; - - JsonNode sseSpec = request.path("SSESpecification"); - Boolean sseEnabled = sseSpec.isMissingNode() ? null : sseSpec.path("Enabled").asBoolean(false); - String sseType = sseSpec.hasNonNull("SSEType") ? sseSpec.get("SSEType").asText() : null; - JsonNode kmsMasterKeyIdNode = sseSpec.path("KMSMasterKeyId"); - String kmsMasterKeyId = kmsMasterKeyIdNode.isMissingNode() || kmsMasterKeyIdNode.isNull() - ? null : kmsMasterKeyIdNode.asText(); - - return new TableSettings(billingMode, deletionProtection, tableClass, - parseOnDemandThroughput(request.path("OnDemandThroughput")), - streamEnabled, streamViewType, sseEnabled, sseType, kmsMasterKeyId); - } - - private static OnDemandThroughput parseOnDemandThroughput(JsonNode onDemand) { - if (!onDemand.isObject()) { - return null; - } - Integer maxRead = onDemand.has("MaxReadRequestUnits") ? onDemand.get("MaxReadRequestUnits").asInt() : null; - Integer maxWrite = onDemand.has("MaxWriteRequestUnits") ? onDemand.get("MaxWriteRequestUnits").asInt() : null; - return new OnDemandThroughput(maxRead, maxWrite); - } - - // AWS reports an empty list as a length constraint on the 1-based member path, before the - // projection type check. A null NonKeyAttributes counts as not specified. - private static void rejectEmptyNonKeyAttributes(JsonNode nonKeyAttrArray, String memberPath) { - if (nonKeyAttrArray.isArray() && nonKeyAttrArray.isEmpty()) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '[]' at '" + memberPath - + ".projection.nonKeyAttributes' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1", 400); - } - } - - /** Reads a VectorIndex or the CreateVectorIndexAction of a VectorIndexUpdate; same members. */ - private static VectorIndex parseVectorIndex(JsonNode node, String memberPath) { - // An absent VectorAttribute is reported as the member itself, one that is present but - // carries no AttributeName as the nested member. Only the request shape tells them apart. - JsonNode vectorAttribute = node.path("VectorAttribute"); - if (vectorAttribute.isObject() && !vectorAttribute.hasNonNull("AttributeName")) { - throw new AwsException("ValidationException", - "1 validation error detected: Value null at '" + memberPath - + ".vectorAttribute.attributeName' failed to satisfy constraint: " - + "Member must not be null", 400); - } - List searchSchema = new ArrayList<>(); - JsonNode searchSchemaArray = node.path("SearchSchema"); - if (searchSchemaArray.isArray()) { - for (JsonNode element : searchSchemaArray) { - searchSchema.add(new SearchSchemaElement( - element.path("AttributeName").asText(null), - element.path("SearchSchemaElementType").asText(null))); - } - } - String projectionType = node.hasNonNull("Projection") - ? node.path("Projection").path("ProjectionType").asText("ALL") : null; - List nonKeyAttributes = new ArrayList<>(); - JsonNode nonKeyAttrArray = node.path("Projection").path("NonKeyAttributes"); - if (nonKeyAttrArray.isArray()) { - for (JsonNode nonKeyAttr : nonKeyAttrArray) { - nonKeyAttributes.add(nonKeyAttr.asText()); - } - } - rejectEmptyNonKeyAttributes(nonKeyAttrArray, memberPath); - validateProjectionSpec(projectionType, nonKeyAttributes); - Long dimensions = node.hasNonNull("Dimensions") ? node.get("Dimensions").asLong() : null; - return new VectorIndex( - node.path("IndexName").asText(null), - node.path("VectorAttribute").path("AttributeName").asText(null), - searchSchema, - projectionType, - nonKeyAttributes, - dimensions, - node.path("DistanceFunction").asText(null)); - } - - // INCLUDE requires the NonKeyAttributes list; every other projection type forbids it. - private static void validateProjectionSpec(String projectionType, List nonKeyAttributes) { - if ("INCLUDE".equals(projectionType) && nonKeyAttributes.isEmpty()) { - throw new AwsException("ValidationException", - "One or more parameter values were invalid: " - + "ProjectionType is INCLUDE, but NonKeyAttributes is not specified", 400); - } - if (!"INCLUDE".equals(projectionType) && !nonKeyAttributes.isEmpty()) { - throw new AwsException("ValidationException", - "One or more parameter values were invalid: " - + "ProjectionType is " + projectionType + ", but NonKeyAttributes is specified", 400); - } - } - - private Response handleDeleteTable(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - TableDefinition table = dynamoDbService.describeTable(tableName, region); - if (table.isDeletionProtectionEnabled()) { - throw new AwsException("ValidationException", - "Table " + tableName + " is protected against deletion. To delete the table, " - + "DeletionProtectionEnabled must be set to false.", 400); - } - ObjectNode response = objectMapper.createObjectNode(); - response.set("TableDescription", tableToNode(table)); - dynamoDbService.deleteTable(tableName, region); - return Response.ok(response).build(); - } - - // ── Global tables, the 2017.11.29 API ──────────────────────────────────── - - private Response handleCreateGlobalTable(JsonNode request, String region) { - String name = request.path("GlobalTableName").asText(); - TableDefinition table = dynamoDbService.createGlobalTable( - name, replicationGroupRegions(request), region); - ObjectNode root = objectMapper.createObjectNode(); - root.set("GlobalTableDescription", globalTableDescription(table, name)); - return Response.ok(root).build(); - } - - private Response handleDescribeGlobalTable(JsonNode request, String region) { - String name = request.path("GlobalTableName").asText(); - TableDefinition table = dynamoDbService.describeGlobalTable(name, region); - ObjectNode root = objectMapper.createObjectNode(); - root.set("GlobalTableDescription", globalTableDescription(table, name)); - return Response.ok(root).build(); - } - - private Response handleUpdateGlobalTable(JsonNode request, String region) { - String name = request.path("GlobalTableName").asText(); - List adds = new ArrayList<>(); - List removes = new ArrayList<>(); - for (JsonNode update : request.path("ReplicaUpdates")) { - String create = update.path("Create").path("RegionName").asText(null); - String delete = update.path("Delete").path("RegionName").asText(null); - if (create != null) { - adds.add(create); - } - if (delete != null) { - removes.add(delete); - } - } - TableDefinition table = dynamoDbService.updateGlobalTable(name, adds, removes, region); - ObjectNode root = objectMapper.createObjectNode(); - root.set("GlobalTableDescription", globalTableDescription(table, name)); - return Response.ok(root).build(); - } - - private Response handleListGlobalTables(JsonNode request, String region) { - String regionFilter = request.path("RegionName").asText(null); - ArrayNode list = objectMapper.createArrayNode(); - for (TableDefinition table : dynamoDbService.listGlobalTables(regionFilter, region)) { - ObjectNode entry = objectMapper.createObjectNode(); - entry.put("GlobalTableName", table.getTableName()); - entry.set("ReplicationGroup", replicaNodes(table, objectMapper.createArrayNode(), false)); - list.add(entry); - } - ObjectNode root = objectMapper.createObjectNode(); - root.set("GlobalTables", list); - return Response.ok(root).build(); - } - - private static List replicationGroupRegions(JsonNode request) { - List regions = new ArrayList<>(); - for (JsonNode replica : request.path("ReplicationGroup")) { - String name = replica.path("RegionName").asText(null); - if (name != null && !name.isBlank()) { - regions.add(name); - } - } - return regions; - } - - private ObjectNode globalTableDescription(TableDefinition table, String globalTableName) { - ObjectNode description = objectMapper.createObjectNode(); - description.put("GlobalTableName", globalTableName); - description.put("GlobalTableStatus", "ACTIVE"); - description.put("GlobalTableArn", table.getTableArn()); - if (table.getCreationDateTime() != null) { - description.put("CreationDateTime", table.getCreationDateTime().getEpochSecond()); - } - description.set("ReplicationGroup", replicaNodes(table, objectMapper.createArrayNode(), true)); - return description; - } - - /** - * The replica list of a global table: every tracked replica plus the home region, which AWS - * reports as a replica of its own global table. ReplicaStatus is only carried by the - * description shapes, not by the ListGlobalTables entry. - */ - private ArrayNode replicaNodes(TableDefinition table, ArrayNode replicas, boolean withStatus) { - LinkedHashSet regions = new LinkedHashSet<>( - table.getReplicaRegions() != null ? table.getReplicaRegions() : List.of()); - if (table.getGlobalTableHomeRegion() != null) { - regions.add(table.getGlobalTableHomeRegion()); - } - for (String replicaRegion : regions) { - ObjectNode replica = objectMapper.createObjectNode(); - replica.put("RegionName", replicaRegion); - if (withStatus) { - replica.put("ReplicaStatus", "ACTIVE"); - } - replicas.add(replica); - } - return replicas; - } - - private Response handleDescribeTable(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - TableDefinition table = dynamoDbService.describeTable(tableName, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.set("Table", tableToNode(table)); - return Response.ok(response).build(); - } - - private Response handleListTables(JsonNode request, String region) { - Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; - String exclusiveStart = request.has("ExclusiveStartTableName") - ? request.get("ExclusiveStartTableName").asText() : null; - - if (limit != null) { - if (limit < 1) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + limit - + "' at 'limit' failed to satisfy constraint: " - + "Member must have value greater than or equal to 1", 400); - } - if (limit > 100) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + limit - + "' at 'limit' failed to satisfy constraint: " - + "Member must have value less than or equal to 100", 400); - } - } - - DynamoDbService.ListTablesResult result = dynamoDbService.listTables(region, limit, exclusiveStart); - - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode tableNames = objectMapper.createArrayNode(); - result.tableNames().forEach(tableNames::add); - response.set("TableNames", tableNames); - if (result.lastEvaluatedTableName() != null) { - response.put("LastEvaluatedTableName", result.lastEvaluatedTableName()); - } - return Response.ok(response).build(); - } - - private static final Set VALID_RETURN_VALUES_PUT = Set.of("NONE", "ALL_OLD"); - private static final Set VALID_RETURN_CONSUMED_CAPACITY = Set.of("INDEXES", "TOTAL", "NONE"); - private static final Set VALID_RETURN_ITEM_COLLECTION_METRICS = Set.of("SIZE", "NONE"); - - private Response handlePutItem(JsonNode request, String region) { - String tableName = request.has("TableName") ? request.path("TableName").asText() : null; - DynamoDbTableNames.resolve(tableName); // validate tableName before other params - JsonNode item = request.path("Item"); - String returnValues = request.path("ReturnValues").asText("NONE"); - String returnValuesOnConditionCheckFailure = request.path("ReturnValuesOnConditionCheckFailure").asText("NONE"); - String conditionExpression = request.has("ConditionExpression") - ? request.get("ConditionExpression").asText() : null; - JsonNode exprAttrNames = request.has("ExpressionAttributeNames") - ? request.get("ExpressionAttributeNames") : null; - JsonNode exprAttrValues = request.has("ExpressionAttributeValues") - ? request.get("ExpressionAttributeValues") : null; - - List validationErrors = new ArrayList<>(); - String rcc = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; - if (rcc != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rcc)) { - validationErrors.add("Value '" + rcc + "' at 'returnConsumedCapacity' failed to satisfy constraint: " - + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"); - } - String ricm = request.has("ReturnItemCollectionMetrics") ? request.get("ReturnItemCollectionMetrics").asText() : null; - if (ricm != null && !VALID_RETURN_ITEM_COLLECTION_METRICS.contains(ricm)) { - validationErrors.add("Value '" + ricm + "' at 'returnItemCollectionMetrics' failed to satisfy constraint: " - + "Member must satisfy enum value set: [SIZE, NONE]"); - } - if (!VALID_RETURN_VALUES_PUT.contains(returnValues)) { - validationErrors.add("Value '" + returnValues + "' at 'returnValues' failed to satisfy constraint: " - + "Member must satisfy enum value set: [NONE, ALL_OLD]"); - } - if (!validationErrors.isEmpty()) { - int n = validationErrors.size(); - throw new AwsException("ValidationException", - n + " validation error" + (n > 1 ? "s" : "") + " detected: " - + String.join("; ", validationErrors), 400); - } - DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(item); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, true); - - JsonNode expected = request.has("Expected") ? request.get("Expected") : null; - DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(expected)); - String conditionalOperator = request.has("ConditionalOperator") - ? request.get("ConditionalOperator").asText() : "AND"; - - if (conditionExpression != null && expected != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); - } - - // EAN/EAV with no expression to reference them: AWS reports "can only be specified - // when using expressions", not the "unused in expressions" wording (#2893). - rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues, - conditionExpression != null, "ConditionExpression is null"); - - ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues); - - // Reject ExpressionAttributeNames/Values entries not referenced by ConditionExpression (AWS parity, #2893) - checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression)); - checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression)); - - validateItemSets(item); - - JsonNode oldItem = null; - if ("ALL_OLD".equals(returnValues) || expected != null) { - dynamoDbService.requireTableForItemCall(tableName, region); - oldItem = dynamoDbService.getItem(tableName, item, region); - } - - if (expected != null) { - evaluateLegacyExpected(oldItem, expected, conditionalOperator, returnValuesOnConditionCheckFailure); - } - - var previousItem = dynamoDbService.putItem(tableName, item, conditionExpression, - exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure); - - ObjectNode response = objectMapper.createObjectNode(); - if ("ALL_OLD" .equals(returnValues) && oldItem != null) { - response.set("Attributes", oldItem); - } - addItemCollectionMetrics(response, request, tableName, item, region); - addWriteConsumedCapacity(response, request, tableName, region, previousItem, item); - return Response.ok(response).build(); - } - - private Response handleGetItem(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - JsonNode key = request.path("Key"); - String projectionExpression = request.has("ProjectionExpression") - ? request.get("ProjectionExpression").asText() : null; - JsonNode exprAttrNames = request.has("ExpressionAttributeNames") - ? request.get("ExpressionAttributeNames") : null; - JsonNode attributesToGet = request.has("AttributesToGet") ? request.get("AttributesToGet") : null; - - if (attributesToGet != null && projectionExpression != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); - } - - // Validate enums before table lookup - String rccGet = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; - if (rccGet != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccGet)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + rccGet + "' at 'returnConsumedCapacity' failed to satisfy constraint: " - + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); - } - - // Validate ProjectionExpression syntax and reserved words before item lookup - if (projectionExpression != null) { - DynamoDbExpressionSize.checkRead(projectionExpression, "ProjectionExpression"); - ProjectionEvaluator.validateExpression(projectionExpression, exprAttrNames); - } - - JsonNode item = dynamoDbService.getItem(tableName, key, region); - var itemBytes = item != null ? DynamoDbItemSize.calculateItemSize(item) : 0; - if (item != null && projectionExpression != null) { - item = ProjectionEvaluator.project(item, projectionExpression, exprAttrNames); - } else if (item != null && attributesToGet != null) { - Set keep = new HashSet<>(); - attributesToGet.forEach(n -> keep.add(n.asText())); - item = ProjectionEvaluator.trimToAttributes((ObjectNode) item, keep); - } - - ObjectNode response = objectMapper.createObjectNode(); - if (item != null) { - response.set("Item", item); - } - addConsumedCapacity(response, request, tableName, - readCapacityUnits(itemBytes, request.path("ConsistentRead").asBoolean(false)), null); - return Response.ok(response).build(); - } - - private static final Set VALID_RETURN_VALUES_DELETE = Set.of("NONE", "ALL_OLD"); - private static final Set VALID_RETURN_VALUES_UPDATE = - Set.of("NONE", "ALL_OLD", "ALL_NEW", "UPDATED_OLD", "UPDATED_NEW"); - - private Response handleDeleteItem(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - DynamoDbTableNames.resolve(tableName); // validate tableName first - JsonNode key = request.path("Key"); - String returnValues = request.path("ReturnValues").asText("NONE"); - String returnValuesOnConditionCheckFailure = request.path("ReturnValuesOnConditionCheckFailure").asText("NONE"); - String conditionExpression = request.has("ConditionExpression") - ? request.get("ConditionExpression").asText() : null; - JsonNode exprAttrNames = request.has("ExpressionAttributeNames") - ? request.get("ExpressionAttributeNames") : null; - JsonNode exprAttrValues = request.has("ExpressionAttributeValues") - ? request.get("ExpressionAttributeValues") : null; - - // Validate ReturnValues + ReturnConsumedCapacity together - List delValidationErrors = new ArrayList<>(); - String rccDel = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; - if (rccDel != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccDel)) { - delValidationErrors.add("Value '" + rccDel + "' at 'returnConsumedCapacity' failed to satisfy constraint: " - + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"); - } - if (!VALID_RETURN_VALUES_DELETE.contains(returnValues)) { - delValidationErrors.add("Value '" + returnValues + "' at 'returnValues' failed to satisfy constraint: " - + "Member must satisfy enum value set: [NONE, ALL_OLD]"); - } - if (!delValidationErrors.isEmpty()) { - int n = delValidationErrors.size(); - throw new AwsException("ValidationException", - n + " validation error" + (n > 1 ? "s" : "") + " detected: " - + String.join("; ", delValidationErrors), 400); - } - DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, true); - JsonNode expectedDel = request.has("Expected") ? request.get("Expected") : null; - DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(expectedDel)); - - if (conditionExpression != null && expectedDel != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); - } - - // EAN/EAV with no expression to reference them: AWS reports "can only be specified - // when using expressions", not the "unused in expressions" wording (#2893). - rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues, - conditionExpression != null, "ConditionExpression is null"); - - ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues); - - // Reject ExpressionAttributeNames/Values entries not referenced by ConditionExpression (AWS parity, #2893) - checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression)); - checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression)); - - String condOpDel = request.has("ConditionalOperator") - ? request.get("ConditionalOperator").asText() : "AND"; - if (expectedDel != null) { - JsonNode existingForDel = dynamoDbService.getItem(tableName, key, region); - evaluateLegacyExpected(existingForDel, expectedDel, condOpDel, returnValuesOnConditionCheckFailure); - } - - JsonNode oldItem = dynamoDbService.deleteItem(tableName, key, conditionExpression, - exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure); - - ObjectNode response = objectMapper.createObjectNode(); - if ("ALL_OLD" .equals(returnValues) && oldItem != null) { - response.set("Attributes", oldItem); - } - addItemCollectionMetrics(response, request, tableName, key, region); - addWriteConsumedCapacity(response, request, tableName, region, oldItem, null); - return Response.ok(response).build(); - } - - private Response handleUpdateItem(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - DynamoDbTableNames.resolve(tableName); // validate tableName first - JsonNode key = request.path("Key"); - JsonNode attributeUpdates = request.path("AttributeUpdates"); - JsonNode exprAttrNames = request.has("ExpressionAttributeNames") - ? request.get("ExpressionAttributeNames") : null; - JsonNode exprAttrValues = request.has("ExpressionAttributeValues") - ? request.get("ExpressionAttributeValues") : null; - String updateExpression = request.has("UpdateExpression") - ? request.get("UpdateExpression").asText() : null; - String conditionExpression = request.has("ConditionExpression") - ? request.get("ConditionExpression").asText() : null; - String returnValues = request.path("ReturnValues").asText("NONE"); - String returnValuesOnConditionCheckFailure = request.path("ReturnValuesOnConditionCheckFailure").asText("NONE"); - - // UpdateItem stops at the first invalid enum and reports one error, unlike PutItem - // and DeleteItem which aggregate. - String rccUpd = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; - if (!VALID_RETURN_VALUES_UPDATE.contains(returnValues)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + returnValues + "' at 'returnValues' " - + "failed to satisfy constraint: " - + "Member must satisfy enum value set: [NONE, ALL_OLD, ALL_NEW, UPDATED_OLD, UPDATED_NEW]", 400); - } - if (rccUpd != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccUpd)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + rccUpd + "' at 'returnConsumedCapacity' " - + "failed to satisfy constraint: " - + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); - } - DynamoDbExpressionSize.checkWrite(updateExpression, "UpdateExpression"); - DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, true); - var attributeUpdateValues = legacyValues(attributeUpdates); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(attributeUpdateValues); - DynamoDbNumberUtils.requireStorable(attributeUpdateValues, true); - DynamoDbAttributeValueValidator.requireNestingWithinLimit( - legacyValues(request.has("Expected") ? request.get("Expected") : null)); - - JsonNode updateData = attributeUpdates.isMissingNode() ? null : attributeUpdates; - JsonNode expectedUpd = request.has("Expected") ? request.get("Expected") : null; - String conditionalOperatorUpd = request.has("ConditionalOperator") - ? request.get("ConditionalOperator").asText() : "AND"; - - if (updateData != null && updateExpression != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {AttributeUpdates} Expression parameters: {UpdateExpression}", 400); - } - - // EAN/EAV with no expression to reference them, mirroring the PutItem guard. - rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues, - updateExpression != null || conditionExpression != null, - "UpdateExpression is null, ConditionExpression is null"); - - ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues); - - if (conditionExpression != null && expectedUpd != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); - } - - // Validate EAN/EAV usage across UpdateExpression + ConditionExpression - if (updateExpression != null) { - // Pre-validate syntax: expression must start with a valid clause keyword. - // AWS tokenizes UpdateExpression whitespace-insensitively, so collapse runs - // of whitespace (newlines, tabs, multiple spaces) before matching keywords. - String ue = updateExpression.trim().replaceAll("\\s+", " "); - if (!ue.isEmpty()) { - String upper = ue.toUpperCase(); - if (!upper.startsWith("SET ") && !upper.startsWith("REMOVE ") && !upper.startsWith("ADD ") && !upper.startsWith("DELETE ")) { - String[] parts = ue.split("\\s+", 3); - String token = parts[0]; - String near = parts.length >= 2 - ? (token + " " + parts[1]).substring(0, Math.min(token.length() + 1 + parts[1].length(), 20)) - : token; - throw new AwsException("ValidationException", - "Invalid UpdateExpression: Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400); - } - } - Set colonTokens = extractColonTokens(updateExpression); - for (String token : colonTokens) { - if (exprAttrValues == null || !exprAttrValues.has(token)) { - throw new AwsException("ValidationException", - "Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: " + token, 400); - } - } - Set hashTokens = extractHashTokens(updateExpression, conditionExpression); - checkUnusedEan(exprAttrNames, hashTokens); - Set colonTokensAll = extractColonTokens(updateExpression, conditionExpression); - checkUnusedEav(exprAttrValues, colonTokensAll); - dynamoDbService.requireAddOrDeleteOperandTypes(updateExpression, exprAttrValues, true); - } - - if (expectedUpd != null) { - JsonNode existingForUpd = dynamoDbService.getItem(tableName, key, region); - evaluateLegacyExpected(existingForUpd, expectedUpd, conditionalOperatorUpd, returnValuesOnConditionCheckFailure); - } - - DynamoDbService.UpdateResult result = dynamoDbService.updateItem( - tableName, key, updateData, updateExpression, exprAttrNames, exprAttrValues, - returnValues, conditionExpression, region, returnValuesOnConditionCheckFailure); - - ObjectNode response = objectMapper.createObjectNode(); - if ("ALL_NEW" .equals(returnValues) && result.newItem() != null) { - response.set("Attributes", result.newItem()); - } else if ("ALL_OLD" .equals(returnValues) && result.oldItem() != null) { - response.set("Attributes", result.oldItem()); - } else if ("UPDATED_NEW".equals(returnValues) || "UPDATED_OLD".equals(returnValues)) { - var updated = DynamoDbUpdatedAttributes.collect(result.touched(), "UPDATED_NEW".equals(returnValues)); - // AWS omits Attributes when no touched path has a value on that side. - if (!updated.isEmpty()) { - response.set("Attributes", updated); - } - } - addItemCollectionMetrics(response, request, tableName, key, region); - addWriteConsumedCapacity(response, request, tableName, region, result.oldItem(), result.newItem()); - return Response.ok(response).build(); - } - - private void evaluateLegacyExpected(JsonNode existing, JsonNode expected, String conditionalOperator, - String returnValuesOnConditionCheckFailure) { - if (expected == null) return; - validateLegacyExpected(expected); - boolean useOr = "OR".equals(conditionalOperator); - boolean overall = !useOr; - var fields = expected.fields(); - while (fields.hasNext()) { - var entry = fields.next(); - String attrName = entry.getKey(); - JsonNode condition = entry.getValue(); - JsonNode attrValue = existing != null ? existing.get(attrName) : null; - boolean condResult; - if (condition.has("Exists") && !condition.get("Exists").asBoolean()) { - condResult = attrValue == null; - } else { - // Exists:true always carries a Value, so it evaluates as an attribute - // comparison exactly like a bare Value: must exist AND match. - condResult = dynamoDbService.matchesKeyConditionPublic(attrValue, normalizeLegacyCondition(condition)); - } - if (useOr) overall = overall || condResult; - else overall = overall && condResult; - } - if (!overall) { - if ("ALL_OLD".equals(returnValuesOnConditionCheckFailure)) { - throw new ConditionalCheckFailedException(existing); - } else { - throw new ConditionalCheckFailedException(null); - } - } - } - - /** - * Validates every entry of a legacy Expected map before any condition is evaluated. - * The rules and their precedence mirror ExpectedAttributeValue: - *
    - *
  • {@code AttributeValueList} is only meaningful alongside a {@code ComparisonOperator}.
  • - *
  • {@code Exists} cannot be combined with a {@code ComparisonOperator} — they are - * alternative forms.
  • - *
  • Without a {@code ComparisonOperator}, a {@code Value} is required unless - * {@code Exists: false} asks for plain absence.
  • - *
  • {@code Exists: false} forbids a {@code Value} — an attribute cannot be expected to - * hold a value while also being expected to be absent.
  • - *
- * DynamoDB reports only the first offending entry, so validation stops at the first error. - */ - private void validateLegacyExpected(JsonNode expected) { - var fields = expected.fields(); - while (fields.hasNext()) { - var entry = fields.next(); - String attrName = entry.getKey(); - JsonNode condition = entry.getValue(); - boolean hasComparisonOperator = condition.has("ComparisonOperator"); - boolean hasExists = condition.has("Exists"); - boolean hasValue = condition.has("Value"); - - if (condition.has("AttributeValueList") && !hasComparisonOperator) { - throw legacyExpectedValidationError( - "AttributeValueList can only be used with a ComparisonOperator for Attribute: " + attrName); - } - if (hasExists && hasComparisonOperator) { - throw legacyExpectedValidationError( - "Exists and ComparisonOperator cannot be used together for Attribute: " + attrName); - } - boolean expectsValue = !hasExists || condition.get("Exists").asBoolean(); - if (!hasComparisonOperator && expectsValue && !hasValue) { - throw legacyExpectedValidationError("Value must be provided when Exists is " - + (hasExists ? "true" : "null") + " for Attribute: " + attrName); - } - if (!expectsValue && hasValue) { - throw legacyExpectedValidationError( - "Value cannot be used when Exists is false for Attribute: " + attrName); - } - } - } - - private AwsException legacyExpectedValidationError(String detail) { - return new AwsException("ValidationException", - "1 validation error detected: One or more parameter values were invalid: " + detail, 400); - } - - /** - * Converts a legacy Expected condition from the {"Value": {...}} form to the - * {"AttributeValueList": [{...}]} form expected by matchesKeyCondition. - * Operators that already use AttributeValueList (IN, BETWEEN) pass through unchanged. - */ - private JsonNode normalizeLegacyCondition(JsonNode condition) { - if (!condition.has("Value") || condition.has("AttributeValueList")) { - return condition; - } - com.fasterxml.jackson.databind.node.ObjectNode normalized = objectMapper.createObjectNode(); - condition.fields().forEachRemaining(e -> { - if (!"Value".equals(e.getKey())) { - normalized.set(e.getKey(), e.getValue()); - } - }); - com.fasterxml.jackson.databind.node.ArrayNode avl = objectMapper.createArrayNode(); - avl.add(condition.get("Value")); - normalized.set("AttributeValueList", avl); - return normalized; - } - - private void addItemCollectionMetrics(ObjectNode response, JsonNode request, String tableName, - JsonNode itemOrKey, String region) { - String ricm = request.has("ReturnItemCollectionMetrics") - ? request.get("ReturnItemCollectionMetrics").asText() : null; - if (!"SIZE".equals(ricm) || itemOrKey == null) return; - try { - TableDefinition table = dynamoDbService.requireTableForItemCall(tableName, region); - String pkName = table.getPartitionKeyName(); - JsonNode pkValue = itemOrKey.get(pkName); - if (pkValue == null) return; - ObjectNode metrics = objectMapper.createObjectNode(); - ObjectNode collKey = objectMapper.createObjectNode(); - collKey.set(pkName, pkValue); - metrics.set("ItemCollectionKey", collKey); - ArrayNode sizeRange = objectMapper.createArrayNode(); - sizeRange.add(0.0); - sizeRange.add(1.0); - metrics.set("SizeEstimateRangeGB", sizeRange); - response.set("ItemCollectionMetrics", metrics); - } catch (Exception ignored) {} - } - - private static final int MAX_TOTAL_SEGMENTS = 1_000_000; - - // The AttributeValues inside a legacy container. AttributeUpdates, Expected, - // KeyConditions and QueryFilter carry them under Value or AttributeValueList. - private ObjectNode legacyValues(JsonNode container) { - var values = objectMapper.createObjectNode(); - if (container == null || !container.isObject()) { - return values; - } - var i = 0; - for (var spec : container) { - if (spec.has("Value")) { - values.set("v" + i++, spec.get("Value")); - } - for (var value : spec.path("AttributeValueList")) { - values.set("v" + i++, value); - } - } - return values; - } - - private static final Set VALID_SELECT = Set.of( - "ALL_ATTRIBUTES", "ALL_PROJECTED_ATTRIBUTES", "SPECIFIC_ATTRIBUTES", "COUNT"); - - private static final String SELECT_NEEDS_PROJECTION = - "Must specify the AttributesToGet or ProjectionExpression when choosing to get SPECIFIC_ATTRIBUTES"; - - private Response handleQuery(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - DynamoDbTableNames.resolve(tableName); // validate tableName first - JsonNode keyConditions = request.has("KeyConditions") ? request.get("KeyConditions") : null; - JsonNode exprAttrValues = request.has("ExpressionAttributeValues") - ? request.get("ExpressionAttributeValues") : null; - JsonNode exprAttrNames = request.has("ExpressionAttributeNames") - ? request.get("ExpressionAttributeNames") : null; - String keyConditionExpr = request.has("KeyConditionExpression") - ? request.get("KeyConditionExpression").asText() : null; - String filterExpr = request.has("FilterExpression") - ? request.get("FilterExpression").asText() : null; - JsonNode queryFilter = request.has("QueryFilter") ? request.get("QueryFilter") : null; - JsonNode attributesToGet = request.has("AttributesToGet") ? request.get("AttributesToGet") : null; - Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; - Boolean scanIndexForward = request.has("ScanIndexForward") - ? request.get("ScanIndexForward").asBoolean() : null; - String indexName = request.has("IndexName") ? request.get("IndexName").asText() : null; - JsonNode exclusiveStartKey = request.has("ExclusiveStartKey") - ? request.get("ExclusiveStartKey") : null; - String select = request.has("Select") ? request.get("Select").asText() : null; - String projectionExpression = request.has("ProjectionExpression") - ? request.get("ProjectionExpression").asText() : null; - - // Validate Limit - if (limit != null && limit < 1) { - throw new AwsException("ValidationException", - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " - + "Member must have value greater than or equal to 1", 400); - } - - // Validate ReturnConsumedCapacity before Select - String rccQuery = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; - if (rccQuery != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccQuery)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + rccQuery + "' at 'returnConsumedCapacity' failed to satisfy constraint: " - + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); - } - - if (keyConditionExpr != null && keyConditions != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {KeyConditions} Expression parameters: {KeyConditionExpression}", 400); - } - if (keyConditionExpr != null && queryFilter != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {QueryFilter} Expression parameters: {KeyConditionExpression}", 400); - } - if (filterExpr != null && queryFilter != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {QueryFilter} Expression parameters: {FilterExpression}", 400); - } - if (attributesToGet != null && projectionExpression != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); - } - - if (keyConditionExpr == null && keyConditions == null) { - throw new AwsException("ValidationException", - "Either KeyConditions or KeyConditionExpression must be provided", 400); - } - - // Validate empty KCE - if (keyConditionExpr != null && keyConditionExpr.isEmpty()) { - throw new AwsException("ValidationException", - "Invalid KeyConditionExpression: The expression can not be empty;", 400); - } - - DynamoDbExpressionSize.checkRead(keyConditionExpr, "KeyConditionExpression"); - DynamoDbExpressionSize.checkRead(filterExpr, "FilterExpression"); - DynamoDbExpressionSize.checkRead(projectionExpression, "ProjectionExpression"); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, false); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(keyConditions), false); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(queryFilter), false); - ExpressionEvaluator.validateExpression(keyConditionExpr, "KeyConditionExpression", exprAttrNames, exprAttrValues); - ExpressionEvaluator.validateExpression(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues); - ProjectionEvaluator.validateExpression(projectionExpression, exprAttrNames); - - if (select != null && !VALID_SELECT.contains(select)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + select + "' at 'select' failed to satisfy constraint: " - + "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]", 400); - } - - boolean hasAttributesToGet = attributesToGet != null && attributesToGet.size() > 0; - if ("SPECIFIC_ATTRIBUTES".equals(select) && projectionExpression == null && !hasAttributesToGet) { - // Query prefixes the count here, Scan does not. - throw new AwsException("ValidationException", - "1 validation error detected: " + SELECT_NEEDS_PROJECTION, 400); - } - - TableDefinition queryTable = dynamoDbService.requireTableForItemCall(tableName, region); - DynamoDbAccessPath queryAccessPath = DynamoDbAccessPath.resolve(queryTable, indexName); - DynamoDbAccessPathValidator.validateQuery(queryTable, queryAccessPath, keyConditions, - keyConditionExpr, filterExpr, queryFilter, exprAttrNames, exprAttrValues); - DynamoDbAccessPathValidator.validateSelection(queryTable, queryAccessPath, select, - projectionExpression, attributesToGet, exprAttrNames); - rejectConsistentReadOnGsi(request, queryAccessPath); - - // Check undefined #tokens in FilterExpression - if (filterExpr != null) { - for (String token : extractHashTokens(filterExpr)) { - if (exprAttrNames == null || !exprAttrNames.has(token)) { - throw new AwsException("ValidationException", - "Invalid FilterExpression: An expression attribute name used in the document path is not defined; attribute name: " + token, 400); - } - } - } - // Reject ExpressionAttributeNames/Values entries not referenced by any expression - // (AWS parity, #2893). Unconditional: a legacy KeyConditions request that still - // carries EAN/EAV must be rejected, and either map can only be referenced from - // KeyConditionExpression, FilterExpression or (names only) ProjectionExpression. - Set hashTokens = extractHashTokens(keyConditionExpr, filterExpr, projectionExpression); - checkUnusedEan(exprAttrNames, hashTokens); - checkUnusedEav(exprAttrValues, extractColonTokens(keyConditionExpr, filterExpr)); - if (exclusiveStartKey != null) { - DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, queryTable, queryAccessPath, false); - } - - DynamoDbService.QueryResult result = dynamoDbService.query(tableName, keyConditions, - exprAttrValues, keyConditionExpr, filterExpr, limit, scanIndexForward, indexName, - exclusiveStartKey, exprAttrNames, region); - - List queryItems = result.items(); - // Apply QueryFilter (legacy API) - if (queryFilter != null) { - final JsonNode qf = queryFilter; - queryItems = queryItems.stream() - .filter(i -> dynamoDbService.matchesScanFilterPublic(i, qf)) - .toList(); - } - // Apply index projection (KEYS_ONLY / INCLUDE) when querying a secondary index - if (indexName != null && projectionExpression == null && attributesToGet == null) { - queryItems = applyIndexProjection(queryItems, queryTable, queryAccessPath, select); - } - if (projectionExpression != null) { - queryItems = queryItems.stream() - .map(i -> (JsonNode) ProjectionEvaluator.project(i, projectionExpression, exprAttrNames)) - .toList(); - } else if (attributesToGet != null) { - Set keep = new HashSet<>(); - attributesToGet.forEach(n -> keep.add(n.asText())); - queryItems = queryItems.stream() - .map(i -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) i, keep)) - .toList(); - } - - ObjectNode response = objectMapper.createObjectNode(); - if ("COUNT".equals(select)) { - response.put("Count", result.items().size()); - response.put("ScannedCount", result.scannedCount()); - } else { - ArrayNode itemsArray = objectMapper.createArrayNode(); - queryItems.forEach(itemsArray::add); - response.set("Items", itemsArray); - response.put("Count", queryItems.size()); - response.put("ScannedCount", result.scannedCount()); - } - if (result.lastEvaluatedKey() != null) { - response.set("LastEvaluatedKey", result.lastEvaluatedKey()); - } - addConsumedCapacity(response, request, tableName, - readCapacityUnits(result.scannedBytes(), request.path("ConsistentRead").asBoolean(false)), queryAccessPath); - return Response.ok(response).build(); - } - - private static void rejectConsistentReadOnGsi(JsonNode request, DynamoDbAccessPath accessPath) { - if (request.path("ConsistentRead").asBoolean(false) && accessPath.isGlobalSecondaryIndex()) { - throw new AwsException("ValidationException", - "Consistent reads are not supported on global secondary indexes", 400); - } - } - - private Response handleScan(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - String filterExpr = request.has("FilterExpression") - ? request.get("FilterExpression").asText() : null; - JsonNode exprAttrNames = request.has("ExpressionAttributeNames") - ? request.get("ExpressionAttributeNames") : null; - JsonNode exprAttrValues = request.has("ExpressionAttributeValues") - ? request.get("ExpressionAttributeValues") : null; - JsonNode scanFilter = request.has("ScanFilter") - ? request.get("ScanFilter") : null; - Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; - JsonNode exclusiveStartKey = request.has("ExclusiveStartKey") - ? request.get("ExclusiveStartKey") : null; - String select = request.has("Select") ? request.get("Select").asText() : null; - String indexNameScan = request.has("IndexName") ? request.get("IndexName").asText() : null; - String projectionExpressionScan = request.has("ProjectionExpression") - ? request.get("ProjectionExpression").asText() : null; - JsonNode attributesToGetScan = request.has("AttributesToGet") ? request.get("AttributesToGet") : null; - Integer segment = request.has("Segment") ? request.get("Segment").asInt() : null; - Integer totalSegments = request.has("TotalSegments") ? request.get("TotalSegments").asInt() : null; - - if (filterExpr != null && scanFilter != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}", 400); - } - - if (limit != null && limit < 1) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + limit + "' at 'limit' failed to satisfy constraint: " - + "Member must have value greater than or equal to 1", 400); - } - - var segmentErrors = new ArrayList(); - if (totalSegments != null) { - if (totalSegments < 1) { - segmentErrors.add("Value '" + totalSegments + "' at 'totalSegments' failed to satisfy constraint: " - + "Member must have value greater than or equal to 1"); - } - if (MAX_TOTAL_SEGMENTS < totalSegments) { - segmentErrors.add("Value '" + totalSegments + "' at 'totalSegments' failed to satisfy constraint: " - + "Member must have value less than or equal to " + MAX_TOTAL_SEGMENTS); - } - } - if (segment != null && segment < 0) { - segmentErrors.add("Value '" + segment + "' at 'segment' failed to satisfy constraint: " - + "Member must have value greater than or equal to 0"); - } - if (!segmentErrors.isEmpty()) { - var n = segmentErrors.size(); - throw new AwsException("ValidationException", - n + " validation error" + (n > 1 ? "s" : "") + " detected: " - + String.join("; ", segmentErrors), 400); - } - - if (segment != null && totalSegments == null) { - throw new AwsException("ValidationException", - "The TotalSegments parameter is required but was not present in the request when Segment parameter is present", 400); - } - if (totalSegments != null && segment == null) { - throw new AwsException("ValidationException", - "The Segment parameter is required but was not present in the request when parameter TotalSegments is present", 400); - } - if (segment != null && totalSegments != null && segment >= totalSegments) { - throw new AwsException("ValidationException", - "The Segment parameter is zero-based and must be less than parameter TotalSegments: " - + "Segment: " + segment + " is not less than TotalSegments: " + totalSegments, 400); - } - - DynamoDbExpressionSize.checkReadWithSize(filterExpr, "FilterExpression"); - DynamoDbExpressionSize.checkRead(projectionExpressionScan, "ProjectionExpression"); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, false); - ExpressionEvaluator.validateExpression(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues); - ProjectionEvaluator.validateExpression(projectionExpressionScan, exprAttrNames); - - // Reject ExpressionAttributeNames/Values entries not referenced by any expression (AWS parity, #2893) - checkUnusedEan(exprAttrNames, extractHashTokens(filterExpr, projectionExpressionScan)); - checkUnusedEav(exprAttrValues, extractColonTokens(filterExpr)); - - if (select != null && !VALID_SELECT.contains(select)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + select + "' at 'select' failed to satisfy constraint: " - + "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]", 400); - } - if (projectionExpressionScan != null && attributesToGetScan != null) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); - } - boolean hasAttributesToGetScan = attributesToGetScan != null && attributesToGetScan.size() > 0; - if ("SPECIFIC_ATTRIBUTES".equals(select) - && projectionExpressionScan == null && !hasAttributesToGetScan) { - throw new AwsException("ValidationException", SELECT_NEEDS_PROJECTION, 400); - } - - TableDefinition scanTable = dynamoDbService.requireTableForItemCall(tableName, region); - DynamoDbAccessPath scanAccessPath = DynamoDbAccessPath.resolve(scanTable, indexNameScan); - DynamoDbAccessPathValidator.validateSelection(scanTable, scanAccessPath, select, - projectionExpressionScan, attributesToGetScan, exprAttrNames); - rejectConsistentReadOnGsi(request, scanAccessPath); - - if (exclusiveStartKey != null) { - DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, scanTable, scanAccessPath, true); - } - - DynamoDbService.ScanResult result = dynamoDbService.scan( - tableName, filterExpr, exprAttrNames, exprAttrValues, scanFilter, limit, - exclusiveStartKey, indexNameScan, segment, totalSegments, region); - - List scanItems = result.items(); - // Apply index projection (KEYS_ONLY / INCLUDE) when scanning a secondary index - if (indexNameScan != null && projectionExpressionScan == null && attributesToGetScan == null) { - scanItems = applyIndexProjection(scanItems, scanTable, scanAccessPath, select); - } - if (projectionExpressionScan != null) { - scanItems = scanItems.stream() - .map(i -> (JsonNode) ProjectionEvaluator.project(i, projectionExpressionScan, exprAttrNames)) - .toList(); - } else if (attributesToGetScan != null) { - Set keep = new HashSet<>(); - attributesToGetScan.forEach(n -> keep.add(n.asText())); - scanItems = scanItems.stream() - .map(i -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) i, keep)) - .toList(); - } - - ObjectNode response = objectMapper.createObjectNode(); - if ("COUNT".equals(select)) { - response.put("Count", result.items().size()); - response.put("ScannedCount", result.scannedCount()); - } else { - ArrayNode itemsArray = objectMapper.createArrayNode(); - scanItems.forEach(itemsArray::add); - response.set("Items", itemsArray); - response.put("Count", scanItems.size()); - response.put("ScannedCount", result.scannedCount()); - } - if (result.lastEvaluatedKey() != null) { - response.set("LastEvaluatedKey", result.lastEvaluatedKey()); - } - addConsumedCapacity(response, request, tableName, - readCapacityUnits(result.scannedBytes(), request.path("ConsistentRead").asBoolean(false)), scanAccessPath); - return Response.ok(response).build(); - } - - // The floor AWS reports for a small search. The real figure is non-deterministic there, - // so every search reports the floor (measured in eu-west-2, 2026-09-23). - private static final double VECTOR_SEARCH_REQUEST_BYTES = 1024; - - private static final int MAX_VECTOR_SEARCH_TOP_K = 100; - - private Response handleSearchVectors(JsonNode request, String region) { - requireSearchVectorsMember(request, "SearchVector"); - requireSearchVectorsMember(request, "IndexName"); - String tableName = request.path("TableName").asText(); - String indexName = request.get("IndexName").asText(); - String rccSearch = request.has("ReturnConsumedCapacity") - ? request.get("ReturnConsumedCapacity").asText() : null; - if (rccSearch != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccSearch)) { - // No "N validation errors detected" envelope here, unlike every other operation. - throw new AwsException("ValidationException", - "Value '" + rccSearch + "' at 'returnConsumedCapacity' " - + "failed to satisfy constraint: Member must satisfy enum value set: " - + "[INDEXES, TOTAL, NONE]", 400); - } - requireSearchVectorsMember(request, "TopK"); - int topK = request.get("TopK").asInt(); - if (topK < 1) { - // AWS names this member TopK and quotes no value, unlike every other member of this - // family. Measured on real DynamoDB, eu-west-2, 2026-09-23. - throw new AwsException("ValidationException", - "1 validation error detected: Value at 'TopK' failed to satisfy " - + "constraint: Member must have value greater than or equal to 1", 400); - } - // Both bounds answer before the table and the index are resolved: AWS reports the range - // even for a table that does not exist. - if (topK > MAX_VECTOR_SEARCH_TOP_K) { - throw new AwsException("ValidationException", - "Provided TopK value '" + topK + "' is out of valid range. " - + "The value must be between 1 and " + MAX_VECTOR_SEARCH_TOP_K + " inclusive", 400); - } - - TableDefinition table = dynamoDbService.settledTable(tableName, region); - VectorIndex index = requireSearchableVectorIndex(table, indexName); - - JsonNode exprAttrNames = request.has("ExpressionAttributeNames") - ? request.get("ExpressionAttributeNames") : null; - JsonNode exprAttrValues = request.has("ExpressionAttributeValues") - ? request.get("ExpressionAttributeValues") : null; - List hits = DynamoDbVectorSearch.search(table, index, - dynamoDbService.liveItems(table, region), - request.path("SearchVector"), topK, - request.has("SearchConditionExpression") - ? request.get("SearchConditionExpression").asText() : null, - exprAttrNames, exprAttrValues, - request.has("ProjectionExpression") ? request.get("ProjectionExpression").asText() : null); - - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode searchResults = objectMapper.createArrayNode(); - for (DynamoDbVectorSearch.Hit hit : hits) { - ObjectNode searchResult = objectMapper.createObjectNode(); - searchResult.set("Item", hit.item()); - searchResult.put("Score", hit.score()); - searchResults.add(searchResult); - } - response.set("SearchResults", searchResults); - if (rccSearch != null && !"NONE".equals(rccSearch)) { - ObjectNode consumedCapacity = objectMapper.createObjectNode(); - consumedCapacity.put("VectorSearchRequestBytes", VECTOR_SEARCH_REQUEST_BYTES); - response.set("ConsumedCapacity", consumedCapacity); - } - return Response.ok(response).build(); - } - - /** - * Rejects an omitted required member of SearchVectors the way the AWS frontend does: as a - * deserialisation failure quoting the offset of the body's closing brace, which for the - * compact JSON an SDK sends is the body length. Measured in eu-west-2, 2026-09-23. - */ - private static void requireSearchVectorsMember(JsonNode request, String member) { - if (!request.hasNonNull(member)) { - throw new AwsException("ValidationException", - "missing field `" + member + "` at line 1 column " - + request.toString().length(), 400); - } - } - - /** - * The vector index a search may run against. - * - *

An index still in its resource allocation phase answers as if the table did not have it, - * which is the wording AWS uses there and what the documented readiness wait retries on. - */ - private VectorIndex requireSearchableVectorIndex(TableDefinition table, String indexName) { - VectorIndex index = table.findVectorIndex(indexName).orElse(null); - if (index == null) { - throw new AwsException("ValidationException", - "The table does not have the specified index: " + indexName, 400); - } - if ("CREATING".equals(index.getIndexStatus())) { - if (!dynamoDbService.isVectorIndexBackfilling(index)) { - throw new AwsException("ValidationException", - "The table does not have the specified index: " + indexName, 400); - } - throw new AwsException("ValidationException", - "Cannot search backfilling vector index: " + indexName, 400); - } - return index; - } - - private Response handleBatchWriteItem(JsonNode request, String region) { - JsonNode requestItems = request.get("RequestItems"); - if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode() - || !requestItems.fields().hasNext()) { - throw new AwsException("ValidationException", - "The requestItems parameter is required for BatchWriteItem", 400); - } - Map> items = new HashMap<>(); - Iterator> tables = requestItems.fields(); - while (tables.hasNext()) { - var entry = tables.next(); - List writes = new ArrayList<>(); - for (JsonNode writeReq : entry.getValue()) { - DynamoDbAttributeValueValidator.requireNestingWithinLimit( - writeReq.path("PutRequest").get("Item"), false); - writes.add(writeReq); - } - items.put(entry.getKey(), writes); - } - - // Per-table check: max 25 write requests - for (Map.Entry> entry : items.entrySet()) { - if (entry.getValue().size() > 25) { - // Build a representation of the requestItems - StringBuilder sb = new StringBuilder("{"); - sb.append(entry.getKey()).append("=["); - List reprs = new ArrayList<>(); - for (JsonNode w : entry.getValue()) { - reprs.add(w.toString()); - } - sb.append(String.join(", ", reprs)).append("]}"); - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + sb + "' at 'requestItems' failed to satisfy constraint: " - + "Map value must satisfy constraint: [Member must have length less than or equal to 25, " - + "Member must have length greater than or equal to 1]", 400); - } - } - - for (Map.Entry> entry : items.entrySet()) { - TableDefinition bwTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); - Set seen = new HashSet<>(); - for (JsonNode writeReq : entry.getValue()) { - JsonNode keyNode = writeReq.has("PutRequest") - ? writeReq.get("PutRequest").get("Item") - : writeReq.get("DeleteRequest").get("Key"); - String key = dynamoDbService.buildItemKey(bwTable, keyNode, - DynamoDbService.KeySurface.BATCH_WRITE); - if (!seen.add(key)) { - throw new AwsException("ValidationException", - "Provided list of item keys contains duplicates", 400); - } - } - } - - // The per-table write cost needs the stored images from before the batch runs. - var returnCCBatch = request.path("ReturnConsumedCapacity").asText("NONE"); - if (!VALID_RETURN_CONSUMED_CAPACITY.contains(returnCCBatch)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + returnCCBatch - + "' at 'returnConsumedCapacity' failed to satisfy constraint: " - + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); - } - Map costs = null; - if (!"NONE".equals(returnCCBatch)) { - costs = new LinkedHashMap<>(); - for (var entry : items.entrySet()) { - TableDefinition costTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); - var cost = DynamoDbWriteCapacity.Cost.zero(); - for (var writeReq : entry.getValue()) { - var newItem = writeReq.has("PutRequest") - ? DynamoDbNumberUtils.normalizeNumbersInItem(writeReq.get("PutRequest").get("Item")) - : null; - var keyNode = writeReq.has("PutRequest") - ? writeReq.get("PutRequest").get("Item") - : writeReq.get("DeleteRequest").get("Key"); - var previous = dynamoDbService.getItem(entry.getKey(), keyNode, region); - cost = cost.plus(DynamoDbWriteCapacity.forWrite(costTable, previous, newItem)); - } - costs.put(entry.getKey(), cost); - } - } - - dynamoDbService.batchWriteItem(items, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.set("UnprocessedItems", objectMapper.createObjectNode()); - if (costs != null) { - var ccArray = objectMapper.createArrayNode(); - for (var entry : costs.entrySet()) { - ccArray.add(writeCapacityNode(entry.getKey(), entry.getValue(), - "INDEXES".equals(returnCCBatch))); - } - response.set("ConsumedCapacity", ccArray); - } - return Response.ok(response).build(); - } - - private Response handleBatchGetItem(JsonNode request, String region) { - JsonNode requestItems = request.get("RequestItems"); - if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()) { - throw new AwsException("ValidationException", - "The requestItems parameter is required for BatchGetItem", 400); - } - // BatchGetItem answers an empty map from the validation framework, BatchWriteItem - // still answers with its own sentence. - if (!requestItems.fields().hasNext()) { - throw new AwsException("ValidationException", - "1 validation error detected: Value at 'RequestItems' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1", 400); - } - Map items = new HashMap<>(); - Iterator> tables = requestItems.fields(); - while (tables.hasNext()) { - var entry = tables.next(); - items.put(entry.getKey(), entry.getValue()); - } - - // AWS weighs the two projection styles across the whole request, so one table - // entry naming AttributesToGet and another naming ProjectionExpression conflict. - boolean usesAttributesToGet = false; - boolean usesProjectionExpression = false; - for (JsonNode tableRequest : items.values()) { - usesAttributesToGet |= tableRequest.hasNonNull("AttributesToGet"); - usesProjectionExpression |= tableRequest.hasNonNull("ProjectionExpression"); - } - if (usesAttributesToGet && usesProjectionExpression) { - throw new AwsException("ValidationException", - "Can not use both expression and non-expression parameters in the same request: " - + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); - } - - // Per-table check: max 100 keys - for (Map.Entry entry : items.entrySet()) { - var projection = entry.getValue().path("ProjectionExpression"); - if (projection.isTextual()) { - DynamoDbExpressionSize.checkRead(projection.asText(), "ProjectionExpression"); - ProjectionEvaluator.validateExpression(projection.asText(), - entry.getValue().get("ExpressionAttributeNames")); - } - JsonNode keysNode = entry.getValue().has("Keys") ? entry.getValue().get("Keys") : null; - if (keysNode != null && keysNode.size() > 100) { - throw new AwsException("ValidationException", - "1 validation error detected: Value at 'RequestItems." + entry.getKey() - + ".member.Keys' failed to satisfy constraint: " - + "Member must have length less than or equal to 100", 400); - } - } - - for (Map.Entry entry : items.entrySet()) { - TableDefinition bgTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); - JsonNode keys = entry.getValue().get("Keys"); - if (keys == null || !keys.isArray()) continue; - Set seen = new HashSet<>(); - for (JsonNode key : keys) { - String itemKey = dynamoDbService.buildItemKey(bgTable, key); - if (!seen.add(itemKey)) { - throw new AwsException("ValidationException", - "Provided list of item keys contains duplicates", 400); - } - } - } - - DynamoDbService.BatchGetResult result = dynamoDbService.batchGetItem(items, region); - - ObjectNode response = objectMapper.createObjectNode(); - ObjectNode responses = objectMapper.createObjectNode(); - for (Map.Entry> entry : result.responses().entrySet()) { - String tblName = entry.getKey(); - JsonNode tableRequest = requestItems.get(tblName); - String projExpr = tableRequest != null && tableRequest.has("ProjectionExpression") - ? tableRequest.get("ProjectionExpression").asText() : null; - JsonNode exprNames = tableRequest != null && tableRequest.has("ExpressionAttributeNames") - ? tableRequest.get("ExpressionAttributeNames") : null; - JsonNode attrToGet = tableRequest != null && tableRequest.has("AttributesToGet") - ? tableRequest.get("AttributesToGet") : null; - ArrayNode tableItems = objectMapper.createArrayNode(); - for (JsonNode item : entry.getValue()) { - JsonNode projected; - if (projExpr != null) { - projected = ProjectionEvaluator.project(item, projExpr, exprNames); - } else if (attrToGet != null) { - Set keep = new HashSet<>(); - attrToGet.forEach(n -> keep.add(n.asText())); - projected = ProjectionEvaluator.trimToAttributes((ObjectNode) item, keep); - } else { - projected = item; - } - tableItems.add(projected); - } - responses.set(tblName, tableItems); - } - response.set("Responses", responses); - response.set("UnprocessedKeys", objectMapper.createObjectNode()); - addBatchConsumedCapacity(response, request, items, false); - return Response.ok(response).build(); - } - - private Response handleUpdateTable(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - JsonNode replicaUpdates = request.path("ReplicaUpdates"); - List addRegions = new ArrayList<>(); - List removeRegions = new ArrayList<>(); - List updateRegions = new ArrayList<>(); - if (replicaUpdates.isArray()) { - for (JsonNode update : replicaUpdates) { - JsonNode create = update.path("Create"); - if (create.isObject()) { - String replicaRegion = create.path("RegionName").asText(null); - validateReplicaRegion(replicaRegion); - addRegions.add(replicaRegion); - } - JsonNode delete = update.path("Delete"); - if (delete.isObject()) { - String replicaRegion = delete.path("RegionName").asText(null); - validateReplicaRegion(replicaRegion); - removeRegions.add(replicaRegion); - } - JsonNode updateNode = update.path("Update"); - if (updateNode.isObject()) { - String replicaRegion = updateNode.path("RegionName").asText(null); - validateReplicaRegion(replicaRegion); - updateRegions.add(replicaRegion); - } - } - } - JsonNode pt = request.path("ProvisionedThroughput"); - Throughput throughput = null; - if (!pt.isMissingNode()) { - throughput = parseThroughput(pt); - } - - String billingModeCheck = request.has("BillingMode") ? request.get("BillingMode").asText() : null; - if ("PAY_PER_REQUEST".equals(billingModeCheck) && !pt.isMissingNode()) { - throw new AwsException("ValidationException", - "ProvisionedThroughput cannot be specified when BillingMode is PAY_PER_REQUEST", 400); - } - - List gsiCreates = new ArrayList<>(); - List gsiDeletes = new ArrayList<>(); - List gsiThroughputUpdates = new ArrayList<>(); - JsonNode gsiUpdates = request.path("GlobalSecondaryIndexUpdates"); - if (!gsiUpdates.isMissingNode() && gsiUpdates.isArray()) { - var updatePosition = 0; - for (JsonNode update : gsiUpdates) { - updatePosition++; - JsonNode createNode = update.path("Create"); - if (!createNode.isMissingNode()) { - String indexName = createNode.path("IndexName").asText(); - List gsiKeySchema = new ArrayList<>(); - createNode.path("KeySchema").forEach(ks -> - gsiKeySchema.add(new KeySchemaElement( - ks.path("AttributeName").asText(), - ks.path("KeyType").asText()))); - String projectionType = createNode.path("Projection").path("ProjectionType").asText("ALL"); - JsonNode nonKeyAttrArray = createNode.path("Projection").path("NonKeyAttributes"); - List nonKeyAttributes = new ArrayList<>(); - if (!nonKeyAttrArray.isMissingNode() && nonKeyAttrArray.isArray()){ - for (JsonNode nonKeyAttr : nonKeyAttrArray){ - nonKeyAttributes.add(nonKeyAttr.asText()); - } - } - rejectEmptyNonKeyAttributes(nonKeyAttrArray, - "globalSecondaryIndexUpdates." + updatePosition + ".member.create"); - validateProjectionSpec(projectionType, nonKeyAttributes); - GlobalSecondaryIndex newGsi = new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes); - JsonNode newGsiPt = createNode.path("ProvisionedThroughput"); - if (!newGsiPt.isMissingNode()) { - newGsi.getProvisionedThroughput().setReadCapacityUnits(newGsiPt.path("ReadCapacityUnits").asLong(0)); - newGsi.getProvisionedThroughput().setWriteCapacityUnits(newGsiPt.path("WriteCapacityUnits").asLong(0)); - } - JsonNode newGsiOnDemand = createNode.path("OnDemandThroughput"); - if (newGsiOnDemand.isObject()) { - if (newGsiOnDemand.has("MaxReadRequestUnits")) { - newGsi.setOnDemandMaxReadRequestUnits(newGsiOnDemand.get("MaxReadRequestUnits").asInt()); - } - if (newGsiOnDemand.has("MaxWriteRequestUnits")) { - newGsi.setOnDemandMaxWriteRequestUnits(newGsiOnDemand.get("MaxWriteRequestUnits").asInt()); - } - } - gsiCreates.add(newGsi); - } - JsonNode deleteNode = update.path("Delete"); - if (!deleteNode.isMissingNode()) { - gsiDeletes.add(deleteNode.path("IndexName").asText()); - } - JsonNode updateNode = update.path("Update"); - if (updateNode.isObject()) { - JsonNode gsiPt = updateNode.path("ProvisionedThroughput"); - gsiThroughputUpdates.add(new GsiThroughputUpdate( - updateNode.path("IndexName").asText(), - gsiPt.isObject() ? parseThroughput(gsiPt) : null, - parseOnDemandThroughput(updateNode.path("OnDemandThroughput")))); - } - } - } - - if (!gsiThroughputUpdates.isEmpty()) { - TableDefinition currentTable = dynamoDbService.describeTable(tableName, region); - for (GsiThroughputUpdate gsiUpdate : gsiThroughputUpdates) { - String indexName = gsiUpdate.indexName(); - if (gsiDeletes.contains(indexName)) { - throw new AwsException("ValidationException", - "Cannot delete and update the same index: " + indexName, 400); - } - if (currentTable.findGsi(indexName).isEmpty()) { - throw new AwsException("ValidationException", - "The table does not have the specified index: " + indexName, 400); - } - } - } - - List vectorCreates = new ArrayList<>(); - List vectorDeletes = new ArrayList<>(); - JsonNode vectorIndexUpdates = request.path("VectorIndexUpdates"); - if (vectorIndexUpdates.isArray()) { - // AWS reports a per-member constraint under the position in this array, which a - // create shares with the deletes beside it. - int updatePosition = 0; - for (JsonNode update : vectorIndexUpdates) { - updatePosition++; - JsonNode createNode = update.path("Create"); - if (createNode.isObject()) { - String memberPath = "vectorIndexUpdates." + updatePosition + ".member.create"; - vectorCreates.add(new DynamoDbService.VectorIndexCreate( - parseVectorIndex(createNode, memberPath), memberPath)); - } - JsonNode deleteNode = update.path("Delete"); - if (deleteNode.isObject()) { - vectorDeletes.add(deleteNode.path("IndexName").asText(null)); - } - } - } - - List newAttrDefs = new ArrayList<>(); - JsonNode attrDefsNode = request.path("AttributeDefinitions"); - if (!attrDefsNode.isMissingNode() && attrDefsNode.isArray()) { - for (JsonNode ad : attrDefsNode) { - newAttrDefs.add(new AttributeDefinition( - ad.path("AttributeName").asText(), - ad.path("AttributeType").asText())); - } - } - - TableDefinition table = tableService.updateTable(new UpdateTableRequest(tableName, - throughput, newAttrDefs, gsiCreates, gsiDeletes, gsiThroughputUpdates, vectorCreates, vectorDeletes, - addRegions, removeRegions, updateRegions, parseTableSettings(request)), region); - - ObjectNode response = objectMapper.createObjectNode(); - response.set("TableDescription", tableToNode(table)); - return Response.ok(response).build(); - } - - private static Throughput parseThroughput(JsonNode pt) { - Long readCapacity = pt.has("ReadCapacityUnits") ? pt.get("ReadCapacityUnits").asLong() : null; - Long writeCapacity = pt.has("WriteCapacityUnits") ? pt.get("WriteCapacityUnits").asLong() : null; - return new Throughput(readCapacity, writeCapacity); - } - - private static void validateReplicaRegion(String replicaRegion) { - if (replicaRegion == null || replicaRegion.isBlank()) { - throw new AwsException("ValidationException", "Replica RegionName must not be empty", 400); - } - } - - private Response handleDescribeTimeToLive(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - TableDefinition table = dynamoDbService.describeTable(tableName, region); - - ObjectNode response = objectMapper.createObjectNode(); - ObjectNode ttlDesc = objectMapper.createObjectNode(); - if (table.isTtlEnabled() && table.getTtlAttributeName() != null) { - ttlDesc.put("TimeToLiveStatus", "ENABLED"); - ttlDesc.put("AttributeName", table.getTtlAttributeName()); - } else { - ttlDesc.put("TimeToLiveStatus", "DISABLED"); - } - response.set("TimeToLiveDescription", ttlDesc); - return Response.ok(response).build(); - } - - private Response handleUpdateTimeToLive(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - JsonNode spec = request.path("TimeToLiveSpecification"); - String ttlAttributeName = spec.path("AttributeName").asText(); - if (ttlAttributeName == null || ttlAttributeName.isBlank()) { - throw new AwsException("ValidationException", - "TimeToLiveSpecification.AttributeName must not be empty", 400); - } - boolean enabled = spec.path("Enabled").asBoolean(false); - - dynamoDbService.updateTimeToLive(tableName, ttlAttributeName, enabled, region); - - ObjectNode response = objectMapper.createObjectNode(); - ObjectNode ttlSpec = objectMapper.createObjectNode(); - ttlSpec.put("AttributeName", ttlAttributeName); - ttlSpec.put("Enabled", enabled); - response.set("TimeToLiveSpecification", ttlSpec); - return Response.ok(response).build(); - } - - private Response handleDescribeContinuousBackups(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - TableDefinition table = dynamoDbService.describeTable(tableName, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(table)); - return Response.ok(response).build(); - } - - private Response handleUpdateContinuousBackups(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - JsonNode spec = request.path("PointInTimeRecoverySpecification"); - boolean enabled = spec.path("PointInTimeRecoveryEnabled").asBoolean(false); - Integer recoveryPeriodInDays = spec.has("RecoveryPeriodInDays") - ? spec.path("RecoveryPeriodInDays").asInt() - : null; - if (recoveryPeriodInDays != null && (recoveryPeriodInDays < 1 || recoveryPeriodInDays > 35)) { - throw new AwsException("ValidationException", - "RecoveryPeriodInDays must be between 1 and 35", 400); - } - - TableDefinition table = dynamoDbService.updateContinuousBackups( - tableName, enabled, recoveryPeriodInDays, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(table)); - return Response.ok(response).build(); - } - - private Response handleTransactWriteItems(JsonNode request, String region) { - JsonNode transactItemsNode = requireValidTransactRequest(request); - - for (JsonNode txItem : transactItemsNode) { - for (JsonNode op : txItem) { - String conditionExpression = op.has("ConditionExpression") - ? op.get("ConditionExpression").asText() : null; - DynamoDbExpressionSize.checkRead(op.path("UpdateExpression").textValue(), "UpdateExpression"); - DynamoDbExpressionSize.checkReadWithSize(conditionExpression, "ConditionExpression"); - ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", - op.get("ExpressionAttributeNames"), - op.get("ExpressionAttributeValues")); - DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Item"), false); - dynamoDbService.requireAddOrDeleteOperandTypes(op.path("UpdateExpression").textValue(), - op.get("ExpressionAttributeValues"), false); - } - } - - // Check 4MB total item size limit - final int MAX_TRANSACTION_BYTES = 4 * 1024 * 1024; - int totalSize = 0; - for (JsonNode txItem : transactItemsNode) { - JsonNode item = txItem.has("Put") ? txItem.get("Put").get("Item") - : txItem.has("Update") ? txItem.get("Update").get("Key") - : txItem.has("Delete") ? txItem.get("Delete").get("Key") - : txItem.has("ConditionCheck") ? txItem.get("ConditionCheck").get("Key") - : null; - if (item != null) totalSize += DynamoDbItemSize.calculateItemSize(item); - } - if (totalSize > MAX_TRANSACTION_BYTES) { - throw new AwsException("ValidationException", - "Transaction failed: The total size of all items in the transaction request cannot exceed 4 MB", 400); - } - - List transactItems = new ArrayList<>(); - transactItemsNode.forEach(transactItems::add); - try { - dynamoDbService.cancelOnKeySchemaMismatch(transactItems, region); - } catch (TransactionCanceledException e) { - return transactWriteCanceled(e); - } - - Map tableCache = new HashMap<>(); - Set seen = new HashSet<>(); - for (JsonNode txItem : transactItemsNode) { - JsonNode op = txItem.has("Put") ? txItem.get("Put") - : txItem.has("Delete") ? txItem.get("Delete") - : txItem.has("Update") ? txItem.get("Update") - : txItem.has("ConditionCheck") ? txItem.get("ConditionCheck") : null; - if (op == null) continue; - String opTable = op.path("TableName").asText(); - TableDefinition txTable = tableCache.computeIfAbsent(opTable, - tn -> dynamoDbService.requireTableForItemCall(tn, region)); - JsonNode keyNode = op.has("Item") ? op.get("Item") : op.get("Key"); - if (keyNode == null) continue; - String key = region + "::" + opTable + "::" + dynamoDbService.buildItemKey(txTable, keyNode); - if (!seen.add(key)) { - throw new AwsException("ValidationException", - "Transaction request cannot include multiple operations on one item", 400); - } - } - - // ClientRequestToken makes TransactWriteItems idempotent within ~10 minutes. - // Forward the token and the raw request body so the service can hash the body - // and reject replays whose parameters changed. - String clientRequestToken = request.has("ClientRequestToken") && !request.get("ClientRequestToken").isNull() - ? request.get("ClientRequestToken").asText() - : null; - - try { - DynamoDbService.TransactWriteResult result = - dynamoDbService.transactWriteItems(transactItems, region, clientRequestToken, request); - ObjectNode response = objectMapper.createObjectNode(); - addTransactWriteConsumedCapacity(response, request, result); - return Response.ok(response).build(); - } catch (TransactionCanceledException e) { - return transactWriteCanceled(e); - } - } - - private static JsonNode requireValidTransactRequest(JsonNode request) { - JsonNode transactItems = request.path("TransactItems"); - List validationErrors = new ArrayList<>(); - if (transactItems.isMissingNode() || transactItems.isNull() || !transactItems.isArray()) { - validationErrors.add("Value null at 'transactItems' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1"); - } else if (transactItems.isEmpty()) { - validationErrors.add("Value '[]' at 'transactItems' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1"); - } else if (transactItems.size() > 100) { - validationErrors.add("Value '" + transactItems + "' at 'transactItems' failed to satisfy constraint: " - + "Member must have length less than or equal to 100"); - } - addReturnConsumedCapacityError(request, validationErrors); - throwValidationErrors(validationErrors); - return transactItems; - } - - private static void addReturnConsumedCapacityError(JsonNode request, List validationErrors) { - String returnCC = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; - if (returnCC != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(returnCC)) { - validationErrors.add("Value '" + returnCC + "' at 'returnConsumedCapacity' failed to satisfy constraint: " - + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"); - } - } - - private static void requireValidReturnConsumedCapacity(JsonNode request) { - List validationErrors = new ArrayList<>(); - addReturnConsumedCapacityError(request, validationErrors); - throwValidationErrors(validationErrors); - } - - private static void throwValidationErrors(List validationErrors) { - if (validationErrors.isEmpty()) { - return; - } - int n = validationErrors.size(); - throw new AwsException("ValidationException", - n + " validation error" + (n > 1 ? "s" : "") + " detected: " - + String.join("; ", validationErrors), 400); - } - - private Response transactWriteCanceled(TransactionCanceledException e) { - ObjectNode body = objectMapper.createObjectNode(); - body.put("__type", "TransactionCanceledException"); - body.put("message", e.getMessage()); - ArrayNode reasons = body.putArray("CancellationReasons"); - for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) { - ObjectNode r = objectMapper.createObjectNode(); - r.put("Code", reason.code().isEmpty() ? "None" : reason.code()); - if (!reason.code().isEmpty()) { - r.put("Message", reason.message() != null ? reason.message() : "The conditional request failed"); - } - if (reason.item() != null) { - r.set("Item", reason.item()); - } - reasons.add(r); - } - return Response.status(400).entity(body).build(); - } - - private Response handleTransactGetItems(JsonNode request, String region) { - JsonNode transactItemsNode = requireValidTransactRequest(request); - - for (JsonNode txItem : transactItemsNode) { - DynamoDbExpressionSize.checkRead(txItem.path("Get").path("ProjectionExpression").textValue(), - "ProjectionExpression"); - } - - Map tableCache = new HashMap<>(); - Set seenGet = new HashSet<>(); - for (JsonNode txItem : transactItemsNode) { - JsonNode get = txItem.has("Get") ? txItem.get("Get") : null; - if (get == null) continue; - String opTable = get.path("TableName").asText(); - TableDefinition txTable = tableCache.computeIfAbsent(opTable, - tn -> dynamoDbService.requireTableForItemCall(tn, region)); - JsonNode keyNode = get.get("Key"); - if (keyNode == null) continue; - try { - String key = region + "::" + opTable + "::" + dynamoDbService.buildItemKey(txTable, keyNode); - if (!seenGet.add(key)) { - throw new AwsException("ValidationException", - "Transaction request cannot include multiple operations on one item", 400); - } - } catch (AwsException e) { - if ("Transaction request cannot include multiple operations on one item".equals(e.getMessage())) { - throw e; - } - // Per-action validation error - will be surfaced via TransactionCanceledException in transactGetItems - } - } - - // Validate the ProjectionExpression in each Get action before executing - for (JsonNode txItem : transactItemsNode) { - JsonNode get = txItem.has("Get") ? txItem.get("Get") : null; - if (get == null) continue; - String pe = get.has("ProjectionExpression") ? get.get("ProjectionExpression").asText() : null; - if (pe != null) { - ProjectionEvaluator.validateExpression(pe, get.get("ExpressionAttributeNames")); - } - } - - List transactItems = new ArrayList<>(); - transactItemsNode.forEach(transactItems::add); - - DynamoDbService.TransactGetResult result; - try { - result = dynamoDbService.transactGetItems(transactItems, region); - } catch (TransactionCanceledException e) { - ObjectNode body = objectMapper.createObjectNode(); - body.put("__type", "TransactionCanceledException"); - body.put("message", e.getMessage()); - ArrayNode reasons = body.putArray("CancellationReasons"); - for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) { - ObjectNode r = objectMapper.createObjectNode(); - r.put("Code", reason.code().isEmpty() ? "None" : reason.code()); - if (!reason.code().isEmpty()) { - r.put("Message", ""); - } - if (reason.item() != null) { - r.set("Item", reason.item()); - } - reasons.add(r); - } - return Response.status(400).entity(body).build(); - } - - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode responsesArray = objectMapper.createArrayNode(); - for (JsonNode item : result.items()) { - ObjectNode entry = objectMapper.createObjectNode(); - if (item != null) { - entry.set("Item", item); - } - responsesArray.add(entry); - } - response.set("Responses", responsesArray); - addPerTableConsumedCapacity(response, request, result.capacity(), "ReadCapacityUnits"); - return Response.ok(response).build(); - } - - /** - * Botocore gives DynamoDB's {@code ResourceArnString} no pattern at all, only a length range, - * so this shape is the emulator's own. Widening the partition keeps it from rejecting a legal - * GovCloud or China table ARN. - */ - private static final java.util.regex.Pattern DYNAMODB_TABLE_ARN_PATTERN = - java.util.regex.Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX - + ":dynamodb:[a-z0-9-]+:\\d{12}:table/[a-zA-Z0-9._-]+$"); - - private static boolean isValidDynamoDbTableArn(String arn) { - return arn != null && DYNAMODB_TABLE_ARN_PATTERN.matcher(arn).matches(); - } - - private Response handleTagResource(JsonNode request, String region) { - String resourceArn = request.path("ResourceArn").asText(); - if (!isValidDynamoDbTableArn(resourceArn)) { - throw new AwsException("ValidationException", - "Invalid ResourceArn: " + resourceArn, 400); - } - Map tags = new HashMap<>(); - JsonNode tagsNode = request.path("Tags"); - if (tagsNode.isArray()) { - for (JsonNode tag : tagsNode) { - tags.put(tag.path("Key").asText(), tag.path("Value").asText()); - } - } - dynamoDbService.tagResource(resourceArn, tags, region); - return Response.ok(objectMapper.createObjectNode()).build(); - } - - private Response handleUntagResource(JsonNode request, String region) { - String resourceArn = request.path("ResourceArn").asText(); - List tagKeys = new ArrayList<>(); - JsonNode keysNode = request.path("TagKeys"); - if (keysNode.isArray()) { - for (JsonNode key : keysNode) { - tagKeys.add(key.asText()); - } - } - dynamoDbService.untagResource(resourceArn, tagKeys, region); - return Response.ok(objectMapper.createObjectNode()).build(); - } - - private Response handleListTagsOfResource(JsonNode request, String region) { - String resourceArn = request.path("ResourceArn").asText(); - Map tags; - try { - tags = dynamoDbService.listTagsOfResource(resourceArn, region); - } catch (AwsException e) { - if ("ResourceNotFoundException".equals(e.getErrorCode())) { - throw new AwsException("AccessDeniedException", - "User is not authorized to perform: dynamodb:ListTagsOfResource on resource: " - + resourceArn, 400); - } - throw e; - } - - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode tagsArray = objectMapper.createArrayNode(); - for (Map.Entry entry : tags.entrySet()) { - ObjectNode tagNode = objectMapper.createObjectNode(); - tagNode.put("Key", entry.getKey()); - tagNode.put("Value", entry.getValue()); - tagsArray.add(tagNode); - } - response.set("Tags", tagsArray); - return Response.ok(response).build(); - } - - private Response handlePutResourcePolicy(JsonNode request, String region) { - String resourceArn = request.path("ResourceArn").asText(); - if (!isValidDynamoDbTableArn(resourceArn)) { - throw new AwsException("ValidationException", - "Invalid ResourceArn: " + resourceArn, 400); - } - if (!request.hasNonNull("Policy")) { - throw new AwsException("ValidationException", - "1 validation error detected: Value null at 'policy' failed to satisfy constraint: " - + "Member must not be null", 400); - } - String policy = request.path("Policy").asText(); - String expectedRevisionId = request.has("ExpectedRevisionId") - ? request.get("ExpectedRevisionId").asText() : null; - - String revisionId = dynamoDbService.putResourcePolicy(resourceArn, policy, expectedRevisionId, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.put("RevisionId", revisionId); - return Response.ok(response).build(); - } - - private Response handleGetResourcePolicy(JsonNode request, String region) { - String resourceArn = request.path("ResourceArn").asText(); - if (!isValidDynamoDbTableArn(resourceArn)) { - throw new AwsException("ValidationException", - "Invalid ResourceArn: " + resourceArn, 400); - } - DynamoDbService.ResourcePolicyResult result = dynamoDbService.getResourcePolicy(resourceArn, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.put("Policy", result.policy()); - response.put("RevisionId", result.revisionId()); - return Response.ok(response).build(); - } - - private Response handleDeleteResourcePolicy(JsonNode request, String region) { - String resourceArn = request.path("ResourceArn").asText(); - if (!isValidDynamoDbTableArn(resourceArn)) { - throw new AwsException("ValidationException", - "Invalid ResourceArn: " + resourceArn, 400); - } - String expectedRevisionId = request.has("ExpectedRevisionId") - ? request.get("ExpectedRevisionId").asText() : null; - - String revisionId = dynamoDbService.deleteResourcePolicy(resourceArn, expectedRevisionId, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.put("RevisionId", revisionId); - return Response.ok(response).build(); - } - - private Response handleEnableKinesisStreamingDestination(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - String streamArn = request.path("StreamArn").asText(); - JsonNode precisionNode = request.path("EnableKinesisStreamingConfiguration") - .path("ApproximateCreationDateTimePrecision"); - String precision = precisionNode.isMissingNode() || precisionNode.isNull() - ? KinesisStreamingDestination.PRECISION_MILLISECOND : precisionNode.asText(); - if (!KinesisStreamingDestination.PRECISION_MILLISECOND.equals(precision) - && !KinesisStreamingDestination.PRECISION_MICROSECOND.equals(precision)) { - throw new AwsException("ValidationException", - "1 validation error detected: Value '" + precision - + "' at 'enableKinesisStreamingConfiguration.approximateCreationDateTimePrecision' " - + "failed to satisfy constraint: Member must satisfy enum value set: [MILLISECOND, MICROSECOND]", - 400); - } - - String resolvedTableName = tableService.enableKinesisStreamingDestination( - tableName, streamArn, precision, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.put("TableName", resolvedTableName); - response.put("StreamArn", streamArn); - response.put("DestinationStatus", "ACTIVE"); - response.put("DestinationStatusDescription", "Kinesis streaming is enabled for this table"); - response.putObject("EnableKinesisStreamingConfiguration") - .put("ApproximateCreationDateTimePrecision", precision); - return Response.ok(response).build(); - } - - private Response handleDisableKinesisStreamingDestination(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - String streamArn = request.path("StreamArn").asText(); - - String resolvedTableName = tableService.disableKinesisStreamingDestination(tableName, streamArn, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.put("TableName", resolvedTableName); - response.put("StreamArn", streamArn); - response.put("DestinationStatus", "DISABLED"); - response.put("DestinationStatusDescription", "Kinesis streaming is disabled for this table"); - return Response.ok(response).build(); - } - - private Response handleDescribeKinesisStreamingDestination(JsonNode request, String region) { - String tableName = request.path("TableName").asText(); - TableDefinition table = dynamoDbService.describeTable(tableName, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.put("TableName", table.getTableName()); - - ArrayNode destinations = objectMapper.createArrayNode(); - for (KinesisStreamingDestination dest : table.getKinesisStreamingDestinations()) { - ObjectNode destNode = objectMapper.createObjectNode(); - destNode.put("StreamArn", dest.getStreamArn()); - destNode.put("DestinationStatus", dest.getDestinationStatus()); - destNode.put("DestinationStatusDescription", dest.getDestinationStatusDescription()); - destNode.put("ApproximateCreationDateTimePrecision", - dest.getApproximateCreationDateTimePrecision()); - destinations.add(destNode); - } - response.set("KinesisDataStreamDestinations", destinations); - return Response.ok(response).build(); - } - - /** - * Builds a ConsumedCapacity node if the request includes ReturnConsumedCapacity. - * Uses simple estimates: 0.5 RCU per item read, 1.0 WCU per item written. - */ - private void validateItemSets(JsonNode item) { - if (item == null || !item.isObject()) return; - item.fields().forEachRemaining(entry -> { - JsonNode attr = entry.getValue(); - checkAttrSets(attr); - }); - } - - private void checkAttrSets(JsonNode attr) { - if (attr == null) return; - if (attr.has("NULL") && !attr.get("NULL").asBoolean()) { - throw new AwsException("ValidationException", - "One or more parameter values were invalid: Null attribute value types must have the value of true", 400); - } - if (attr.has("SS")) { - JsonNode ss = attr.get("SS"); - if (ss.isEmpty()) throw new AwsException("ValidationException", - "One or more parameter values were invalid: An string set may not be empty", 400); - Set seen = new HashSet<>(); - for (JsonNode e : ss) { - if (!seen.add(e.asText())) throw new AwsException("ValidationException", - "One or more parameter values were invalid: Input collection " + formatSetForError(ss) + " contains duplicates.", 400); - } - } else if (attr.has("NS")) { - JsonNode ns = attr.get("NS"); - if (ns.isEmpty()) throw new AwsException("ValidationException", - "One or more parameter values were invalid: An number set may not be empty", 400); - Set seen = new HashSet<>(); - for (JsonNode e : ns) { - if (!seen.add(e.asText())) throw new AwsException("ValidationException", - "One or more parameter values were invalid: Input collection " + formatSetForError(ns) + " contains duplicates.", 400); - } - } else if (attr.has("BS")) { - JsonNode bs = attr.get("BS"); - if (bs.isEmpty()) throw new AwsException("ValidationException", - "One or more parameter values were invalid: Binary sets should not be empty", 400); - Set seen = new HashSet<>(); - for (JsonNode e : bs) { - // A binary set names its type, and AWS leaves out the space before "of". - if (!seen.add(e.asText())) throw new AwsException("ValidationException", - "One or more parameter values were invalid: Input collection " + formatSetForError(bs) - + "of type BS contains duplicates.", 400); - } - } else if (attr.has("M")) { - attr.get("M").fields().forEachRemaining(e -> checkAttrSets(e.getValue())); - } else if (attr.has("L")) { - attr.get("L").forEach(this::checkAttrSets); - } - } - - // ── Expression token utilities ── - - private static void extractPrefixedTokens(String expr, char prefix, Set out) { - if (expr == null) return; - int i = 0; - while (i < expr.length()) { - if (expr.charAt(i) == prefix) { - int start = i++; - while (i < expr.length() && (Character.isLetterOrDigit(expr.charAt(i)) || expr.charAt(i) == '_')) i++; - if (i > start + 1) out.add(expr.substring(start, i)); - } else { - i++; - } - } - } - - private static Set extractHashTokens(String... expressions) { - Set tokens = new LinkedHashSet<>(); - for (String expr : expressions) extractPrefixedTokens(expr, '#', tokens); - return tokens; - } - - private static Set extractColonTokens(String... expressions) { - Set tokens = new LinkedHashSet<>(); - for (String expr : expressions) extractPrefixedTokens(expr, ':', tokens); - return tokens; - } - - /** - * Rejects ExpressionAttributeNames/Values supplied when the request carries no expression to - * reference them. AWS answers this sub-case with "<param> can only be specified when using - * expressions: <nullExpressionParams>" rather than the "unused in expressions" wording used - * once an alias is merely unreferenced (#2893). {@code nullExpressionParams} must spell the absent - * expression parameter(s) exactly as AWS reports them for the operation, e.g. "ConditionExpression is null". - * EAV is checked before EAN to match the pre-existing PutItem guard. - */ - private static void rejectExprAttrsWithoutExpression(JsonNode exprAttrNames, JsonNode exprAttrValues, - boolean hasAnyExpression, String nullExpressionParams) { - if (hasAnyExpression) { - return; - } - if (exprAttrValues != null) { - throw new AwsException("ValidationException", - "ExpressionAttributeValues can only be specified when using expressions: " + nullExpressionParams, 400); - } - if (exprAttrNames != null) { - throw new AwsException("ValidationException", - "ExpressionAttributeNames can only be specified when using expressions: " + nullExpressionParams, 400); - } - } - - private static void checkUnusedEan(JsonNode exprAttrNames, Set usedHashTokens) { - if (exprAttrNames == null) return; - List unused = new ArrayList<>(); - exprAttrNames.fieldNames().forEachRemaining(k -> { - if (!usedHashTokens.contains(k)) unused.add(k); - }); - if (!unused.isEmpty()) { - throw new AwsException("ValidationException", - "Value provided in ExpressionAttributeNames unused in expressions: keys: {" - + String.join(", ", unused) + "}", 400); - } - } - - private static void checkUnusedEav(JsonNode exprAttrValues, Set usedColonTokens) { - if (exprAttrValues == null) return; - List unused = new ArrayList<>(); - exprAttrValues.fieldNames().forEachRemaining(k -> { - if (!usedColonTokens.contains(k)) unused.add(k); - }); - if (!unused.isEmpty()) { - throw new AwsException("ValidationException", - "Value provided in ExpressionAttributeValues unused in expressions: keys: {" - + String.join(", ", unused) + "}", 400); - } - } - - private String formatSetForError(JsonNode arr) { - StringBuilder sb = new StringBuilder("["); - boolean first = true; - for (JsonNode e : arr) { - if (!first) sb.append(", "); - sb.append(e.asText()); - first = false; - } - sb.append("]"); - return sb.toString(); - } - - // Filters items to only include the attributes projected into the given index. - private List applyIndexProjection(List items, TableDefinition table, - DynamoDbAccessPath accessPath, String select) { - if ("ALL_ATTRIBUTES".equals(select) || "ALL".equals(accessPath.projectionType())) { - return items; - } - - Set allowed = accessPath.projectedAttributeNames(table); - return items.stream() - .map(item -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) item, allowed)) - .toList(); - } - - /** - * Half a read unit per 4KB read, doubled for a strongly consistent read, with the - * half-unit minimum DynamoDB charges even when nothing is found. - */ - static double readCapacityUnits(long bytes, boolean consistentRead) { - var units = Math.max(1, (bytes + 4095) / 4096) * 0.5; - return consistentRead ? units * 2 : units; - } - - /** - * Write-side ConsumedCapacity with the per-index arms DynamoDB reports under - * INDEXES. oldItem and newItem are the stored images around the write; the new - * image is normalized the way storage normalizes it so an identical overwrite - * compares equal. - */ - private void addWriteConsumedCapacity(ObjectNode response, JsonNode request, String tableName, - String region, JsonNode oldItem, JsonNode newItem) { - String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); - if ("NONE".equals(returnCC)) return; - TableDefinition table = dynamoDbService.requireTableForItemCall(tableName, region); - var cost = DynamoDbWriteCapacity.forWrite(table, oldItem, - newItem != null ? DynamoDbNumberUtils.normalizeNumbersInItem(newItem) : null); - response.set("ConsumedCapacity", - writeCapacityNode(tableName, cost, "INDEXES".equals(returnCC))); - } - - private void addTransactWriteConsumedCapacity(ObjectNode response, JsonNode request, - DynamoDbService.TransactWriteResult result) { - addPerTableConsumedCapacity(response, request, result.capacity(), - result.replayed() ? "ReadCapacityUnits" : "WriteCapacityUnits"); - } - - private void addPerTableConsumedCapacity(ObjectNode response, JsonNode request, - Map capacityByTable, - String unitsField) { - String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); - if ("NONE".equals(returnCC) || capacityByTable.isEmpty()) { - return; - } - ArrayNode entries = objectMapper.createArrayNode(); - capacityByTable.forEach((tableName, cost) -> - entries.add(writeCapacityNode(tableName, cost, "INDEXES".equals(returnCC), unitsField))); - response.set("ConsumedCapacity", entries); - } - - private ObjectNode writeCapacityNode(String tableName, DynamoDbWriteCapacity.Cost cost, - boolean withBreakdown) { - return writeCapacityNode(tableName, cost, withBreakdown, null); - } - - private ObjectNode writeCapacityNode(String tableName, DynamoDbWriteCapacity.Cost cost, - boolean withBreakdown, String unitsField) { - ObjectNode cc = objectMapper.createObjectNode(); - cc.put("TableName", DynamoDbTableNames.resolve(tableName)); - cc.setAll(capacityUnitsNode(cost.total(), unitsField)); - if (withBreakdown) { - cc.set("Table", capacityUnitsNode(cost.table(), unitsField)); - if (!cost.gsi().isEmpty()) { - cc.set("GlobalSecondaryIndexes", capacityUnitsMap(cost.gsi(), unitsField)); - } - if (!cost.lsi().isEmpty()) { - cc.set("LocalSecondaryIndexes", capacityUnitsMap(cost.lsi(), unitsField)); - } - if (!cost.vectorBytes().isEmpty()) { - cc.set("VectorIndexes", vectorWriteBytesMap(cost.vectorBytes())); - } - } - return cc; - } - - /** A vector index meters bytes processed, so it carries no CapacityUnits of its own. */ - private ObjectNode vectorWriteBytesMap(Map bytesByIndex) { - ObjectNode node = objectMapper.createObjectNode(); - bytesByIndex.forEach((indexName, bytes) -> { - ObjectNode entry = objectMapper.createObjectNode(); - entry.put("VectorWriteRequestBytes", bytes); - node.set(indexName, entry); - }); - return node; - } - - private ObjectNode capacityUnitsMap(Map unitsByIndex, String unitsField) { - ObjectNode node = objectMapper.createObjectNode(); - unitsByIndex.forEach((indexName, units) -> node.set(indexName, capacityUnitsNode(units, unitsField))); - return node; - } - - private ObjectNode capacityUnitsNode(double units, String unitsField) { - ObjectNode node = objectMapper.createObjectNode(); - node.put("CapacityUnits", units); - if (unitsField != null) { - node.put(unitsField, units); - } - return node; - } - - private void addConsumedCapacity(ObjectNode response, JsonNode request, String tableName, - double cu, DynamoDbAccessPath accessPath) { - String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); - if ("NONE".equals(returnCC)) return; - - ObjectNode cc = objectMapper.createObjectNode(); - cc.put("TableName", DynamoDbTableNames.resolve(tableName)); - cc.put("CapacityUnits", cu); - - if ("INDEXES".equals(returnCC)) { - ObjectNode tableCap = objectMapper.createObjectNode(); - if (accessPath != null && accessPath.isIndex()) { - tableCap.put("CapacityUnits", 0.0); - cc.set("Table", tableCap); - ObjectNode indexCaps = objectMapper.createObjectNode(); - ObjectNode indexCap = objectMapper.createObjectNode(); - indexCap.put("CapacityUnits", cu); - indexCaps.set(accessPath.indexName(), indexCap); - cc.set(accessPath.isGlobalSecondaryIndex() - ? "GlobalSecondaryIndexes" : "LocalSecondaryIndexes", indexCaps); - } else { - tableCap.put("CapacityUnits", cu); - cc.set("Table", tableCap); - } - } - - response.set("ConsumedCapacity", cc); - } - - /** - * Builds a list-style ConsumedCapacity for batch operations. - */ - private void addBatchConsumedCapacity(ObjectNode response, JsonNode request, - Map tableItems, boolean isWrite) { - String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); - if ("NONE".equals(returnCC)) return; - - ArrayNode ccArray = objectMapper.createArrayNode(); - for (String tableName : tableItems.keySet()) { - ObjectNode cc = objectMapper.createObjectNode(); - cc.put("TableName", DynamoDbTableNames.resolve(tableName)); - cc.put("CapacityUnits", isWrite ? 1.0 : 0.5); - if ("INDEXES".equals(returnCC)) { - ObjectNode tableCap = objectMapper.createObjectNode(); - tableCap.put("CapacityUnits", isWrite ? 1.0 : 0.5); - cc.set("Table", tableCap); - } - ccArray.add(cc); - } - response.set("ConsumedCapacity", ccArray); - } - - private ObjectNode tableToNode(TableDefinition table) { - ObjectNode node = objectMapper.createObjectNode(); - node.put("TableName", table.getTableName()); - node.put("TableId", table.getTableId()); - node.put("TableStatus", table.getTableStatus()); - node.put("TableArn", table.getTableArn()); - node.put("CreationDateTime", table.getCreationDateTime().getEpochSecond()); - node.put("ItemCount", table.getItemCount()); - node.put("TableSizeBytes", table.getTableSizeBytes()); - node.put("DeletionProtectionEnabled", table.isDeletionProtectionEnabled()); - - if ("PAY_PER_REQUEST".equals(table.getBillingMode())) { - ObjectNode billing = objectMapper.createObjectNode(); - billing.put("BillingMode", "PAY_PER_REQUEST"); - billing.put("LastUpdateToPayPerRequestDateTime", - table.getCreationDateTime().getEpochSecond()); - node.set("BillingModeSummary", billing); - } - - // TableClassSummary always present; defaults to STANDARD. - ObjectNode tableClassSummary = objectMapper.createObjectNode(); - tableClassSummary.put("TableClass", - table.getTableClass() != null ? table.getTableClass() : "STANDARD"); - node.set("TableClassSummary", tableClassSummary); - - if (table.getOnDemandMaxReadRequestUnits() != null - || table.getOnDemandMaxWriteRequestUnits() != null) { - ObjectNode odt = objectMapper.createObjectNode(); - if (table.getOnDemandMaxReadRequestUnits() != null) { - odt.put("MaxReadRequestUnits", table.getOnDemandMaxReadRequestUnits()); - } - if (table.getOnDemandMaxWriteRequestUnits() != null) { - odt.put("MaxWriteRequestUnits", table.getOnDemandMaxWriteRequestUnits()); - } - node.set("OnDemandThroughput", odt); - } - - ObjectNode warmThroughput = objectMapper.createObjectNode(); - warmThroughput.put("Status", "ACTIVE"); - warmThroughput.put("ReadUnitsPerSecond", 0); - warmThroughput.put("WriteUnitsPerSecond", 0); - node.set("WarmThroughput", warmThroughput); - - // Global-table replicas. In a single-process emulator every region is served by this same - // table, so a replica is metadata; AWS reports each as an ACTIVE Replica and marks the table - // a 2019.11.21 global table. A global table also lists its own home region as a replica, so it - // is appended (once) after the tracked ones; a plain table (no replicas, no home) has neither. - List replicaRegions = table.getReplicaRegions(); - String homeRegion = table.getGlobalTableHomeRegion(); - LinkedHashSet regions = new LinkedHashSet<>( - replicaRegions != null ? replicaRegions : List.of()); - if (homeRegion != null && !homeRegion.isBlank()) { - regions.add(homeRegion); - } - if (!regions.isEmpty()) { - ArrayNode replicas = objectMapper.createArrayNode(); - for (String replicaRegion : regions) { - ObjectNode replica = objectMapper.createObjectNode(); - replica.put("RegionName", replicaRegion); - replica.put("ReplicaStatus", "ACTIVE"); - replicas.add(replica); - } - node.set("Replicas", replicas); - node.put("GlobalTableVersion", "2019.11.21"); - } - - ArrayNode keySchemaArray = objectMapper.createArrayNode(); - for (var ks : table.getKeySchema()) { - ObjectNode ksNode = objectMapper.createObjectNode(); - ksNode.put("AttributeName", ks.getAttributeName()); - ksNode.put("KeyType", ks.getKeyType()); - keySchemaArray.add(ksNode); - } - node.set("KeySchema", keySchemaArray); - - ArrayNode attrDefsArray = objectMapper.createArrayNode(); - for (var ad : table.getAttributeDefinitions()) { - ObjectNode adNode = objectMapper.createObjectNode(); - adNode.put("AttributeName", ad.getAttributeName()); - adNode.put("AttributeType", ad.getAttributeType()); - attrDefsArray.add(adNode); - } - node.set("AttributeDefinitions", attrDefsArray); - - ObjectNode ptNode = objectMapper.createObjectNode(); - ptNode.put("ReadCapacityUnits", table.getProvisionedThroughput().getReadCapacityUnits()); - ptNode.put("WriteCapacityUnits", table.getProvisionedThroughput().getWriteCapacityUnits()); - ptNode.put("NumberOfDecreasesToday", table.getProvisionedThroughput().getNumberOfDecreasesToday()); - node.set("ProvisionedThroughput", ptNode); - - if (table.isSseEnabled()) { - ObjectNode sseDescription = objectMapper.createObjectNode(); - sseDescription.put("Status", "ENABLED"); - String sseType = table.getSseType() != null ? table.getSseType() : SSE_TYPE_KMS; - sseDescription.put("SSEType", sseType); - if (SSE_TYPE_KMS.equals(sseType)) { - sseDescription.put("KMSMasterKeyArn", table.getKmsMasterKeyArn() != null - ? table.getKmsMasterKeyArn() - : NativeDynamoDbTableService.defaultKmsMasterKeyArn( - AwsArnUtils.regionOrDefault(table.getTableArn(), "us-east-1"))); - } - node.set("SSEDescription", sseDescription); - } - - List gsis = table.getGlobalSecondaryIndexes(); - if (gsis != null && !gsis.isEmpty()) { - ArrayNode gsiArray = objectMapper.createArrayNode(); - for (GlobalSecondaryIndex gsi : gsis) { - ObjectNode gsiNode = objectMapper.createObjectNode(); - gsiNode.put("IndexName", gsi.getIndexName()); - gsiNode.put("IndexArn", gsi.getIndexArn()); - gsiNode.put("IndexStatus", "ACTIVE"); - - ArrayNode gsiKeySchema = objectMapper.createArrayNode(); - for (var ks : gsi.getKeySchema()) { - ObjectNode ksNode = objectMapper.createObjectNode(); - ksNode.put("AttributeName", ks.getAttributeName()); - ksNode.put("KeyType", ks.getKeyType()); - gsiKeySchema.add(ksNode); - } - gsiNode.set("KeySchema", gsiKeySchema); - - ObjectNode projection = objectMapper.createObjectNode(); - projection.put("ProjectionType", - gsi.getProjectionType() != null ? gsi.getProjectionType() : "ALL"); - if ("INCLUDE".equals(gsi.getProjectionType())){ - ArrayNode nonKeyAttributes = objectMapper.createArrayNode(); - for (var attr : gsi.getNonKeyAttributes()){ - nonKeyAttributes.add(attr); - } - projection.put("NonKeyAttributes", nonKeyAttributes); - } - gsiNode.set("Projection", projection); - - ObjectNode gsiPt = objectMapper.createObjectNode(); - gsiPt.put("ReadCapacityUnits", gsi.getProvisionedThroughput().getReadCapacityUnits()); - gsiPt.put("WriteCapacityUnits", gsi.getProvisionedThroughput().getWriteCapacityUnits()); - gsiPt.put("NumberOfDecreasesToday", gsi.getProvisionedThroughput().getNumberOfDecreasesToday()); - gsiNode.set("ProvisionedThroughput", gsiPt); - gsiNode.put("IndexSizeBytes", gsi.getIndexSizeBytes()); - gsiNode.put("ItemCount", gsi.getItemCount()); - - if (gsi.getOnDemandMaxReadRequestUnits() != null - || gsi.getOnDemandMaxWriteRequestUnits() != null) { - ObjectNode gsiOdt = objectMapper.createObjectNode(); - if (gsi.getOnDemandMaxReadRequestUnits() != null) { - gsiOdt.put("MaxReadRequestUnits", gsi.getOnDemandMaxReadRequestUnits()); - } - if (gsi.getOnDemandMaxWriteRequestUnits() != null) { - gsiOdt.put("MaxWriteRequestUnits", gsi.getOnDemandMaxWriteRequestUnits()); - } - gsiNode.set("OnDemandThroughput", gsiOdt); - } - - gsiArray.add(gsiNode); - } - node.set("GlobalSecondaryIndexes", gsiArray); - } - - List lsis = table.getLocalSecondaryIndexes(); - if (lsis != null && !lsis.isEmpty()) { - ArrayNode lsiArray = objectMapper.createArrayNode(); - for (LocalSecondaryIndex lsi : lsis) { - ObjectNode lsiNode = objectMapper.createObjectNode(); - lsiNode.put("IndexName", lsi.getIndexName()); - lsiNode.put("IndexArn", lsi.getIndexArn()); - - ArrayNode lsiKeySchema = objectMapper.createArrayNode(); - for (var ks : lsi.getKeySchema()) { - ObjectNode ksNode = objectMapper.createObjectNode(); - ksNode.put("AttributeName", ks.getAttributeName()); - ksNode.put("KeyType", ks.getKeyType()); - lsiKeySchema.add(ksNode); - } - lsiNode.set("KeySchema", lsiKeySchema); - - ObjectNode projection = objectMapper.createObjectNode(); - projection.put("ProjectionType", - lsi.getProjectionType() != null ? lsi.getProjectionType() : "ALL"); - lsiNode.set("Projection", projection); - - lsiNode.put("IndexSizeBytes", lsi.getIndexSizeBytes()); - lsiNode.put("ItemCount", lsi.getItemCount()); - - lsiArray.add(lsiNode); - } - node.set("LocalSecondaryIndexes", lsiArray); - } - - List vectorIndexes = table.getVectorIndexes(); - if (!vectorIndexes.isEmpty()) { - ArrayNode vectorIndexArray = objectMapper.createArrayNode(); - for (VectorIndex vectorIndex : vectorIndexes) { - vectorIndexArray.add(vectorIndexToNode(vectorIndex)); - } - node.set("VectorIndexes", vectorIndexArray); - } - - if (table.getStreamArn() != null) { - ObjectNode streamSpecNode = objectMapper.createObjectNode(); - streamSpecNode.put("StreamEnabled", table.isStreamEnabled()); - streamSpecNode.put("StreamViewType", table.getStreamViewType()); - node.set("StreamSpecification", streamSpecNode); - node.put("LatestStreamArn", table.getStreamArn()); - String label = table.getStreamArn().contains("/stream/") - ? table.getStreamArn().substring(table.getStreamArn().lastIndexOf("/stream/") + 8) - : ""; - node.put("LatestStreamLabel", label); - } - - return node; - } - - /** - * Renders a VectorIndexDescription. ItemCount and IndexSizeBytes are always 0. AWS refreshes - * those two roughly every six hours, so a freshly built index reports 0 for both there too. - */ - private ObjectNode vectorIndexToNode(VectorIndex vectorIndex) { - ObjectNode vectorIndexNode = objectMapper.createObjectNode(); - vectorIndexNode.put("IndexName", vectorIndex.getIndexName()); - - ObjectNode vectorAttribute = objectMapper.createObjectNode(); - vectorAttribute.put("AttributeName", vectorIndex.getVectorAttributeName()); - vectorIndexNode.set("VectorAttribute", vectorAttribute); - - List searchSchema = vectorIndex.getSearchSchema(); - if (searchSchema != null && !searchSchema.isEmpty()) { - ArrayNode searchSchemaArray = objectMapper.createArrayNode(); - for (SearchSchemaElement element : searchSchema) { - ObjectNode elementNode = objectMapper.createObjectNode(); - elementNode.put("AttributeName", element.getAttributeName()); - elementNode.put("SearchSchemaElementType", element.getSearchSchemaElementType()); - searchSchemaArray.add(elementNode); - } - vectorIndexNode.set("SearchSchema", searchSchemaArray); - } - - ObjectNode projection = objectMapper.createObjectNode(); - projection.put("ProjectionType", - vectorIndex.getProjectionType() != null ? vectorIndex.getProjectionType() : "ALL"); - if ("INCLUDE".equals(vectorIndex.getProjectionType())) { - ArrayNode nonKeyAttributes = objectMapper.createArrayNode(); - for (String attr : vectorIndex.getNonKeyAttributes()) { - nonKeyAttributes.add(attr); - } - projection.set("NonKeyAttributes", nonKeyAttributes); - } - vectorIndexNode.set("Projection", projection); - - vectorIndexNode.put("Dimensions", vectorIndex.getDimensions()); - vectorIndexNode.put("DistanceFunction", vectorIndex.getDistanceFunction()); - vectorIndexNode.put("IndexStatus", vectorIndex.getIndexStatus()); - if (dynamoDbService.reportsVectorIndexBackfilling(vectorIndex)) { - vectorIndexNode.put("Backfilling", dynamoDbService.isVectorIndexBackfilling(vectorIndex)); - } - vectorIndexNode.put("IndexSizeBytes", 0); - vectorIndexNode.put("ItemCount", 0); - vectorIndexNode.put("IndexArn", vectorIndex.getIndexArn()); - return vectorIndexNode; - } - - private ObjectNode continuousBackupsDescriptionNode(TableDefinition table) { - ObjectNode node = objectMapper.createObjectNode(); - node.put("ContinuousBackupsStatus", "ENABLED"); - - ObjectNode pitrNode = objectMapper.createObjectNode(); - pitrNode.put("PointInTimeRecoveryStatus", - table.isPointInTimeRecoveryEnabled() ? "ENABLED" : "DISABLED"); - if (table.isPointInTimeRecoveryEnabled()) { - pitrNode.put("RecoveryPeriodInDays", table.getPointInTimeRecoveryRecoveryPeriodInDays()); - } - node.set("PointInTimeRecoveryDescription", pitrNode); - return node; - } - - private Response handleExportTable(JsonNode request, String region) { - Map params = new java.util.HashMap<>(); - request.fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().isTextual() - ? e.getValue().asText() : e.getValue())); - - io.github.hectorvent.floci.services.dynamodb.model.ExportDescription desc = - dynamoDbService.exportTable(params, region); - - ObjectNode response = objectMapper.createObjectNode(); - response.set("ExportDescription", objectMapper.valueToTree(desc)); - return Response.ok(response).build(); - } - - private Response handleDescribeExport(JsonNode request, String region) { - String exportArn = request.path("ExportArn").asText(); - io.github.hectorvent.floci.services.dynamodb.model.ExportDescription desc = - dynamoDbService.describeExport(exportArn); - - ObjectNode response = objectMapper.createObjectNode(); - response.set("ExportDescription", objectMapper.valueToTree(desc)); - return Response.ok(response).build(); - } - - private Response handleListExports(JsonNode request, String region) { - String tableArn = request.has("TableArn") ? request.get("TableArn").asText() : null; - Integer maxResults = request.has("MaxResults") ? request.get("MaxResults").asInt() : null; - String nextToken = request.has("NextToken") && !request.get("NextToken").isNull() - ? request.get("NextToken").asText() : null; - - DynamoDbService.ListExportsResult result = dynamoDbService.listExports(tableArn, maxResults, nextToken); - - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode summaries = objectMapper.createArrayNode(); - for (io.github.hectorvent.floci.services.dynamodb.model.ExportSummary s : result.exportSummaries()) { - summaries.add(objectMapper.valueToTree(s)); - } - response.set("ExportSummaries", summaries); - if (result.nextToken() != null) { - response.put("NextToken", result.nextToken()); - } - 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) { - requireValidReturnConsumedCapacity(request); - String statement = request.path("Statement").asText(); - List parameters = toPartiQLParams(request.path("Parameters")); - DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(statement, parameters); - PartiQLExecuteContext ctx = PartiQLExecuteContext.builder() - .limit(request.has("Limit") ? request.get("Limit").asInt() : null) - .nextToken(request.has("NextToken") ? request.get("NextToken").asText() : null) - .consistentRead(request.path("ConsistentRead").asBoolean(false)) - .tokenBinding(partiQLHandler.tokenBinding(statement, parameters)); - DynamoDbPartiQLHandler.Result result = partiQLHandler.execute(stmt, ctx, region); - ObjectNode response = result.body(); - String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); - if (!"NONE".equals(returnCC)) { - response.set("ConsumedCapacity", - writeCapacityNode(stmt.table(), result.capacity(), "INDEXES".equals(returnCC))); - } - return Response.ok(response).build(); - } - - private Response handleExecuteTransaction(JsonNode request, String region) { - JsonNode stmts = request.path("TransactStatements"); - if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) { - throw new AwsException("ValidationException", "TransactStatements must not be empty", 400); - } - List validationErrors = new ArrayList<>(); - addReturnConsumedCapacityError(request, validationErrors); - throwValidationErrors(validationErrors); - try { - List statements = new ArrayList<>(); - for (int i = 0; i < stmts.size(); i++) { - JsonNode s = stmts.get(i); - List parameters = toPartiQLParams(s.path("Parameters")); - statements.add(inTransactStatement(i, - () -> DynamoDbPartiQLParser.parse(s.path("Statement").asText(), parameters))); - } - long reads = statements.stream().filter(DynamoDbPartiQLParser.Stmt.Select.class::isInstance).count(); - if (reads > 0 && reads < statements.size()) { - throw new AwsException("ValidationException", - "ExecuteTransaction API does not support both read and write operations in the same request.", 400); - } - if (reads == statements.size()) { - return executeTransactionReads(statements.stream() - .map(DynamoDbPartiQLParser.Stmt.Select.class::cast) - .toList(), request, region); - } - List members = new ArrayList<>(); - for (int i = 0; i < statements.size(); i++) { - DynamoDbPartiQLParser.Stmt stmt = statements.get(i); - members.add(inTransactStatement(i, () -> partiQLHandler.toTransactItem(stmt, region))); - } - List transactItems = cancelOnMemberReasons(members); - DynamoDbService.TransactWriteResult result = dynamoDbService.transactWriteItems(transactItems, region, - request.path("ClientRequestToken").asText(null), request); - ObjectNode resp = objectMapper.createObjectNode(); - resp.set("Responses", objectMapper.createArrayNode()); - addTransactWriteConsumedCapacity(resp, request, result); - return Response.ok(resp).build(); - } catch (TransactionCanceledException e) { - ObjectNode body = objectMapper.createObjectNode(); - body.put("__type", "TransactionCanceledException"); - body.put("message", e.getMessage()); - ArrayNode reasons = body.putArray("CancellationReasons"); - for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) { - ObjectNode r = objectMapper.createObjectNode(); - r.put("Code", reason.code().isEmpty() ? "None" : reason.code()); - if (!reason.code().isEmpty()) { - r.put("Message", reason.message() != null ? reason.message() : "The conditional request failed"); - } - if (reason.item() != null) { - r.set("Item", reason.item()); - } - reasons.add(r); - } - return Response.status(400).entity(body).build(); - } - } - - private Response executeTransactionReads(List selects, JsonNode request, - String region) { - List members = new ArrayList<>(); - for (int i = 0; i < selects.size(); i++) { - DynamoDbPartiQLParser.Stmt.Select select = selects.get(i); - members.add(inTransactStatement(i, () -> partiQLHandler.toTransactGetItem(select, region))); - } - List getItems = cancelOnMemberReasons(members); - - DynamoDbService.TransactGetResult result = dynamoDbService.transactGetItems(getItems, region); - requireOneReadPerItem(getItems, region); - List results = result.items(); - ArrayNode responses = objectMapper.createArrayNode(); - for (int i = 0; i < results.size(); i++) { - JsonNode item = partiQLHandler.projectSelected(selects.get(i), results.get(i)); - ObjectNode entry = objectMapper.createObjectNode(); - if (item != null) { - entry.set("Item", item); - } - responses.add(entry); - } - ObjectNode resp = objectMapper.createObjectNode(); - resp.set("Responses", responses); - addPerTableConsumedCapacity(resp, request, result.capacity(), "ReadCapacityUnits"); - return Response.ok(resp).build(); - } - - private static List cancelOnMemberReasons(List members) { - List items = new ArrayList<>(); - List reasons = new ArrayList<>(); - boolean cancelled = false; - for (DynamoDbPartiQLHandler.TransactMember member : members) { - cancelled |= member.reason() != null; - items.add(member.item()); - reasons.add(member.reason() != null ? member.reason() : new TransactionCanceledException.CancellationReason("", null)); - } - if (cancelled) { - throw new TransactionCanceledException(reasons); - } - return items; - } - - private void requireOneReadPerItem(List getItems, String region) { - Set> items = new HashSet<>(); - for (JsonNode getItem : getItems) { - JsonNode get = getItem.path("Get"); - String tableName = get.path("TableName").asText(); - TableDefinition table = dynamoDbService.findTable(tableName, region).orElseThrow(); - String itemKey = dynamoDbService.buildItemKey(table, get.path("Key"), true); - if (!items.add(List.of(tableName, itemKey))) { - throw new AwsException("ValidationException", - "Transaction request cannot include multiple operations on one item", 400); - } - } - } - - private T inTransactStatement(int index, Supplier member) { - try { - return member.get(); - } catch (AwsException e) { - if (!"ValidationException".equals(e.getErrorCode())) { - throw e; - } - throw new AwsException("ValidationException", - "Validation failed in TransactStatements[" + index + "]: " + e.getMessage(), 400); - } - } - - private Response handleBatchExecuteStatement(JsonNode request, String region) { - requireValidReturnConsumedCapacity(request); - JsonNode stmts = request.path("Statements"); - if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) { - throw new AwsException("ValidationException", "Statements must not be empty", 400); - } - ArrayNode responses = objectMapper.createArrayNode(); - Map capacity = new LinkedHashMap<>(); - for (JsonNode s : stmts) { - responses.add(batchMemberResponse(s, region, capacity)); - } - ObjectNode resp = objectMapper.createObjectNode(); - resp.set("Responses", responses); - addPerTableConsumedCapacity(resp, request, capacity, null); - return Response.ok(resp).build(); + Scope scope = new Scope(regionResolver.getAccountId(), + region != null ? region : regionResolver.getDefaultRegion()); + return toResponse(operations.execute(new Call(scope, Api.DYNAMODB, action, request))); } - private ObjectNode batchMemberResponse(JsonNode statement, String region, - Map capacity) { - ObjectNode slot = objectMapper.createObjectNode(); - String tableName = null; - try { - DynamoDbPartiQLParser.Stmt stmt = parsePartiQLStatement(statement); - tableName = stmt.table(); - if (stmt instanceof DynamoDbPartiQLParser.Stmt.Select select) { - requireBatchSelectReadsByKey(select, region); - } - DynamoDbPartiQLHandler.Result result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder() - .consistentRead(statement.path("ConsistentRead").asBoolean(false)), region); - JsonNode firstItem = result.body().path("Items").path(0); - if (!firstItem.isMissingNode()) { - slot.set("Item", firstItem); + static Response toResponse(Reply reply) { + Response.ResponseBuilder builder = Response.status(reply.status()).entity(reply.body()); + for (Map.Entry> header : reply.headers().entrySet()) { + for (String value : header.getValue()) { + builder.header(header.getKey(), value); } - slot.put("TableName", tableName); - capacity.merge(tableName, result.capacity(), DynamoDbWriteCapacity.Cost::plus); - } catch (AwsException e) { - ObjectNode err = objectMapper.createObjectNode(); - err.put("Code", batchMemberErrorCode(e.getErrorCode())); - err.put("Message", e.getMessage()); - slot.set("Error", err); - if (tableName != null && batchMemberReachedItsTable(e)) { - slot.put("TableName", tableName); - } - } - return slot; - } - - private static String batchMemberErrorCode(String errorCode) { - if ("ValidationException".equals(errorCode)) { - return "ValidationError"; - } - return errorCode.endsWith("Exception") - ? errorCode.substring(0, errorCode.length() - "Exception".length()) - : errorCode; - } - - private static boolean batchMemberReachedItsTable(AwsException e) { - return e instanceof ItemNestingExceededException - || "ConditionalCheckFailedException".equals(e.getErrorCode()) - || "DuplicateItemException".equals(e.getErrorCode()); - } - - // BatchExecuteStatement only runs SELECT statements that resolve through - // the table's primary key: index-qualified statements and partial-key - // WHERE clauses are rejected per statement (characterised on real AWS, - // eu-west-1, 2026-09-02). - private void requireBatchSelectReadsByKey(DynamoDbPartiQLParser.Stmt.Select select, String region) { - if (select.index() != null) { - throw batchSelectNeedsKey(); - } - TableDefinition table = dynamoDbService.requireTableForItemCall(select.table(), region); - DynamoDbPartiQLHandler.requireReadsWithinLimit(table, select.where()); - if (!DynamoDbPartiQLHandler.namesOnlyTheKey(table, select.where())) { - throw batchSelectNeedsKey(); - } - } - - private static AwsException batchSelectNeedsKey() { - return new AwsException("ValidationException", - "Select statements within BatchExecuteStatement must specify the primary key in the where clause.", 400); - } - - private DynamoDbPartiQLParser.Stmt parsePartiQLStatement(JsonNode statement) { - return DynamoDbPartiQLParser.parse(statement.path("Statement").asText(), - toPartiQLParams(statement.path("Parameters"))); - } - - private List toPartiQLParams(JsonNode node) { - if (node == null || node.isMissingNode() || !node.isArray()) { - return Collections.emptyList(); - } - List params = new ArrayList<>(); - for (JsonNode parameter : node) { - DynamoDbAttributeValueValidator.requireParameterNestingWithinLimit(parameter); - checkAttrSets(parameter); - params.add(parameter); } - return params; + return builder.build(); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.java index 0120944881..3266683d02 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.java @@ -133,14 +133,14 @@ class DynamoDbPartiQLHandler { private static DynamoDbWriteCapacity.Cost readCapacity(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath, Page page, boolean consistentRead) { - double units = DynamoDbJsonHandler.readCapacityUnits(page.scannedBytes(), consistentRead); + double units = NativeDynamoDbJsonHandler.readCapacityUnits(page.scannedBytes(), consistentRead); if (!accessPath.isIndex()) { return new DynamoDbWriteCapacity.Cost(units, Map.of(), Map.of()); } double tableUnits = 0; if (fetchesFromTable(stmt, table, accessPath)) { for (JsonNode item : page.scannedItems()) { - tableUnits += DynamoDbJsonHandler.readCapacityUnits( + tableUnits += NativeDynamoDbJsonHandler.readCapacityUnits( DynamoDbItemSize.calculateItemSize(item), consistentRead); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index 7a89fee3f4..a9d3bb078e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -71,11 +71,9 @@ 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; -import io.github.hectorvent.floci.core.resource.SupportedResourceType; @ApplicationScoped -public class DynamoDbService implements ResourceProvider { +public class DynamoDbService { private static final String LOCAL_REPLICA_UPDATE_ERROR = "Cannot add, delete, or update the local region through ReplicaUpdates. " @@ -1697,7 +1695,7 @@ public class DynamoDbService implements ResourceProvider { /** * Backward-compatible overload for callers that do not pass a ClientRequestToken. - * The 4-arg variant is what {@link DynamoDbJsonHandler#handleTransactWriteItems} + * The 4-arg variant is what {@link NativeDynamoDbJsonHandler#handleTransactWriteItems} * uses so the caller's ClientRequestToken is honoured. */ public void transactWriteItems(List transactItems, String region) { @@ -5017,7 +5015,6 @@ public class DynamoDbService implements ResourceProvider { return new ListImportsResult(page.items().stream().map(ImportSummary::new).toList(), page.nextToken()); } - @Override public List getResources() { List resources = new ArrayList<>(); for (TableDefinition table : tableStore.scan(k -> true)) { @@ -5033,9 +5030,4 @@ public class DynamoDbService implements ResourceProvider { } return resources; } - - @Override - public Set getSupportedResourceTypes() { - return Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true)); - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamsJsonHandler.java index 6c2df6f3d0..664415bb4b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamsJsonHandler.java @@ -1,175 +1,36 @@ package io.github.hectorvent.floci.services.dynamodb; -import io.github.hectorvent.floci.core.common.AwsErrorResponse; -import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord; -import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; -import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.RegionResolver; +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.Scope; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; -import java.util.List; - /** - * DynamoDB Streams JSON protocol handler. - * Handles requests with X-Amz-Target prefix {@code DynamoDBStreams_20120810.}. + * The public DynamoDB Streams entry point, for requests with X-Amz-Target prefix + * {@code DynamoDBStreams_20120810.}. It resolves the caller's account and region and dispatches + * through the selected backend. */ @ApplicationScoped public class DynamoDbStreamsJsonHandler { - private static final org.jboss.logging.Logger LOG = org.jboss.logging.Logger.getLogger(DynamoDbStreamsJsonHandler.class); - - private final DynamoDbStreamService streamService; - private final DynamoDbService dynamoDbService; - private final ObjectMapper objectMapper; + private final DynamoDbOperations operations; + private final RegionResolver regionResolver; @Inject - public DynamoDbStreamsJsonHandler(DynamoDbStreamService streamService, DynamoDbService dynamoDbService, - ObjectMapper objectMapper) { - this.streamService = streamService; - this.dynamoDbService = dynamoDbService; - this.objectMapper = objectMapper; + public DynamoDbStreamsJsonHandler(DynamoDbOperations operations, RegionResolver regionResolver) { + this.operations = operations; + this.regionResolver = regionResolver; } - public Response handle(String action, JsonNode request, String region) { - return switch (action) { - case "ListStreams" -> handleListStreams(request, region); - case "DescribeStream" -> handleDescribeStream(request, region); - case "GetShardIterator" -> handleGetShardIterator(request, region); - case "GetRecords" -> handleGetRecords(request, region); - default -> { - yield Response.status(400) - .entity(new AwsErrorResponse("UnknownOperationException", "Operation " + action + " is not supported.")) - .build(); - } - }; - } - - private Response handleListStreams(JsonNode request, String region) { - String tableNameFilter = request.has("TableName") ? request.get("TableName").asText() : null; - - List streams = streamService.listStreams(tableNameFilter, region); - - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode streamList = objectMapper.createArrayNode(); - for (StreamDescription sd : streams) { - ObjectNode entry = objectMapper.createObjectNode(); - entry.put("StreamArn", sd.getStreamArn()); - entry.put("StreamLabel", sd.getStreamLabel()); - entry.put("TableName", sd.getTableName()); - streamList.add(entry); - } - response.set("Streams", streamList); - return Response.ok(response).build(); - } - - private Response handleDescribeStream(JsonNode request, String region) { - String streamArn = request.path("StreamArn").asText(); - StreamDescription sd = streamService.describeStream(streamArn); - - // Fetch key schema from the table - List keySchema = List.of(); - try { - var table = dynamoDbService.describeTable(sd.getTableName(), region); - keySchema = table.getKeySchema(); - } catch (Exception ignored) { - } - - ObjectNode response = objectMapper.createObjectNode(); - response.set("StreamDescription", describeStreamToNode(sd, keySchema)); - return Response.ok(response).build(); - } - - private ObjectNode describeStreamToNode(StreamDescription sd, List keySchema) { - ObjectNode node = objectMapper.createObjectNode(); - node.put("StreamArn", sd.getStreamArn()); - node.put("StreamLabel", sd.getStreamLabel()); - node.put("StreamStatus", sd.getStreamStatus()); - node.put("StreamViewType", sd.getStreamViewType()); - node.put("TableName", sd.getTableName()); - node.put("CreationRequestDateTime", sd.getCreationDateTime().getEpochSecond()); - - ArrayNode keySchemaArray = objectMapper.createArrayNode(); - for (KeySchemaElement ks : keySchema) { - ObjectNode ksNode = objectMapper.createObjectNode(); - ksNode.put("AttributeName", ks.getAttributeName()); - ksNode.put("KeyType", ks.getKeyType()); - keySchemaArray.add(ksNode); - } - node.set("KeySchema", keySchemaArray); - - ArrayNode shards = objectMapper.createArrayNode(); - ObjectNode shard = objectMapper.createObjectNode(); - shard.put("ShardId", DynamoDbStreamService.SHARD_ID); - ObjectNode seqRange = objectMapper.createObjectNode(); - seqRange.put("StartingSequenceNumber", sd.getStartingSequenceNumber()); - shard.set("SequenceNumberRange", seqRange); - shards.add(shard); - node.set("Shards", shards); - - node.putNull("LastEvaluatedShardId"); - return node; - } - - private Response handleGetShardIterator(JsonNode request, String region) { - String streamArn = request.path("StreamArn").asText(); - String shardId = request.path("ShardId").asText(); - String iteratorType = request.path("ShardIteratorType").asText(); - String sequenceNumber = request.has("SequenceNumber") - ? request.get("SequenceNumber").asText() : null; - - String iterator = streamService.getShardIterator(streamArn, shardId, iteratorType, sequenceNumber); - - ObjectNode response = objectMapper.createObjectNode(); - response.put("ShardIterator", iterator); - return Response.ok(response).build(); - } - - private Response handleGetRecords(JsonNode request, String region) { - String shardIterator = request.path("ShardIterator").asText(); - Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; - - DynamoDbStreamService.GetRecordsResult result = streamService.getRecords(shardIterator, limit); - - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode recordsArray = objectMapper.createArrayNode(); - for (DynamoDbStreamRecord record : result.records()) { - recordsArray.add(recordToNode(record)); - } - response.set("Records", recordsArray); - response.put("NextShardIterator", result.nextShardIterator()); - - return Response.ok(response).build(); - } - - private ObjectNode recordToNode(DynamoDbStreamRecord record) { - ObjectNode node = objectMapper.createObjectNode(); - node.put("eventID", record.getEventId()); - node.put("eventName", record.getEventName()); - node.put("eventVersion", record.getEventVersion()); - node.put("eventSource", record.getEventSource()); - node.put("awsRegion", record.getAwsRegion()); - - ObjectNode dynamodb = objectMapper.createObjectNode(); - dynamodb.put("ApproximateCreationDateTime", record.getApproximateCreationDateTime()); - if (record.getKeys() != null) { - dynamodb.set("Keys", record.getKeys()); - } - if (record.getNewImage() != null) { - dynamodb.set("NewImage", record.getNewImage()); - } - if (record.getOldImage() != null) { - dynamodb.set("OldImage", record.getOldImage()); - } - dynamodb.put("SequenceNumber", record.getSequenceNumber()); - dynamodb.put("SizeBytes", 100); - dynamodb.put("StreamViewType", record.getStreamViewType()); - node.set("dynamodb", dynamodb); - - return node; + public Response handle(String action, JsonNode request, String region) throws Exception { + Scope scope = new Scope(regionResolver.getAccountId(), + region != null ? region : regionResolver.getDefaultRegion()); + return DynamoDbJsonHandler.toResponse( + operations.execute(new Call(scope, Api.DYNAMODB_STREAMS, action, request))); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java new file mode 100644 index 0000000000..b67f48aa53 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -0,0 +1,3171 @@ +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.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.CreateTableRequest; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.GsiThroughputUpdate; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.OnDemandThroughput; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.TableSettings; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.Throughput; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService.UpdateTableRequest; +import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException; +import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex; +import io.github.hectorvent.floci.services.dynamodb.model.ImportTableDescription; +import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; +import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestination; +import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex; +import io.github.hectorvent.floci.services.dynamodb.model.SearchSchemaElement; +import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.VectorIndex; +import io.github.hectorvent.floci.services.kinesis.KinesisService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +/** + * DynamoDB JSON protocol handler of the native engine, reached through the native backend + * behind the DynamoDB operation seam rather than directly from the controllers. + */ +@ApplicationScoped +public class NativeDynamoDbJsonHandler { + + private static final String SSE_TYPE_KMS = "KMS"; + + private final DynamoDbService dynamoDbService; + private final NativeDynamoDbTableService tableService; + private final ObjectMapper objectMapper; + private final DynamoDbPartiQLHandler partiQLHandler; + private final Object importLock = new Object(); + + @Inject + public NativeDynamoDbJsonHandler(DynamoDbService dynamoDbService, NativeDynamoDbTableService tableService, + ObjectMapper objectMapper) { + this.dynamoDbService = dynamoDbService; + this.tableService = tableService; + this.objectMapper = objectMapper; + this.partiQLHandler = new DynamoDbPartiQLHandler(dynamoDbService, objectMapper); + } + + /** Package-private constructor for testing. */ + NativeDynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService, + KinesisService kinesisService, ObjectMapper objectMapper) { + this(dynamoDbService, new NativeDynamoDbTableService(dynamoDbService, dynamoDbStreamService, kinesisService), + objectMapper); + } + + public Response handle(String action, JsonNode request, String region) throws Exception { + return switch (action) { + case "CreateTable" -> handleCreateTable(request, region); + case "DeleteTable" -> handleDeleteTable(request, region); + case "DescribeTable" -> handleDescribeTable(request, region); + case "ListTables" -> handleListTables(request, region); + case "PutItem" -> handlePutItem(request, region); + case "GetItem" -> handleGetItem(request, region); + case "DeleteItem" -> handleDeleteItem(request, region); + case "UpdateItem" -> handleUpdateItem(request, region); + case "Query" -> handleQuery(request, region); + case "Scan" -> handleScan(request, region); + case "SearchVectors" -> handleSearchVectors(request, region); + case "BatchWriteItem" -> handleBatchWriteItem(request, region); + case "BatchGetItem" -> handleBatchGetItem(request, region); + case "UpdateTable" -> handleUpdateTable(request, region); + case "DescribeTimeToLive" -> handleDescribeTimeToLive(request, region); + case "UpdateTimeToLive" -> handleUpdateTimeToLive(request, region); + case "DescribeContinuousBackups" -> handleDescribeContinuousBackups(request, region); + case "UpdateContinuousBackups" -> handleUpdateContinuousBackups(request, region); + case "TransactWriteItems" -> handleTransactWriteItems(request, region); + case "TransactGetItems" -> handleTransactGetItems(request, region); + case "TagResource" -> handleTagResource(request, region); + case "UntagResource" -> handleUntagResource(request, region); + case "ListTagsOfResource" -> handleListTagsOfResource(request, region); + case "PutResourcePolicy" -> handlePutResourcePolicy(request, region); + case "GetResourcePolicy" -> handleGetResourcePolicy(request, region); + case "DeleteResourcePolicy" -> handleDeleteResourcePolicy(request, region); + case "EnableKinesisStreamingDestination" -> handleEnableKinesisStreamingDestination(request, region); + case "DisableKinesisStreamingDestination" -> handleDisableKinesisStreamingDestination(request, region); + case "DescribeKinesisStreamingDestination" -> handleDescribeKinesisStreamingDestination(request, region); + case "ExportTableToPointInTime" -> handleExportTable(request, region); + case "CreateGlobalTable" -> handleCreateGlobalTable(request, region); + case "DescribeGlobalTable" -> handleDescribeGlobalTable(request, region); + case "UpdateGlobalTable" -> handleUpdateGlobalTable(request, region); + case "ListGlobalTables" -> handleListGlobalTables(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); + default -> Response.status(400) + .entity(new AwsErrorResponse("UnknownOperationException", "Operation " + action + " is not supported.")) + .build(); + + }; + } + + 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; + String tableName = DynamoDbTableNames.requireShortName(tableNameRaw); + + List keySchema = new ArrayList<>(); + request.path("KeySchema").forEach(ks -> + keySchema.add(new KeySchemaElement( + ks.path("AttributeName").asText(), + ks.path("KeyType").asText()))); + + List attrDefs = new ArrayList<>(); + request.path("AttributeDefinitions").forEach(ad -> + attrDefs.add(new AttributeDefinition( + ad.path("AttributeName").asText(), + ad.path("AttributeType").asText()))); + + JsonNode pt = request.path("ProvisionedThroughput"); + Throughput throughput = null; + if (!pt.isMissingNode()) { + throughput = new Throughput( + pt.path("ReadCapacityUnits").asLong(5), pt.path("WriteCapacityUnits").asLong(5)); + } + + List gsis = new ArrayList<>(); + JsonNode gsiArray = request.path("GlobalSecondaryIndexes"); + if (!gsiArray.isMissingNode() && gsiArray.isArray()) { + var gsiPosition = 0; + for (JsonNode gsiNode : gsiArray) { + gsiPosition++; + String indexName = gsiNode.path("IndexName").asText(); + List gsiKeySchema = new ArrayList<>(); + gsiNode.path("KeySchema").forEach(ks -> + gsiKeySchema.add(new KeySchemaElement( + ks.path("AttributeName").asText(), + ks.path("KeyType").asText()))); + String projectionType = gsiNode.path("Projection").path("ProjectionType").asText("ALL"); + JsonNode nonKeyAttrArray = gsiNode.path("Projection").path("NonKeyAttributes"); + List nonKeyAttributes = new ArrayList<>(); + if (!nonKeyAttrArray.isMissingNode() && nonKeyAttrArray.isArray()){ + for (JsonNode nonKeyAttr : nonKeyAttrArray){ + nonKeyAttributes.add(nonKeyAttr.asText()); + } + } + rejectEmptyNonKeyAttributes(nonKeyAttrArray, "globalSecondaryIndexes." + gsiPosition + ".member"); + validateProjectionSpec(projectionType, nonKeyAttributes); + GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes); + JsonNode gsiPt = gsiNode.path("ProvisionedThroughput"); + if (!gsiPt.isMissingNode()) { + gsi.getProvisionedThroughput().setReadCapacityUnits(gsiPt.path("ReadCapacityUnits").asLong(0)); + gsi.getProvisionedThroughput().setWriteCapacityUnits(gsiPt.path("WriteCapacityUnits").asLong(0)); + } + JsonNode gsiOnDemand = gsiNode.path("OnDemandThroughput"); + if (gsiOnDemand.isObject()) { + if (gsiOnDemand.has("MaxReadRequestUnits")) { + gsi.setOnDemandMaxReadRequestUnits(gsiOnDemand.get("MaxReadRequestUnits").asInt()); + } + if (gsiOnDemand.has("MaxWriteRequestUnits")) { + gsi.setOnDemandMaxWriteRequestUnits(gsiOnDemand.get("MaxWriteRequestUnits").asInt()); + } + } + gsis.add(gsi); + } + } + + List lsis = new ArrayList<>(); + JsonNode lsiArray = request.path("LocalSecondaryIndexes"); + if (!lsiArray.isMissingNode() && lsiArray.isArray()) { + var lsiPosition = 0; + for (JsonNode lsiNode : lsiArray) { + lsiPosition++; + String indexName = lsiNode.path("IndexName").asText(); + List lsiKeySchema = new ArrayList<>(); + lsiNode.path("KeySchema").forEach(ks -> + lsiKeySchema.add(new KeySchemaElement( + ks.path("AttributeName").asText(), + ks.path("KeyType").asText()))); + String projectionType = lsiNode.path("Projection").path("ProjectionType").asText("ALL"); + JsonNode lsiNonKeyAttrArray = lsiNode.path("Projection").path("NonKeyAttributes"); + List lsiNonKeyAttributes = new ArrayList<>(); + if (!lsiNonKeyAttrArray.isMissingNode() && lsiNonKeyAttrArray.isArray()) { + lsiNonKeyAttrArray.forEach(a -> lsiNonKeyAttributes.add(a.asText())); + } + rejectEmptyNonKeyAttributes(lsiNonKeyAttrArray, "localSecondaryIndexes." + lsiPosition + ".member"); + validateProjectionSpec(projectionType, lsiNonKeyAttributes); + lsis.add(new LocalSecondaryIndex(indexName, lsiKeySchema, null, projectionType, lsiNonKeyAttributes)); + } + } + + List vectorIndexes = new ArrayList<>(); + JsonNode vectorIndexArray = request.path("VectorIndexes"); + if (vectorIndexArray.isArray()) { + int vectorPosition = 0; + for (JsonNode vectorIndexNode : vectorIndexArray) { + vectorPosition++; + String memberPath = "vectorIndexes." + vectorPosition + ".member"; + vectorIndexes.add(new DynamoDbService.VectorIndexCreate( + parseVectorIndex(vectorIndexNode, memberPath), memberPath)); + } + } + + Map tags = new LinkedHashMap<>(); + JsonNode tagsNode = request.path("Tags"); + if (tagsNode.isArray()) { + for (JsonNode tag : tagsNode) { + tags.put(tag.path("Key").asText(), tag.path("Value").asText()); + } + } + + return tableService.createTable(new CreateTableRequest(tableName, keySchema, attrDefs, + throughput, gsis, lsis, vectorIndexes, tags, parseTableSettings(request)), initialStatus, region); + } + + /** + * The table-level settings CreateTable and UpdateTable share. A member absent from the request + * is null; the service applies the per-operation defaults. + */ + private static TableSettings parseTableSettings(JsonNode request) { + String billingMode = request.has("BillingMode") ? request.get("BillingMode").asText() : null; + + JsonNode deletionProtectionNode = request.path("DeletionProtectionEnabled"); + Boolean deletionProtection = deletionProtectionNode.isMissingNode() + ? null : deletionProtectionNode.asBoolean(); + + String tableClass = request.has("TableClass") ? request.get("TableClass").asText() : null; + + JsonNode streamSpec = request.path("StreamSpecification"); + Boolean streamEnabled = streamSpec.isMissingNode() + ? null : streamSpec.path("StreamEnabled").asBoolean(false); + String streamViewType = streamSpec.hasNonNull("StreamViewType") + ? streamSpec.get("StreamViewType").asText() : null; + + JsonNode sseSpec = request.path("SSESpecification"); + Boolean sseEnabled = sseSpec.isMissingNode() ? null : sseSpec.path("Enabled").asBoolean(false); + String sseType = sseSpec.hasNonNull("SSEType") ? sseSpec.get("SSEType").asText() : null; + JsonNode kmsMasterKeyIdNode = sseSpec.path("KMSMasterKeyId"); + String kmsMasterKeyId = kmsMasterKeyIdNode.isMissingNode() || kmsMasterKeyIdNode.isNull() + ? null : kmsMasterKeyIdNode.asText(); + + return new TableSettings(billingMode, deletionProtection, tableClass, + parseOnDemandThroughput(request.path("OnDemandThroughput")), + streamEnabled, streamViewType, sseEnabled, sseType, kmsMasterKeyId); + } + + private static OnDemandThroughput parseOnDemandThroughput(JsonNode onDemand) { + if (!onDemand.isObject()) { + return null; + } + Integer maxRead = onDemand.has("MaxReadRequestUnits") ? onDemand.get("MaxReadRequestUnits").asInt() : null; + Integer maxWrite = onDemand.has("MaxWriteRequestUnits") ? onDemand.get("MaxWriteRequestUnits").asInt() : null; + return new OnDemandThroughput(maxRead, maxWrite); + } + + // AWS reports an empty list as a length constraint on the 1-based member path, before the + // projection type check. A null NonKeyAttributes counts as not specified. + private static void rejectEmptyNonKeyAttributes(JsonNode nonKeyAttrArray, String memberPath) { + if (nonKeyAttrArray.isArray() && nonKeyAttrArray.isEmpty()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '[]' at '" + memberPath + + ".projection.nonKeyAttributes' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1", 400); + } + } + + /** Reads a VectorIndex or the CreateVectorIndexAction of a VectorIndexUpdate; same members. */ + private static VectorIndex parseVectorIndex(JsonNode node, String memberPath) { + // An absent VectorAttribute is reported as the member itself, one that is present but + // carries no AttributeName as the nested member. Only the request shape tells them apart. + JsonNode vectorAttribute = node.path("VectorAttribute"); + if (vectorAttribute.isObject() && !vectorAttribute.hasNonNull("AttributeName")) { + throw new AwsException("ValidationException", + "1 validation error detected: Value null at '" + memberPath + + ".vectorAttribute.attributeName' failed to satisfy constraint: " + + "Member must not be null", 400); + } + List searchSchema = new ArrayList<>(); + JsonNode searchSchemaArray = node.path("SearchSchema"); + if (searchSchemaArray.isArray()) { + for (JsonNode element : searchSchemaArray) { + searchSchema.add(new SearchSchemaElement( + element.path("AttributeName").asText(null), + element.path("SearchSchemaElementType").asText(null))); + } + } + String projectionType = node.hasNonNull("Projection") + ? node.path("Projection").path("ProjectionType").asText("ALL") : null; + List nonKeyAttributes = new ArrayList<>(); + JsonNode nonKeyAttrArray = node.path("Projection").path("NonKeyAttributes"); + if (nonKeyAttrArray.isArray()) { + for (JsonNode nonKeyAttr : nonKeyAttrArray) { + nonKeyAttributes.add(nonKeyAttr.asText()); + } + } + rejectEmptyNonKeyAttributes(nonKeyAttrArray, memberPath); + validateProjectionSpec(projectionType, nonKeyAttributes); + Long dimensions = node.hasNonNull("Dimensions") ? node.get("Dimensions").asLong() : null; + return new VectorIndex( + node.path("IndexName").asText(null), + node.path("VectorAttribute").path("AttributeName").asText(null), + searchSchema, + projectionType, + nonKeyAttributes, + dimensions, + node.path("DistanceFunction").asText(null)); + } + + // INCLUDE requires the NonKeyAttributes list; every other projection type forbids it. + private static void validateProjectionSpec(String projectionType, List nonKeyAttributes) { + if ("INCLUDE".equals(projectionType) && nonKeyAttributes.isEmpty()) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: " + + "ProjectionType is INCLUDE, but NonKeyAttributes is not specified", 400); + } + if (!"INCLUDE".equals(projectionType) && !nonKeyAttributes.isEmpty()) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: " + + "ProjectionType is " + projectionType + ", but NonKeyAttributes is specified", 400); + } + } + + private Response handleDeleteTable(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + TableDefinition table = dynamoDbService.describeTable(tableName, region); + if (table.isDeletionProtectionEnabled()) { + throw new AwsException("ValidationException", + "Table " + tableName + " is protected against deletion. To delete the table, " + + "DeletionProtectionEnabled must be set to false.", 400); + } + ObjectNode response = objectMapper.createObjectNode(); + response.set("TableDescription", tableToNode(table)); + dynamoDbService.deleteTable(tableName, region); + return Response.ok(response).build(); + } + + // ── Global tables, the 2017.11.29 API ──────────────────────────────────── + + private Response handleCreateGlobalTable(JsonNode request, String region) { + String name = request.path("GlobalTableName").asText(); + TableDefinition table = dynamoDbService.createGlobalTable( + name, replicationGroupRegions(request), region); + ObjectNode root = objectMapper.createObjectNode(); + root.set("GlobalTableDescription", globalTableDescription(table, name)); + return Response.ok(root).build(); + } + + private Response handleDescribeGlobalTable(JsonNode request, String region) { + String name = request.path("GlobalTableName").asText(); + TableDefinition table = dynamoDbService.describeGlobalTable(name, region); + ObjectNode root = objectMapper.createObjectNode(); + root.set("GlobalTableDescription", globalTableDescription(table, name)); + return Response.ok(root).build(); + } + + private Response handleUpdateGlobalTable(JsonNode request, String region) { + String name = request.path("GlobalTableName").asText(); + List adds = new ArrayList<>(); + List removes = new ArrayList<>(); + for (JsonNode update : request.path("ReplicaUpdates")) { + String create = update.path("Create").path("RegionName").asText(null); + String delete = update.path("Delete").path("RegionName").asText(null); + if (create != null) { + adds.add(create); + } + if (delete != null) { + removes.add(delete); + } + } + TableDefinition table = dynamoDbService.updateGlobalTable(name, adds, removes, region); + ObjectNode root = objectMapper.createObjectNode(); + root.set("GlobalTableDescription", globalTableDescription(table, name)); + return Response.ok(root).build(); + } + + private Response handleListGlobalTables(JsonNode request, String region) { + String regionFilter = request.path("RegionName").asText(null); + ArrayNode list = objectMapper.createArrayNode(); + for (TableDefinition table : dynamoDbService.listGlobalTables(regionFilter, region)) { + ObjectNode entry = objectMapper.createObjectNode(); + entry.put("GlobalTableName", table.getTableName()); + entry.set("ReplicationGroup", replicaNodes(table, objectMapper.createArrayNode(), false)); + list.add(entry); + } + ObjectNode root = objectMapper.createObjectNode(); + root.set("GlobalTables", list); + return Response.ok(root).build(); + } + + private static List replicationGroupRegions(JsonNode request) { + List regions = new ArrayList<>(); + for (JsonNode replica : request.path("ReplicationGroup")) { + String name = replica.path("RegionName").asText(null); + if (name != null && !name.isBlank()) { + regions.add(name); + } + } + return regions; + } + + private ObjectNode globalTableDescription(TableDefinition table, String globalTableName) { + ObjectNode description = objectMapper.createObjectNode(); + description.put("GlobalTableName", globalTableName); + description.put("GlobalTableStatus", "ACTIVE"); + description.put("GlobalTableArn", table.getTableArn()); + if (table.getCreationDateTime() != null) { + description.put("CreationDateTime", table.getCreationDateTime().getEpochSecond()); + } + description.set("ReplicationGroup", replicaNodes(table, objectMapper.createArrayNode(), true)); + return description; + } + + /** + * The replica list of a global table: every tracked replica plus the home region, which AWS + * reports as a replica of its own global table. ReplicaStatus is only carried by the + * description shapes, not by the ListGlobalTables entry. + */ + private ArrayNode replicaNodes(TableDefinition table, ArrayNode replicas, boolean withStatus) { + LinkedHashSet regions = new LinkedHashSet<>( + table.getReplicaRegions() != null ? table.getReplicaRegions() : List.of()); + if (table.getGlobalTableHomeRegion() != null) { + regions.add(table.getGlobalTableHomeRegion()); + } + for (String replicaRegion : regions) { + ObjectNode replica = objectMapper.createObjectNode(); + replica.put("RegionName", replicaRegion); + if (withStatus) { + replica.put("ReplicaStatus", "ACTIVE"); + } + replicas.add(replica); + } + return replicas; + } + + private Response handleDescribeTable(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + TableDefinition table = dynamoDbService.describeTable(tableName, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("Table", tableToNode(table)); + return Response.ok(response).build(); + } + + private Response handleListTables(JsonNode request, String region) { + Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; + String exclusiveStart = request.has("ExclusiveStartTableName") + ? request.get("ExclusiveStartTableName").asText() : null; + + if (limit != null) { + if (limit < 1) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + limit + + "' at 'limit' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1", 400); + } + if (limit > 100) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + limit + + "' at 'limit' failed to satisfy constraint: " + + "Member must have value less than or equal to 100", 400); + } + } + + DynamoDbService.ListTablesResult result = dynamoDbService.listTables(region, limit, exclusiveStart); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode tableNames = objectMapper.createArrayNode(); + result.tableNames().forEach(tableNames::add); + response.set("TableNames", tableNames); + if (result.lastEvaluatedTableName() != null) { + response.put("LastEvaluatedTableName", result.lastEvaluatedTableName()); + } + return Response.ok(response).build(); + } + + private static final Set VALID_RETURN_VALUES_PUT = Set.of("NONE", "ALL_OLD"); + private static final Set VALID_RETURN_CONSUMED_CAPACITY = Set.of("INDEXES", "TOTAL", "NONE"); + private static final Set VALID_RETURN_ITEM_COLLECTION_METRICS = Set.of("SIZE", "NONE"); + + private Response handlePutItem(JsonNode request, String region) { + String tableName = request.has("TableName") ? request.path("TableName").asText() : null; + DynamoDbTableNames.resolve(tableName); // validate tableName before other params + JsonNode item = request.path("Item"); + String returnValues = request.path("ReturnValues").asText("NONE"); + String returnValuesOnConditionCheckFailure = request.path("ReturnValuesOnConditionCheckFailure").asText("NONE"); + String conditionExpression = request.has("ConditionExpression") + ? request.get("ConditionExpression").asText() : null; + JsonNode exprAttrNames = request.has("ExpressionAttributeNames") + ? request.get("ExpressionAttributeNames") : null; + JsonNode exprAttrValues = request.has("ExpressionAttributeValues") + ? request.get("ExpressionAttributeValues") : null; + + List validationErrors = new ArrayList<>(); + String rcc = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; + if (rcc != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rcc)) { + validationErrors.add("Value '" + rcc + "' at 'returnConsumedCapacity' failed to satisfy constraint: " + + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"); + } + String ricm = request.has("ReturnItemCollectionMetrics") ? request.get("ReturnItemCollectionMetrics").asText() : null; + if (ricm != null && !VALID_RETURN_ITEM_COLLECTION_METRICS.contains(ricm)) { + validationErrors.add("Value '" + ricm + "' at 'returnItemCollectionMetrics' failed to satisfy constraint: " + + "Member must satisfy enum value set: [SIZE, NONE]"); + } + if (!VALID_RETURN_VALUES_PUT.contains(returnValues)) { + validationErrors.add("Value '" + returnValues + "' at 'returnValues' failed to satisfy constraint: " + + "Member must satisfy enum value set: [NONE, ALL_OLD]"); + } + if (!validationErrors.isEmpty()) { + int n = validationErrors.size(); + throw new AwsException("ValidationException", + n + " validation error" + (n > 1 ? "s" : "") + " detected: " + + String.join("; ", validationErrors), 400); + } + DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(item); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); + DynamoDbNumberUtils.requireStorable(exprAttrValues, true); + + JsonNode expected = request.has("Expected") ? request.get("Expected") : null; + DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(expected)); + String conditionalOperator = request.has("ConditionalOperator") + ? request.get("ConditionalOperator").asText() : "AND"; + + if (conditionExpression != null && expected != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); + } + + // EAN/EAV with no expression to reference them: AWS reports "can only be specified + // when using expressions", not the "unused in expressions" wording (#2893). + rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues, + conditionExpression != null, "ConditionExpression is null"); + + ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues); + + // Reject ExpressionAttributeNames/Values entries not referenced by ConditionExpression (AWS parity, #2893) + checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression)); + checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression)); + + validateItemSets(item); + + JsonNode oldItem = null; + if ("ALL_OLD".equals(returnValues) || expected != null) { + dynamoDbService.requireTableForItemCall(tableName, region); + oldItem = dynamoDbService.getItem(tableName, item, region); + } + + if (expected != null) { + evaluateLegacyExpected(oldItem, expected, conditionalOperator, returnValuesOnConditionCheckFailure); + } + + var previousItem = dynamoDbService.putItem(tableName, item, conditionExpression, + exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure); + + ObjectNode response = objectMapper.createObjectNode(); + if ("ALL_OLD" .equals(returnValues) && oldItem != null) { + response.set("Attributes", oldItem); + } + addItemCollectionMetrics(response, request, tableName, item, region); + addWriteConsumedCapacity(response, request, tableName, region, previousItem, item); + return Response.ok(response).build(); + } + + private Response handleGetItem(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + JsonNode key = request.path("Key"); + String projectionExpression = request.has("ProjectionExpression") + ? request.get("ProjectionExpression").asText() : null; + JsonNode exprAttrNames = request.has("ExpressionAttributeNames") + ? request.get("ExpressionAttributeNames") : null; + JsonNode attributesToGet = request.has("AttributesToGet") ? request.get("AttributesToGet") : null; + + if (attributesToGet != null && projectionExpression != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); + } + + // Validate enums before table lookup + String rccGet = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; + if (rccGet != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccGet)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + rccGet + "' at 'returnConsumedCapacity' failed to satisfy constraint: " + + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); + } + + // Validate ProjectionExpression syntax and reserved words before item lookup + if (projectionExpression != null) { + DynamoDbExpressionSize.checkRead(projectionExpression, "ProjectionExpression"); + ProjectionEvaluator.validateExpression(projectionExpression, exprAttrNames); + } + + JsonNode item = dynamoDbService.getItem(tableName, key, region); + var itemBytes = item != null ? DynamoDbItemSize.calculateItemSize(item) : 0; + if (item != null && projectionExpression != null) { + item = ProjectionEvaluator.project(item, projectionExpression, exprAttrNames); + } else if (item != null && attributesToGet != null) { + Set keep = new HashSet<>(); + attributesToGet.forEach(n -> keep.add(n.asText())); + item = ProjectionEvaluator.trimToAttributes((ObjectNode) item, keep); + } + + ObjectNode response = objectMapper.createObjectNode(); + if (item != null) { + response.set("Item", item); + } + addConsumedCapacity(response, request, tableName, + readCapacityUnits(itemBytes, request.path("ConsistentRead").asBoolean(false)), null); + return Response.ok(response).build(); + } + + private static final Set VALID_RETURN_VALUES_DELETE = Set.of("NONE", "ALL_OLD"); + private static final Set VALID_RETURN_VALUES_UPDATE = + Set.of("NONE", "ALL_OLD", "ALL_NEW", "UPDATED_OLD", "UPDATED_NEW"); + + private Response handleDeleteItem(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + DynamoDbTableNames.resolve(tableName); // validate tableName first + JsonNode key = request.path("Key"); + String returnValues = request.path("ReturnValues").asText("NONE"); + String returnValuesOnConditionCheckFailure = request.path("ReturnValuesOnConditionCheckFailure").asText("NONE"); + String conditionExpression = request.has("ConditionExpression") + ? request.get("ConditionExpression").asText() : null; + JsonNode exprAttrNames = request.has("ExpressionAttributeNames") + ? request.get("ExpressionAttributeNames") : null; + JsonNode exprAttrValues = request.has("ExpressionAttributeValues") + ? request.get("ExpressionAttributeValues") : null; + + // Validate ReturnValues + ReturnConsumedCapacity together + List delValidationErrors = new ArrayList<>(); + String rccDel = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; + if (rccDel != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccDel)) { + delValidationErrors.add("Value '" + rccDel + "' at 'returnConsumedCapacity' failed to satisfy constraint: " + + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"); + } + if (!VALID_RETURN_VALUES_DELETE.contains(returnValues)) { + delValidationErrors.add("Value '" + returnValues + "' at 'returnValues' failed to satisfy constraint: " + + "Member must satisfy enum value set: [NONE, ALL_OLD]"); + } + if (!delValidationErrors.isEmpty()) { + int n = delValidationErrors.size(); + throw new AwsException("ValidationException", + n + " validation error" + (n > 1 ? "s" : "") + " detected: " + + String.join("; ", delValidationErrors), 400); + } + DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); + DynamoDbNumberUtils.requireStorable(exprAttrValues, true); + JsonNode expectedDel = request.has("Expected") ? request.get("Expected") : null; + DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(expectedDel)); + + if (conditionExpression != null && expectedDel != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); + } + + // EAN/EAV with no expression to reference them: AWS reports "can only be specified + // when using expressions", not the "unused in expressions" wording (#2893). + rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues, + conditionExpression != null, "ConditionExpression is null"); + + ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues); + + // Reject ExpressionAttributeNames/Values entries not referenced by ConditionExpression (AWS parity, #2893) + checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression)); + checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression)); + + String condOpDel = request.has("ConditionalOperator") + ? request.get("ConditionalOperator").asText() : "AND"; + if (expectedDel != null) { + JsonNode existingForDel = dynamoDbService.getItem(tableName, key, region); + evaluateLegacyExpected(existingForDel, expectedDel, condOpDel, returnValuesOnConditionCheckFailure); + } + + JsonNode oldItem = dynamoDbService.deleteItem(tableName, key, conditionExpression, + exprAttrNames, exprAttrValues, region, returnValuesOnConditionCheckFailure); + + ObjectNode response = objectMapper.createObjectNode(); + if ("ALL_OLD" .equals(returnValues) && oldItem != null) { + response.set("Attributes", oldItem); + } + addItemCollectionMetrics(response, request, tableName, key, region); + addWriteConsumedCapacity(response, request, tableName, region, oldItem, null); + return Response.ok(response).build(); + } + + private Response handleUpdateItem(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + DynamoDbTableNames.resolve(tableName); // validate tableName first + JsonNode key = request.path("Key"); + JsonNode attributeUpdates = request.path("AttributeUpdates"); + JsonNode exprAttrNames = request.has("ExpressionAttributeNames") + ? request.get("ExpressionAttributeNames") : null; + JsonNode exprAttrValues = request.has("ExpressionAttributeValues") + ? request.get("ExpressionAttributeValues") : null; + String updateExpression = request.has("UpdateExpression") + ? request.get("UpdateExpression").asText() : null; + String conditionExpression = request.has("ConditionExpression") + ? request.get("ConditionExpression").asText() : null; + String returnValues = request.path("ReturnValues").asText("NONE"); + String returnValuesOnConditionCheckFailure = request.path("ReturnValuesOnConditionCheckFailure").asText("NONE"); + + // UpdateItem stops at the first invalid enum and reports one error, unlike PutItem + // and DeleteItem which aggregate. + String rccUpd = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; + if (!VALID_RETURN_VALUES_UPDATE.contains(returnValues)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + returnValues + "' at 'returnValues' " + + "failed to satisfy constraint: " + + "Member must satisfy enum value set: [NONE, ALL_OLD, ALL_NEW, UPDATED_OLD, UPDATED_NEW]", 400); + } + if (rccUpd != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccUpd)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + rccUpd + "' at 'returnConsumedCapacity' " + + "failed to satisfy constraint: " + + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); + } + DynamoDbExpressionSize.checkWrite(updateExpression, "UpdateExpression"); + DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); + DynamoDbNumberUtils.requireStorable(exprAttrValues, true); + var attributeUpdateValues = legacyValues(attributeUpdates); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(attributeUpdateValues); + DynamoDbNumberUtils.requireStorable(attributeUpdateValues, true); + DynamoDbAttributeValueValidator.requireNestingWithinLimit( + legacyValues(request.has("Expected") ? request.get("Expected") : null)); + + JsonNode updateData = attributeUpdates.isMissingNode() ? null : attributeUpdates; + JsonNode expectedUpd = request.has("Expected") ? request.get("Expected") : null; + String conditionalOperatorUpd = request.has("ConditionalOperator") + ? request.get("ConditionalOperator").asText() : "AND"; + + if (updateData != null && updateExpression != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {AttributeUpdates} Expression parameters: {UpdateExpression}", 400); + } + + // EAN/EAV with no expression to reference them, mirroring the PutItem guard. + rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues, + updateExpression != null || conditionExpression != null, + "UpdateExpression is null, ConditionExpression is null"); + + ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues); + + if (conditionExpression != null && expectedUpd != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); + } + + // Validate EAN/EAV usage across UpdateExpression + ConditionExpression + if (updateExpression != null) { + // Pre-validate syntax: expression must start with a valid clause keyword. + // AWS tokenizes UpdateExpression whitespace-insensitively, so collapse runs + // of whitespace (newlines, tabs, multiple spaces) before matching keywords. + String ue = updateExpression.trim().replaceAll("\\s+", " "); + if (!ue.isEmpty()) { + String upper = ue.toUpperCase(); + if (!upper.startsWith("SET ") && !upper.startsWith("REMOVE ") && !upper.startsWith("ADD ") && !upper.startsWith("DELETE ")) { + String[] parts = ue.split("\\s+", 3); + String token = parts[0]; + String near = parts.length >= 2 + ? (token + " " + parts[1]).substring(0, Math.min(token.length() + 1 + parts[1].length(), 20)) + : token; + throw new AwsException("ValidationException", + "Invalid UpdateExpression: Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400); + } + } + Set colonTokens = extractColonTokens(updateExpression); + for (String token : colonTokens) { + if (exprAttrValues == null || !exprAttrValues.has(token)) { + throw new AwsException("ValidationException", + "Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: " + token, 400); + } + } + Set hashTokens = extractHashTokens(updateExpression, conditionExpression); + checkUnusedEan(exprAttrNames, hashTokens); + Set colonTokensAll = extractColonTokens(updateExpression, conditionExpression); + checkUnusedEav(exprAttrValues, colonTokensAll); + dynamoDbService.requireAddOrDeleteOperandTypes(updateExpression, exprAttrValues, true); + } + + if (expectedUpd != null) { + JsonNode existingForUpd = dynamoDbService.getItem(tableName, key, region); + evaluateLegacyExpected(existingForUpd, expectedUpd, conditionalOperatorUpd, returnValuesOnConditionCheckFailure); + } + + DynamoDbService.UpdateResult result = dynamoDbService.updateItem( + tableName, key, updateData, updateExpression, exprAttrNames, exprAttrValues, + returnValues, conditionExpression, region, returnValuesOnConditionCheckFailure); + + ObjectNode response = objectMapper.createObjectNode(); + if ("ALL_NEW" .equals(returnValues) && result.newItem() != null) { + response.set("Attributes", result.newItem()); + } else if ("ALL_OLD" .equals(returnValues) && result.oldItem() != null) { + response.set("Attributes", result.oldItem()); + } else if ("UPDATED_NEW".equals(returnValues) || "UPDATED_OLD".equals(returnValues)) { + var updated = DynamoDbUpdatedAttributes.collect(result.touched(), "UPDATED_NEW".equals(returnValues)); + // AWS omits Attributes when no touched path has a value on that side. + if (!updated.isEmpty()) { + response.set("Attributes", updated); + } + } + addItemCollectionMetrics(response, request, tableName, key, region); + addWriteConsumedCapacity(response, request, tableName, region, result.oldItem(), result.newItem()); + return Response.ok(response).build(); + } + + private void evaluateLegacyExpected(JsonNode existing, JsonNode expected, String conditionalOperator, + String returnValuesOnConditionCheckFailure) { + if (expected == null) return; + validateLegacyExpected(expected); + boolean useOr = "OR".equals(conditionalOperator); + boolean overall = !useOr; + var fields = expected.fields(); + while (fields.hasNext()) { + var entry = fields.next(); + String attrName = entry.getKey(); + JsonNode condition = entry.getValue(); + JsonNode attrValue = existing != null ? existing.get(attrName) : null; + boolean condResult; + if (condition.has("Exists") && !condition.get("Exists").asBoolean()) { + condResult = attrValue == null; + } else { + // Exists:true always carries a Value, so it evaluates as an attribute + // comparison exactly like a bare Value: must exist AND match. + condResult = dynamoDbService.matchesKeyConditionPublic(attrValue, normalizeLegacyCondition(condition)); + } + if (useOr) overall = overall || condResult; + else overall = overall && condResult; + } + if (!overall) { + if ("ALL_OLD".equals(returnValuesOnConditionCheckFailure)) { + throw new ConditionalCheckFailedException(existing); + } else { + throw new ConditionalCheckFailedException(null); + } + } + } + + /** + * Validates every entry of a legacy Expected map before any condition is evaluated. + * The rules and their precedence mirror ExpectedAttributeValue: + *

    + *
  • {@code AttributeValueList} is only meaningful alongside a {@code ComparisonOperator}.
  • + *
  • {@code Exists} cannot be combined with a {@code ComparisonOperator}: they are + * alternative forms.
  • + *
  • Without a {@code ComparisonOperator}, a {@code Value} is required unless + * {@code Exists: false} asks for plain absence.
  • + *
  • {@code Exists: false} forbids a {@code Value}: an attribute cannot be expected to + * hold a value while also being expected to be absent.
  • + *
+ * DynamoDB reports only the first offending entry, so validation stops at the first error. + */ + private void validateLegacyExpected(JsonNode expected) { + var fields = expected.fields(); + while (fields.hasNext()) { + var entry = fields.next(); + String attrName = entry.getKey(); + JsonNode condition = entry.getValue(); + boolean hasComparisonOperator = condition.has("ComparisonOperator"); + boolean hasExists = condition.has("Exists"); + boolean hasValue = condition.has("Value"); + + if (condition.has("AttributeValueList") && !hasComparisonOperator) { + throw legacyExpectedValidationError( + "AttributeValueList can only be used with a ComparisonOperator for Attribute: " + attrName); + } + if (hasExists && hasComparisonOperator) { + throw legacyExpectedValidationError( + "Exists and ComparisonOperator cannot be used together for Attribute: " + attrName); + } + boolean expectsValue = !hasExists || condition.get("Exists").asBoolean(); + if (!hasComparisonOperator && expectsValue && !hasValue) { + throw legacyExpectedValidationError("Value must be provided when Exists is " + + (hasExists ? "true" : "null") + " for Attribute: " + attrName); + } + if (!expectsValue && hasValue) { + throw legacyExpectedValidationError( + "Value cannot be used when Exists is false for Attribute: " + attrName); + } + } + } + + private AwsException legacyExpectedValidationError(String detail) { + return new AwsException("ValidationException", + "1 validation error detected: One or more parameter values were invalid: " + detail, 400); + } + + /** + * Converts a legacy Expected condition from the {"Value": {...}} form to the + * {"AttributeValueList": [{...}]} form expected by matchesKeyCondition. + * Operators that already use AttributeValueList (IN, BETWEEN) pass through unchanged. + */ + private JsonNode normalizeLegacyCondition(JsonNode condition) { + if (!condition.has("Value") || condition.has("AttributeValueList")) { + return condition; + } + com.fasterxml.jackson.databind.node.ObjectNode normalized = objectMapper.createObjectNode(); + condition.fields().forEachRemaining(e -> { + if (!"Value".equals(e.getKey())) { + normalized.set(e.getKey(), e.getValue()); + } + }); + com.fasterxml.jackson.databind.node.ArrayNode avl = objectMapper.createArrayNode(); + avl.add(condition.get("Value")); + normalized.set("AttributeValueList", avl); + return normalized; + } + + private void addItemCollectionMetrics(ObjectNode response, JsonNode request, String tableName, + JsonNode itemOrKey, String region) { + String ricm = request.has("ReturnItemCollectionMetrics") + ? request.get("ReturnItemCollectionMetrics").asText() : null; + if (!"SIZE".equals(ricm) || itemOrKey == null) return; + try { + TableDefinition table = dynamoDbService.requireTableForItemCall(tableName, region); + String pkName = table.getPartitionKeyName(); + JsonNode pkValue = itemOrKey.get(pkName); + if (pkValue == null) return; + ObjectNode metrics = objectMapper.createObjectNode(); + ObjectNode collKey = objectMapper.createObjectNode(); + collKey.set(pkName, pkValue); + metrics.set("ItemCollectionKey", collKey); + ArrayNode sizeRange = objectMapper.createArrayNode(); + sizeRange.add(0.0); + sizeRange.add(1.0); + metrics.set("SizeEstimateRangeGB", sizeRange); + response.set("ItemCollectionMetrics", metrics); + } catch (Exception ignored) {} + } + + private static final int MAX_TOTAL_SEGMENTS = 1_000_000; + + // The AttributeValues inside a legacy container. AttributeUpdates, Expected, + // KeyConditions and QueryFilter carry them under Value or AttributeValueList. + private ObjectNode legacyValues(JsonNode container) { + var values = objectMapper.createObjectNode(); + if (container == null || !container.isObject()) { + return values; + } + var i = 0; + for (var spec : container) { + if (spec.has("Value")) { + values.set("v" + i++, spec.get("Value")); + } + for (var value : spec.path("AttributeValueList")) { + values.set("v" + i++, value); + } + } + return values; + } + + private static final Set VALID_SELECT = Set.of( + "ALL_ATTRIBUTES", "ALL_PROJECTED_ATTRIBUTES", "SPECIFIC_ATTRIBUTES", "COUNT"); + + private static final String SELECT_NEEDS_PROJECTION = + "Must specify the AttributesToGet or ProjectionExpression when choosing to get SPECIFIC_ATTRIBUTES"; + + private Response handleQuery(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + DynamoDbTableNames.resolve(tableName); // validate tableName first + JsonNode keyConditions = request.has("KeyConditions") ? request.get("KeyConditions") : null; + JsonNode exprAttrValues = request.has("ExpressionAttributeValues") + ? request.get("ExpressionAttributeValues") : null; + JsonNode exprAttrNames = request.has("ExpressionAttributeNames") + ? request.get("ExpressionAttributeNames") : null; + String keyConditionExpr = request.has("KeyConditionExpression") + ? request.get("KeyConditionExpression").asText() : null; + String filterExpr = request.has("FilterExpression") + ? request.get("FilterExpression").asText() : null; + JsonNode queryFilter = request.has("QueryFilter") ? request.get("QueryFilter") : null; + JsonNode attributesToGet = request.has("AttributesToGet") ? request.get("AttributesToGet") : null; + Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; + Boolean scanIndexForward = request.has("ScanIndexForward") + ? request.get("ScanIndexForward").asBoolean() : null; + String indexName = request.has("IndexName") ? request.get("IndexName").asText() : null; + JsonNode exclusiveStartKey = request.has("ExclusiveStartKey") + ? request.get("ExclusiveStartKey") : null; + String select = request.has("Select") ? request.get("Select").asText() : null; + String projectionExpression = request.has("ProjectionExpression") + ? request.get("ProjectionExpression").asText() : null; + + // Validate Limit + if (limit != null && limit < 1) { + throw new AwsException("ValidationException", + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1", 400); + } + + // Validate ReturnConsumedCapacity before Select + String rccQuery = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; + if (rccQuery != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccQuery)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + rccQuery + "' at 'returnConsumedCapacity' failed to satisfy constraint: " + + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); + } + + if (keyConditionExpr != null && keyConditions != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {KeyConditions} Expression parameters: {KeyConditionExpression}", 400); + } + if (keyConditionExpr != null && queryFilter != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {QueryFilter} Expression parameters: {KeyConditionExpression}", 400); + } + if (filterExpr != null && queryFilter != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {QueryFilter} Expression parameters: {FilterExpression}", 400); + } + if (attributesToGet != null && projectionExpression != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); + } + + if (keyConditionExpr == null && keyConditions == null) { + throw new AwsException("ValidationException", + "Either KeyConditions or KeyConditionExpression must be provided", 400); + } + + // Validate empty KCE + if (keyConditionExpr != null && keyConditionExpr.isEmpty()) { + throw new AwsException("ValidationException", + "Invalid KeyConditionExpression: The expression can not be empty;", 400); + } + + DynamoDbExpressionSize.checkRead(keyConditionExpr, "KeyConditionExpression"); + DynamoDbExpressionSize.checkRead(filterExpr, "FilterExpression"); + DynamoDbExpressionSize.checkRead(projectionExpression, "ProjectionExpression"); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); + DynamoDbNumberUtils.requireStorable(exprAttrValues, false); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(keyConditions), false); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(queryFilter), false); + ExpressionEvaluator.validateExpression(keyConditionExpr, "KeyConditionExpression", exprAttrNames, exprAttrValues); + ExpressionEvaluator.validateExpression(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues); + ProjectionEvaluator.validateExpression(projectionExpression, exprAttrNames); + + if (select != null && !VALID_SELECT.contains(select)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + select + "' at 'select' failed to satisfy constraint: " + + "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]", 400); + } + + boolean hasAttributesToGet = attributesToGet != null && attributesToGet.size() > 0; + if ("SPECIFIC_ATTRIBUTES".equals(select) && projectionExpression == null && !hasAttributesToGet) { + // Query prefixes the count here, Scan does not. + throw new AwsException("ValidationException", + "1 validation error detected: " + SELECT_NEEDS_PROJECTION, 400); + } + + TableDefinition queryTable = dynamoDbService.requireTableForItemCall(tableName, region); + DynamoDbAccessPath queryAccessPath = DynamoDbAccessPath.resolve(queryTable, indexName); + DynamoDbAccessPathValidator.validateQuery(queryTable, queryAccessPath, keyConditions, + keyConditionExpr, filterExpr, queryFilter, exprAttrNames, exprAttrValues); + DynamoDbAccessPathValidator.validateSelection(queryTable, queryAccessPath, select, + projectionExpression, attributesToGet, exprAttrNames); + rejectConsistentReadOnGsi(request, queryAccessPath); + + // Check undefined #tokens in FilterExpression + if (filterExpr != null) { + for (String token : extractHashTokens(filterExpr)) { + if (exprAttrNames == null || !exprAttrNames.has(token)) { + throw new AwsException("ValidationException", + "Invalid FilterExpression: An expression attribute name used in the document path is not defined; attribute name: " + token, 400); + } + } + } + // Reject ExpressionAttributeNames/Values entries not referenced by any expression + // (AWS parity, #2893). Unconditional: a legacy KeyConditions request that still + // carries EAN/EAV must be rejected, and either map can only be referenced from + // KeyConditionExpression, FilterExpression or (names only) ProjectionExpression. + Set hashTokens = extractHashTokens(keyConditionExpr, filterExpr, projectionExpression); + checkUnusedEan(exprAttrNames, hashTokens); + checkUnusedEav(exprAttrValues, extractColonTokens(keyConditionExpr, filterExpr)); + if (exclusiveStartKey != null) { + DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, queryTable, queryAccessPath, false); + } + + DynamoDbService.QueryResult result = dynamoDbService.query(tableName, keyConditions, + exprAttrValues, keyConditionExpr, filterExpr, limit, scanIndexForward, indexName, + exclusiveStartKey, exprAttrNames, region); + + List queryItems = result.items(); + // Apply QueryFilter (legacy API) + if (queryFilter != null) { + final JsonNode qf = queryFilter; + queryItems = queryItems.stream() + .filter(i -> dynamoDbService.matchesScanFilterPublic(i, qf)) + .toList(); + } + // Apply index projection (KEYS_ONLY / INCLUDE) when querying a secondary index + if (indexName != null && projectionExpression == null && attributesToGet == null) { + queryItems = applyIndexProjection(queryItems, queryTable, queryAccessPath, select); + } + if (projectionExpression != null) { + queryItems = queryItems.stream() + .map(i -> (JsonNode) ProjectionEvaluator.project(i, projectionExpression, exprAttrNames)) + .toList(); + } else if (attributesToGet != null) { + Set keep = new HashSet<>(); + attributesToGet.forEach(n -> keep.add(n.asText())); + queryItems = queryItems.stream() + .map(i -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) i, keep)) + .toList(); + } + + ObjectNode response = objectMapper.createObjectNode(); + if ("COUNT".equals(select)) { + response.put("Count", result.items().size()); + response.put("ScannedCount", result.scannedCount()); + } else { + ArrayNode itemsArray = objectMapper.createArrayNode(); + queryItems.forEach(itemsArray::add); + response.set("Items", itemsArray); + response.put("Count", queryItems.size()); + response.put("ScannedCount", result.scannedCount()); + } + if (result.lastEvaluatedKey() != null) { + response.set("LastEvaluatedKey", result.lastEvaluatedKey()); + } + addConsumedCapacity(response, request, tableName, + readCapacityUnits(result.scannedBytes(), request.path("ConsistentRead").asBoolean(false)), queryAccessPath); + return Response.ok(response).build(); + } + + private static void rejectConsistentReadOnGsi(JsonNode request, DynamoDbAccessPath accessPath) { + if (request.path("ConsistentRead").asBoolean(false) && accessPath.isGlobalSecondaryIndex()) { + throw new AwsException("ValidationException", + "Consistent reads are not supported on global secondary indexes", 400); + } + } + + private Response handleScan(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + String filterExpr = request.has("FilterExpression") + ? request.get("FilterExpression").asText() : null; + JsonNode exprAttrNames = request.has("ExpressionAttributeNames") + ? request.get("ExpressionAttributeNames") : null; + JsonNode exprAttrValues = request.has("ExpressionAttributeValues") + ? request.get("ExpressionAttributeValues") : null; + JsonNode scanFilter = request.has("ScanFilter") + ? request.get("ScanFilter") : null; + Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; + JsonNode exclusiveStartKey = request.has("ExclusiveStartKey") + ? request.get("ExclusiveStartKey") : null; + String select = request.has("Select") ? request.get("Select").asText() : null; + String indexNameScan = request.has("IndexName") ? request.get("IndexName").asText() : null; + String projectionExpressionScan = request.has("ProjectionExpression") + ? request.get("ProjectionExpression").asText() : null; + JsonNode attributesToGetScan = request.has("AttributesToGet") ? request.get("AttributesToGet") : null; + Integer segment = request.has("Segment") ? request.get("Segment").asInt() : null; + Integer totalSegments = request.has("TotalSegments") ? request.get("TotalSegments").asInt() : null; + + if (filterExpr != null && scanFilter != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}", 400); + } + + if (limit != null && limit < 1) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + limit + "' at 'limit' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1", 400); + } + + var segmentErrors = new ArrayList(); + if (totalSegments != null) { + if (totalSegments < 1) { + segmentErrors.add("Value '" + totalSegments + "' at 'totalSegments' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1"); + } + if (MAX_TOTAL_SEGMENTS < totalSegments) { + segmentErrors.add("Value '" + totalSegments + "' at 'totalSegments' failed to satisfy constraint: " + + "Member must have value less than or equal to " + MAX_TOTAL_SEGMENTS); + } + } + if (segment != null && segment < 0) { + segmentErrors.add("Value '" + segment + "' at 'segment' failed to satisfy constraint: " + + "Member must have value greater than or equal to 0"); + } + if (!segmentErrors.isEmpty()) { + var n = segmentErrors.size(); + throw new AwsException("ValidationException", + n + " validation error" + (n > 1 ? "s" : "") + " detected: " + + String.join("; ", segmentErrors), 400); + } + + if (segment != null && totalSegments == null) { + throw new AwsException("ValidationException", + "The TotalSegments parameter is required but was not present in the request when Segment parameter is present", 400); + } + if (totalSegments != null && segment == null) { + throw new AwsException("ValidationException", + "The Segment parameter is required but was not present in the request when parameter TotalSegments is present", 400); + } + if (segment != null && totalSegments != null && segment >= totalSegments) { + throw new AwsException("ValidationException", + "The Segment parameter is zero-based and must be less than parameter TotalSegments: " + + "Segment: " + segment + " is not less than TotalSegments: " + totalSegments, 400); + } + + DynamoDbExpressionSize.checkReadWithSize(filterExpr, "FilterExpression"); + DynamoDbExpressionSize.checkRead(projectionExpressionScan, "ProjectionExpression"); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); + DynamoDbNumberUtils.requireStorable(exprAttrValues, false); + ExpressionEvaluator.validateExpression(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues); + ProjectionEvaluator.validateExpression(projectionExpressionScan, exprAttrNames); + + // Reject ExpressionAttributeNames/Values entries not referenced by any expression (AWS parity, #2893) + checkUnusedEan(exprAttrNames, extractHashTokens(filterExpr, projectionExpressionScan)); + checkUnusedEav(exprAttrValues, extractColonTokens(filterExpr)); + + if (select != null && !VALID_SELECT.contains(select)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + select + "' at 'select' failed to satisfy constraint: " + + "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]", 400); + } + if (projectionExpressionScan != null && attributesToGetScan != null) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); + } + boolean hasAttributesToGetScan = attributesToGetScan != null && attributesToGetScan.size() > 0; + if ("SPECIFIC_ATTRIBUTES".equals(select) + && projectionExpressionScan == null && !hasAttributesToGetScan) { + throw new AwsException("ValidationException", SELECT_NEEDS_PROJECTION, 400); + } + + TableDefinition scanTable = dynamoDbService.requireTableForItemCall(tableName, region); + DynamoDbAccessPath scanAccessPath = DynamoDbAccessPath.resolve(scanTable, indexNameScan); + DynamoDbAccessPathValidator.validateSelection(scanTable, scanAccessPath, select, + projectionExpressionScan, attributesToGetScan, exprAttrNames); + rejectConsistentReadOnGsi(request, scanAccessPath); + + if (exclusiveStartKey != null) { + DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, scanTable, scanAccessPath, true); + } + + DynamoDbService.ScanResult result = dynamoDbService.scan( + tableName, filterExpr, exprAttrNames, exprAttrValues, scanFilter, limit, + exclusiveStartKey, indexNameScan, segment, totalSegments, region); + + List scanItems = result.items(); + // Apply index projection (KEYS_ONLY / INCLUDE) when scanning a secondary index + if (indexNameScan != null && projectionExpressionScan == null && attributesToGetScan == null) { + scanItems = applyIndexProjection(scanItems, scanTable, scanAccessPath, select); + } + if (projectionExpressionScan != null) { + scanItems = scanItems.stream() + .map(i -> (JsonNode) ProjectionEvaluator.project(i, projectionExpressionScan, exprAttrNames)) + .toList(); + } else if (attributesToGetScan != null) { + Set keep = new HashSet<>(); + attributesToGetScan.forEach(n -> keep.add(n.asText())); + scanItems = scanItems.stream() + .map(i -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) i, keep)) + .toList(); + } + + ObjectNode response = objectMapper.createObjectNode(); + if ("COUNT".equals(select)) { + response.put("Count", result.items().size()); + response.put("ScannedCount", result.scannedCount()); + } else { + ArrayNode itemsArray = objectMapper.createArrayNode(); + scanItems.forEach(itemsArray::add); + response.set("Items", itemsArray); + response.put("Count", scanItems.size()); + response.put("ScannedCount", result.scannedCount()); + } + if (result.lastEvaluatedKey() != null) { + response.set("LastEvaluatedKey", result.lastEvaluatedKey()); + } + addConsumedCapacity(response, request, tableName, + readCapacityUnits(result.scannedBytes(), request.path("ConsistentRead").asBoolean(false)), scanAccessPath); + return Response.ok(response).build(); + } + + // The floor AWS reports for a small search. The real figure is non-deterministic there, + // so every search reports the floor (measured in eu-west-2, 2026-09-23). + private static final double VECTOR_SEARCH_REQUEST_BYTES = 1024; + + private static final int MAX_VECTOR_SEARCH_TOP_K = 100; + + private Response handleSearchVectors(JsonNode request, String region) { + requireSearchVectorsMember(request, "SearchVector"); + requireSearchVectorsMember(request, "IndexName"); + String tableName = request.path("TableName").asText(); + String indexName = request.get("IndexName").asText(); + String rccSearch = request.has("ReturnConsumedCapacity") + ? request.get("ReturnConsumedCapacity").asText() : null; + if (rccSearch != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccSearch)) { + // No "N validation errors detected" envelope here, unlike every other operation. + throw new AwsException("ValidationException", + "Value '" + rccSearch + "' at 'returnConsumedCapacity' " + + "failed to satisfy constraint: Member must satisfy enum value set: " + + "[INDEXES, TOTAL, NONE]", 400); + } + requireSearchVectorsMember(request, "TopK"); + int topK = request.get("TopK").asInt(); + if (topK < 1) { + // AWS names this member TopK and quotes no value, unlike every other member of this + // family. Measured on real DynamoDB, eu-west-2, 2026-09-23. + throw new AwsException("ValidationException", + "1 validation error detected: Value at 'TopK' failed to satisfy " + + "constraint: Member must have value greater than or equal to 1", 400); + } + // Both bounds answer before the table and the index are resolved: AWS reports the range + // even for a table that does not exist. + if (topK > MAX_VECTOR_SEARCH_TOP_K) { + throw new AwsException("ValidationException", + "Provided TopK value '" + topK + "' is out of valid range. " + + "The value must be between 1 and " + MAX_VECTOR_SEARCH_TOP_K + " inclusive", 400); + } + + TableDefinition table = dynamoDbService.settledTable(tableName, region); + VectorIndex index = requireSearchableVectorIndex(table, indexName); + + JsonNode exprAttrNames = request.has("ExpressionAttributeNames") + ? request.get("ExpressionAttributeNames") : null; + JsonNode exprAttrValues = request.has("ExpressionAttributeValues") + ? request.get("ExpressionAttributeValues") : null; + List hits = DynamoDbVectorSearch.search(table, index, + dynamoDbService.liveItems(table, region), + request.path("SearchVector"), topK, + request.has("SearchConditionExpression") + ? request.get("SearchConditionExpression").asText() : null, + exprAttrNames, exprAttrValues, + request.has("ProjectionExpression") ? request.get("ProjectionExpression").asText() : null); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode searchResults = objectMapper.createArrayNode(); + for (DynamoDbVectorSearch.Hit hit : hits) { + ObjectNode searchResult = objectMapper.createObjectNode(); + searchResult.set("Item", hit.item()); + searchResult.put("Score", hit.score()); + searchResults.add(searchResult); + } + response.set("SearchResults", searchResults); + if (rccSearch != null && !"NONE".equals(rccSearch)) { + ObjectNode consumedCapacity = objectMapper.createObjectNode(); + consumedCapacity.put("VectorSearchRequestBytes", VECTOR_SEARCH_REQUEST_BYTES); + response.set("ConsumedCapacity", consumedCapacity); + } + return Response.ok(response).build(); + } + + /** + * Rejects an omitted required member of SearchVectors the way the AWS frontend does: as a + * deserialisation failure quoting the offset of the body's closing brace, which for the + * compact JSON an SDK sends is the body length. Measured in eu-west-2, 2026-09-23. + */ + private static void requireSearchVectorsMember(JsonNode request, String member) { + if (!request.hasNonNull(member)) { + throw new AwsException("ValidationException", + "missing field `" + member + "` at line 1 column " + + request.toString().length(), 400); + } + } + + /** + * The vector index a search may run against. + * + *

An index still in its resource allocation phase answers as if the table did not have it, + * which is the wording AWS uses there and what the documented readiness wait retries on. + */ + private VectorIndex requireSearchableVectorIndex(TableDefinition table, String indexName) { + VectorIndex index = table.findVectorIndex(indexName).orElse(null); + if (index == null) { + throw new AwsException("ValidationException", + "The table does not have the specified index: " + indexName, 400); + } + if ("CREATING".equals(index.getIndexStatus())) { + if (!dynamoDbService.isVectorIndexBackfilling(index)) { + throw new AwsException("ValidationException", + "The table does not have the specified index: " + indexName, 400); + } + throw new AwsException("ValidationException", + "Cannot search backfilling vector index: " + indexName, 400); + } + return index; + } + + private Response handleBatchWriteItem(JsonNode request, String region) { + JsonNode requestItems = request.get("RequestItems"); + if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode() + || !requestItems.fields().hasNext()) { + throw new AwsException("ValidationException", + "The requestItems parameter is required for BatchWriteItem", 400); + } + Map> items = new HashMap<>(); + Iterator> tables = requestItems.fields(); + while (tables.hasNext()) { + var entry = tables.next(); + List writes = new ArrayList<>(); + for (JsonNode writeReq : entry.getValue()) { + DynamoDbAttributeValueValidator.requireNestingWithinLimit( + writeReq.path("PutRequest").get("Item"), false); + writes.add(writeReq); + } + items.put(entry.getKey(), writes); + } + + // Per-table check: max 25 write requests + for (Map.Entry> entry : items.entrySet()) { + if (entry.getValue().size() > 25) { + // Build a representation of the requestItems + StringBuilder sb = new StringBuilder("{"); + sb.append(entry.getKey()).append("=["); + List reprs = new ArrayList<>(); + for (JsonNode w : entry.getValue()) { + reprs.add(w.toString()); + } + sb.append(String.join(", ", reprs)).append("]}"); + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + sb + "' at 'requestItems' failed to satisfy constraint: " + + "Map value must satisfy constraint: [Member must have length less than or equal to 25, " + + "Member must have length greater than or equal to 1]", 400); + } + } + + for (Map.Entry> entry : items.entrySet()) { + TableDefinition bwTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); + Set seen = new HashSet<>(); + for (JsonNode writeReq : entry.getValue()) { + JsonNode keyNode = writeReq.has("PutRequest") + ? writeReq.get("PutRequest").get("Item") + : writeReq.get("DeleteRequest").get("Key"); + String key = dynamoDbService.buildItemKey(bwTable, keyNode, + DynamoDbService.KeySurface.BATCH_WRITE); + if (!seen.add(key)) { + throw new AwsException("ValidationException", + "Provided list of item keys contains duplicates", 400); + } + } + } + + // The per-table write cost needs the stored images from before the batch runs. + var returnCCBatch = request.path("ReturnConsumedCapacity").asText("NONE"); + if (!VALID_RETURN_CONSUMED_CAPACITY.contains(returnCCBatch)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + returnCCBatch + + "' at 'returnConsumedCapacity' failed to satisfy constraint: " + + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]", 400); + } + Map costs = null; + if (!"NONE".equals(returnCCBatch)) { + costs = new LinkedHashMap<>(); + for (var entry : items.entrySet()) { + TableDefinition costTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); + var cost = DynamoDbWriteCapacity.Cost.zero(); + for (var writeReq : entry.getValue()) { + var newItem = writeReq.has("PutRequest") + ? DynamoDbNumberUtils.normalizeNumbersInItem(writeReq.get("PutRequest").get("Item")) + : null; + var keyNode = writeReq.has("PutRequest") + ? writeReq.get("PutRequest").get("Item") + : writeReq.get("DeleteRequest").get("Key"); + var previous = dynamoDbService.getItem(entry.getKey(), keyNode, region); + cost = cost.plus(DynamoDbWriteCapacity.forWrite(costTable, previous, newItem)); + } + costs.put(entry.getKey(), cost); + } + } + + dynamoDbService.batchWriteItem(items, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("UnprocessedItems", objectMapper.createObjectNode()); + if (costs != null) { + var ccArray = objectMapper.createArrayNode(); + for (var entry : costs.entrySet()) { + ccArray.add(writeCapacityNode(entry.getKey(), entry.getValue(), + "INDEXES".equals(returnCCBatch))); + } + response.set("ConsumedCapacity", ccArray); + } + return Response.ok(response).build(); + } + + private Response handleBatchGetItem(JsonNode request, String region) { + JsonNode requestItems = request.get("RequestItems"); + if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()) { + throw new AwsException("ValidationException", + "The requestItems parameter is required for BatchGetItem", 400); + } + // BatchGetItem answers an empty map from the validation framework, BatchWriteItem + // still answers with its own sentence. + if (!requestItems.fields().hasNext()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value at 'RequestItems' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1", 400); + } + Map items = new HashMap<>(); + Iterator> tables = requestItems.fields(); + while (tables.hasNext()) { + var entry = tables.next(); + items.put(entry.getKey(), entry.getValue()); + } + + // AWS weighs the two projection styles across the whole request, so one table + // entry naming AttributesToGet and another naming ProjectionExpression conflict. + boolean usesAttributesToGet = false; + boolean usesProjectionExpression = false; + for (JsonNode tableRequest : items.values()) { + usesAttributesToGet |= tableRequest.hasNonNull("AttributesToGet"); + usesProjectionExpression |= tableRequest.hasNonNull("ProjectionExpression"); + } + if (usesAttributesToGet && usesProjectionExpression) { + throw new AwsException("ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); + } + + // Per-table check: max 100 keys + for (Map.Entry entry : items.entrySet()) { + var projection = entry.getValue().path("ProjectionExpression"); + if (projection.isTextual()) { + DynamoDbExpressionSize.checkRead(projection.asText(), "ProjectionExpression"); + ProjectionEvaluator.validateExpression(projection.asText(), + entry.getValue().get("ExpressionAttributeNames")); + } + JsonNode keysNode = entry.getValue().has("Keys") ? entry.getValue().get("Keys") : null; + if (keysNode != null && keysNode.size() > 100) { + throw new AwsException("ValidationException", + "1 validation error detected: Value at 'RequestItems." + entry.getKey() + + ".member.Keys' failed to satisfy constraint: " + + "Member must have length less than or equal to 100", 400); + } + } + + for (Map.Entry entry : items.entrySet()) { + TableDefinition bgTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); + JsonNode keys = entry.getValue().get("Keys"); + if (keys == null || !keys.isArray()) continue; + Set seen = new HashSet<>(); + for (JsonNode key : keys) { + String itemKey = dynamoDbService.buildItemKey(bgTable, key); + if (!seen.add(itemKey)) { + throw new AwsException("ValidationException", + "Provided list of item keys contains duplicates", 400); + } + } + } + + DynamoDbService.BatchGetResult result = dynamoDbService.batchGetItem(items, region); + + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode responses = objectMapper.createObjectNode(); + for (Map.Entry> entry : result.responses().entrySet()) { + String tblName = entry.getKey(); + JsonNode tableRequest = requestItems.get(tblName); + String projExpr = tableRequest != null && tableRequest.has("ProjectionExpression") + ? tableRequest.get("ProjectionExpression").asText() : null; + JsonNode exprNames = tableRequest != null && tableRequest.has("ExpressionAttributeNames") + ? tableRequest.get("ExpressionAttributeNames") : null; + JsonNode attrToGet = tableRequest != null && tableRequest.has("AttributesToGet") + ? tableRequest.get("AttributesToGet") : null; + ArrayNode tableItems = objectMapper.createArrayNode(); + for (JsonNode item : entry.getValue()) { + JsonNode projected; + if (projExpr != null) { + projected = ProjectionEvaluator.project(item, projExpr, exprNames); + } else if (attrToGet != null) { + Set keep = new HashSet<>(); + attrToGet.forEach(n -> keep.add(n.asText())); + projected = ProjectionEvaluator.trimToAttributes((ObjectNode) item, keep); + } else { + projected = item; + } + tableItems.add(projected); + } + responses.set(tblName, tableItems); + } + response.set("Responses", responses); + response.set("UnprocessedKeys", objectMapper.createObjectNode()); + addBatchConsumedCapacity(response, request, items, false); + return Response.ok(response).build(); + } + + private Response handleUpdateTable(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + JsonNode replicaUpdates = request.path("ReplicaUpdates"); + List addRegions = new ArrayList<>(); + List removeRegions = new ArrayList<>(); + List updateRegions = new ArrayList<>(); + if (replicaUpdates.isArray()) { + for (JsonNode update : replicaUpdates) { + JsonNode create = update.path("Create"); + if (create.isObject()) { + String replicaRegion = create.path("RegionName").asText(null); + validateReplicaRegion(replicaRegion); + addRegions.add(replicaRegion); + } + JsonNode delete = update.path("Delete"); + if (delete.isObject()) { + String replicaRegion = delete.path("RegionName").asText(null); + validateReplicaRegion(replicaRegion); + removeRegions.add(replicaRegion); + } + JsonNode updateNode = update.path("Update"); + if (updateNode.isObject()) { + String replicaRegion = updateNode.path("RegionName").asText(null); + validateReplicaRegion(replicaRegion); + updateRegions.add(replicaRegion); + } + } + } + JsonNode pt = request.path("ProvisionedThroughput"); + Throughput throughput = null; + if (!pt.isMissingNode()) { + throughput = parseThroughput(pt); + } + + String billingModeCheck = request.has("BillingMode") ? request.get("BillingMode").asText() : null; + if ("PAY_PER_REQUEST".equals(billingModeCheck) && !pt.isMissingNode()) { + throw new AwsException("ValidationException", + "ProvisionedThroughput cannot be specified when BillingMode is PAY_PER_REQUEST", 400); + } + + List gsiCreates = new ArrayList<>(); + List gsiDeletes = new ArrayList<>(); + List gsiThroughputUpdates = new ArrayList<>(); + JsonNode gsiUpdates = request.path("GlobalSecondaryIndexUpdates"); + if (!gsiUpdates.isMissingNode() && gsiUpdates.isArray()) { + var updatePosition = 0; + for (JsonNode update : gsiUpdates) { + updatePosition++; + JsonNode createNode = update.path("Create"); + if (!createNode.isMissingNode()) { + String indexName = createNode.path("IndexName").asText(); + List gsiKeySchema = new ArrayList<>(); + createNode.path("KeySchema").forEach(ks -> + gsiKeySchema.add(new KeySchemaElement( + ks.path("AttributeName").asText(), + ks.path("KeyType").asText()))); + String projectionType = createNode.path("Projection").path("ProjectionType").asText("ALL"); + JsonNode nonKeyAttrArray = createNode.path("Projection").path("NonKeyAttributes"); + List nonKeyAttributes = new ArrayList<>(); + if (!nonKeyAttrArray.isMissingNode() && nonKeyAttrArray.isArray()){ + for (JsonNode nonKeyAttr : nonKeyAttrArray){ + nonKeyAttributes.add(nonKeyAttr.asText()); + } + } + rejectEmptyNonKeyAttributes(nonKeyAttrArray, + "globalSecondaryIndexUpdates." + updatePosition + ".member.create"); + validateProjectionSpec(projectionType, nonKeyAttributes); + GlobalSecondaryIndex newGsi = new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes); + JsonNode newGsiPt = createNode.path("ProvisionedThroughput"); + if (!newGsiPt.isMissingNode()) { + newGsi.getProvisionedThroughput().setReadCapacityUnits(newGsiPt.path("ReadCapacityUnits").asLong(0)); + newGsi.getProvisionedThroughput().setWriteCapacityUnits(newGsiPt.path("WriteCapacityUnits").asLong(0)); + } + JsonNode newGsiOnDemand = createNode.path("OnDemandThroughput"); + if (newGsiOnDemand.isObject()) { + if (newGsiOnDemand.has("MaxReadRequestUnits")) { + newGsi.setOnDemandMaxReadRequestUnits(newGsiOnDemand.get("MaxReadRequestUnits").asInt()); + } + if (newGsiOnDemand.has("MaxWriteRequestUnits")) { + newGsi.setOnDemandMaxWriteRequestUnits(newGsiOnDemand.get("MaxWriteRequestUnits").asInt()); + } + } + gsiCreates.add(newGsi); + } + JsonNode deleteNode = update.path("Delete"); + if (!deleteNode.isMissingNode()) { + gsiDeletes.add(deleteNode.path("IndexName").asText()); + } + JsonNode updateNode = update.path("Update"); + if (updateNode.isObject()) { + JsonNode gsiPt = updateNode.path("ProvisionedThroughput"); + gsiThroughputUpdates.add(new GsiThroughputUpdate( + updateNode.path("IndexName").asText(), + gsiPt.isObject() ? parseThroughput(gsiPt) : null, + parseOnDemandThroughput(updateNode.path("OnDemandThroughput")))); + } + } + } + + if (!gsiThroughputUpdates.isEmpty()) { + TableDefinition currentTable = dynamoDbService.describeTable(tableName, region); + for (GsiThroughputUpdate gsiUpdate : gsiThroughputUpdates) { + String indexName = gsiUpdate.indexName(); + if (gsiDeletes.contains(indexName)) { + throw new AwsException("ValidationException", + "Cannot delete and update the same index: " + indexName, 400); + } + if (currentTable.findGsi(indexName).isEmpty()) { + throw new AwsException("ValidationException", + "The table does not have the specified index: " + indexName, 400); + } + } + } + + List vectorCreates = new ArrayList<>(); + List vectorDeletes = new ArrayList<>(); + JsonNode vectorIndexUpdates = request.path("VectorIndexUpdates"); + if (vectorIndexUpdates.isArray()) { + // AWS reports a per-member constraint under the position in this array, which a + // create shares with the deletes beside it. + int updatePosition = 0; + for (JsonNode update : vectorIndexUpdates) { + updatePosition++; + JsonNode createNode = update.path("Create"); + if (createNode.isObject()) { + String memberPath = "vectorIndexUpdates." + updatePosition + ".member.create"; + vectorCreates.add(new DynamoDbService.VectorIndexCreate( + parseVectorIndex(createNode, memberPath), memberPath)); + } + JsonNode deleteNode = update.path("Delete"); + if (deleteNode.isObject()) { + vectorDeletes.add(deleteNode.path("IndexName").asText(null)); + } + } + } + + List newAttrDefs = new ArrayList<>(); + JsonNode attrDefsNode = request.path("AttributeDefinitions"); + if (!attrDefsNode.isMissingNode() && attrDefsNode.isArray()) { + for (JsonNode ad : attrDefsNode) { + newAttrDefs.add(new AttributeDefinition( + ad.path("AttributeName").asText(), + ad.path("AttributeType").asText())); + } + } + + TableDefinition table = tableService.updateTable(new UpdateTableRequest(tableName, + throughput, newAttrDefs, gsiCreates, gsiDeletes, gsiThroughputUpdates, vectorCreates, vectorDeletes, + addRegions, removeRegions, updateRegions, parseTableSettings(request)), region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("TableDescription", tableToNode(table)); + return Response.ok(response).build(); + } + + private static Throughput parseThroughput(JsonNode pt) { + Long readCapacity = pt.has("ReadCapacityUnits") ? pt.get("ReadCapacityUnits").asLong() : null; + Long writeCapacity = pt.has("WriteCapacityUnits") ? pt.get("WriteCapacityUnits").asLong() : null; + return new Throughput(readCapacity, writeCapacity); + } + + private static void validateReplicaRegion(String replicaRegion) { + if (replicaRegion == null || replicaRegion.isBlank()) { + throw new AwsException("ValidationException", "Replica RegionName must not be empty", 400); + } + } + + private Response handleDescribeTimeToLive(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + TableDefinition table = dynamoDbService.describeTable(tableName, region); + + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode ttlDesc = objectMapper.createObjectNode(); + if (table.isTtlEnabled() && table.getTtlAttributeName() != null) { + ttlDesc.put("TimeToLiveStatus", "ENABLED"); + ttlDesc.put("AttributeName", table.getTtlAttributeName()); + } else { + ttlDesc.put("TimeToLiveStatus", "DISABLED"); + } + response.set("TimeToLiveDescription", ttlDesc); + return Response.ok(response).build(); + } + + private Response handleUpdateTimeToLive(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + JsonNode spec = request.path("TimeToLiveSpecification"); + String ttlAttributeName = spec.path("AttributeName").asText(); + if (ttlAttributeName == null || ttlAttributeName.isBlank()) { + throw new AwsException("ValidationException", + "TimeToLiveSpecification.AttributeName must not be empty", 400); + } + boolean enabled = spec.path("Enabled").asBoolean(false); + + dynamoDbService.updateTimeToLive(tableName, ttlAttributeName, enabled, region); + + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode ttlSpec = objectMapper.createObjectNode(); + ttlSpec.put("AttributeName", ttlAttributeName); + ttlSpec.put("Enabled", enabled); + response.set("TimeToLiveSpecification", ttlSpec); + return Response.ok(response).build(); + } + + private Response handleDescribeContinuousBackups(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + TableDefinition table = dynamoDbService.describeTable(tableName, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(table)); + return Response.ok(response).build(); + } + + private Response handleUpdateContinuousBackups(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + JsonNode spec = request.path("PointInTimeRecoverySpecification"); + boolean enabled = spec.path("PointInTimeRecoveryEnabled").asBoolean(false); + Integer recoveryPeriodInDays = spec.has("RecoveryPeriodInDays") + ? spec.path("RecoveryPeriodInDays").asInt() + : null; + if (recoveryPeriodInDays != null && (recoveryPeriodInDays < 1 || recoveryPeriodInDays > 35)) { + throw new AwsException("ValidationException", + "RecoveryPeriodInDays must be between 1 and 35", 400); + } + + TableDefinition table = dynamoDbService.updateContinuousBackups( + tableName, enabled, recoveryPeriodInDays, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(table)); + return Response.ok(response).build(); + } + + private Response handleTransactWriteItems(JsonNode request, String region) { + JsonNode transactItemsNode = requireValidTransactRequest(request); + + for (JsonNode txItem : transactItemsNode) { + for (JsonNode op : txItem) { + String conditionExpression = op.has("ConditionExpression") + ? op.get("ConditionExpression").asText() : null; + DynamoDbExpressionSize.checkRead(op.path("UpdateExpression").textValue(), "UpdateExpression"); + DynamoDbExpressionSize.checkReadWithSize(conditionExpression, "ConditionExpression"); + ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", + op.get("ExpressionAttributeNames"), + op.get("ExpressionAttributeValues")); + DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Item"), false); + dynamoDbService.requireAddOrDeleteOperandTypes(op.path("UpdateExpression").textValue(), + op.get("ExpressionAttributeValues"), false); + } + } + + // Check 4MB total item size limit + final int MAX_TRANSACTION_BYTES = 4 * 1024 * 1024; + int totalSize = 0; + for (JsonNode txItem : transactItemsNode) { + JsonNode item = txItem.has("Put") ? txItem.get("Put").get("Item") + : txItem.has("Update") ? txItem.get("Update").get("Key") + : txItem.has("Delete") ? txItem.get("Delete").get("Key") + : txItem.has("ConditionCheck") ? txItem.get("ConditionCheck").get("Key") + : null; + if (item != null) totalSize += DynamoDbItemSize.calculateItemSize(item); + } + if (totalSize > MAX_TRANSACTION_BYTES) { + throw new AwsException("ValidationException", + "Transaction failed: The total size of all items in the transaction request cannot exceed 4 MB", 400); + } + + List transactItems = new ArrayList<>(); + transactItemsNode.forEach(transactItems::add); + try { + dynamoDbService.cancelOnKeySchemaMismatch(transactItems, region); + } catch (TransactionCanceledException e) { + return transactWriteCanceled(e); + } + + Map tableCache = new HashMap<>(); + Set seen = new HashSet<>(); + for (JsonNode txItem : transactItemsNode) { + JsonNode op = txItem.has("Put") ? txItem.get("Put") + : txItem.has("Delete") ? txItem.get("Delete") + : txItem.has("Update") ? txItem.get("Update") + : txItem.has("ConditionCheck") ? txItem.get("ConditionCheck") : null; + if (op == null) continue; + String opTable = op.path("TableName").asText(); + TableDefinition txTable = tableCache.computeIfAbsent(opTable, + tn -> dynamoDbService.requireTableForItemCall(tn, region)); + JsonNode keyNode = op.has("Item") ? op.get("Item") : op.get("Key"); + if (keyNode == null) continue; + String key = region + "::" + opTable + "::" + dynamoDbService.buildItemKey(txTable, keyNode); + if (!seen.add(key)) { + throw new AwsException("ValidationException", + "Transaction request cannot include multiple operations on one item", 400); + } + } + + // ClientRequestToken makes TransactWriteItems idempotent within ~10 minutes. + // Forward the token and the raw request body so the service can hash the body + // and reject replays whose parameters changed. + String clientRequestToken = request.has("ClientRequestToken") && !request.get("ClientRequestToken").isNull() + ? request.get("ClientRequestToken").asText() + : null; + + try { + DynamoDbService.TransactWriteResult result = + dynamoDbService.transactWriteItems(transactItems, region, clientRequestToken, request); + ObjectNode response = objectMapper.createObjectNode(); + addTransactWriteConsumedCapacity(response, request, result); + return Response.ok(response).build(); + } catch (TransactionCanceledException e) { + return transactWriteCanceled(e); + } + } + + private static JsonNode requireValidTransactRequest(JsonNode request) { + JsonNode transactItems = request.path("TransactItems"); + List validationErrors = new ArrayList<>(); + if (transactItems.isMissingNode() || transactItems.isNull() || !transactItems.isArray()) { + validationErrors.add("Value null at 'transactItems' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1"); + } else if (transactItems.isEmpty()) { + validationErrors.add("Value '[]' at 'transactItems' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1"); + } else if (transactItems.size() > 100) { + validationErrors.add("Value '" + transactItems + "' at 'transactItems' failed to satisfy constraint: " + + "Member must have length less than or equal to 100"); + } + addReturnConsumedCapacityError(request, validationErrors); + throwValidationErrors(validationErrors); + return transactItems; + } + + private static void addReturnConsumedCapacityError(JsonNode request, List validationErrors) { + String returnCC = request.has("ReturnConsumedCapacity") ? request.get("ReturnConsumedCapacity").asText() : null; + if (returnCC != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(returnCC)) { + validationErrors.add("Value '" + returnCC + "' at 'returnConsumedCapacity' failed to satisfy constraint: " + + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"); + } + } + + private static void requireValidReturnConsumedCapacity(JsonNode request) { + List validationErrors = new ArrayList<>(); + addReturnConsumedCapacityError(request, validationErrors); + throwValidationErrors(validationErrors); + } + + private static void throwValidationErrors(List validationErrors) { + if (validationErrors.isEmpty()) { + return; + } + int n = validationErrors.size(); + throw new AwsException("ValidationException", + n + " validation error" + (n > 1 ? "s" : "") + " detected: " + + String.join("; ", validationErrors), 400); + } + + private Response transactWriteCanceled(TransactionCanceledException e) { + ObjectNode body = objectMapper.createObjectNode(); + body.put("__type", "TransactionCanceledException"); + body.put("message", e.getMessage()); + ArrayNode reasons = body.putArray("CancellationReasons"); + for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) { + ObjectNode r = objectMapper.createObjectNode(); + r.put("Code", reason.code().isEmpty() ? "None" : reason.code()); + if (!reason.code().isEmpty()) { + r.put("Message", reason.message() != null ? reason.message() : "The conditional request failed"); + } + if (reason.item() != null) { + r.set("Item", reason.item()); + } + reasons.add(r); + } + return Response.status(400).entity(body).build(); + } + + private Response handleTransactGetItems(JsonNode request, String region) { + JsonNode transactItemsNode = requireValidTransactRequest(request); + + for (JsonNode txItem : transactItemsNode) { + DynamoDbExpressionSize.checkRead(txItem.path("Get").path("ProjectionExpression").textValue(), + "ProjectionExpression"); + } + + Map tableCache = new HashMap<>(); + Set seenGet = new HashSet<>(); + for (JsonNode txItem : transactItemsNode) { + JsonNode get = txItem.has("Get") ? txItem.get("Get") : null; + if (get == null) continue; + String opTable = get.path("TableName").asText(); + TableDefinition txTable = tableCache.computeIfAbsent(opTable, + tn -> dynamoDbService.requireTableForItemCall(tn, region)); + JsonNode keyNode = get.get("Key"); + if (keyNode == null) continue; + try { + String key = region + "::" + opTable + "::" + dynamoDbService.buildItemKey(txTable, keyNode); + if (!seenGet.add(key)) { + throw new AwsException("ValidationException", + "Transaction request cannot include multiple operations on one item", 400); + } + } catch (AwsException e) { + if ("Transaction request cannot include multiple operations on one item".equals(e.getMessage())) { + throw e; + } + // Per-action validation error - will be surfaced via TransactionCanceledException in transactGetItems + } + } + + // Validate the ProjectionExpression in each Get action before executing + for (JsonNode txItem : transactItemsNode) { + JsonNode get = txItem.has("Get") ? txItem.get("Get") : null; + if (get == null) continue; + String pe = get.has("ProjectionExpression") ? get.get("ProjectionExpression").asText() : null; + if (pe != null) { + ProjectionEvaluator.validateExpression(pe, get.get("ExpressionAttributeNames")); + } + } + + List transactItems = new ArrayList<>(); + transactItemsNode.forEach(transactItems::add); + + DynamoDbService.TransactGetResult result; + try { + result = dynamoDbService.transactGetItems(transactItems, region); + } catch (TransactionCanceledException e) { + ObjectNode body = objectMapper.createObjectNode(); + body.put("__type", "TransactionCanceledException"); + body.put("message", e.getMessage()); + ArrayNode reasons = body.putArray("CancellationReasons"); + for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) { + ObjectNode r = objectMapper.createObjectNode(); + r.put("Code", reason.code().isEmpty() ? "None" : reason.code()); + if (!reason.code().isEmpty()) { + r.put("Message", ""); + } + if (reason.item() != null) { + r.set("Item", reason.item()); + } + reasons.add(r); + } + return Response.status(400).entity(body).build(); + } + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode responsesArray = objectMapper.createArrayNode(); + for (JsonNode item : result.items()) { + ObjectNode entry = objectMapper.createObjectNode(); + if (item != null) { + entry.set("Item", item); + } + responsesArray.add(entry); + } + response.set("Responses", responsesArray); + addPerTableConsumedCapacity(response, request, result.capacity(), "ReadCapacityUnits"); + return Response.ok(response).build(); + } + + /** + * Botocore gives DynamoDB's {@code ResourceArnString} no pattern at all, only a length range, + * so this shape is the emulator's own. Widening the partition keeps it from rejecting a legal + * GovCloud or China table ARN. + */ + private static final java.util.regex.Pattern DYNAMODB_TABLE_ARN_PATTERN = + java.util.regex.Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + + ":dynamodb:[a-z0-9-]+:\\d{12}:table/[a-zA-Z0-9._-]+$"); + + private static boolean isValidDynamoDbTableArn(String arn) { + return arn != null && DYNAMODB_TABLE_ARN_PATTERN.matcher(arn).matches(); + } + + private Response handleTagResource(JsonNode request, String region) { + String resourceArn = request.path("ResourceArn").asText(); + if (!isValidDynamoDbTableArn(resourceArn)) { + throw new AwsException("ValidationException", + "Invalid ResourceArn: " + resourceArn, 400); + } + Map tags = new HashMap<>(); + JsonNode tagsNode = request.path("Tags"); + if (tagsNode.isArray()) { + for (JsonNode tag : tagsNode) { + tags.put(tag.path("Key").asText(), tag.path("Value").asText()); + } + } + dynamoDbService.tagResource(resourceArn, tags, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleUntagResource(JsonNode request, String region) { + String resourceArn = request.path("ResourceArn").asText(); + List tagKeys = new ArrayList<>(); + JsonNode keysNode = request.path("TagKeys"); + if (keysNode.isArray()) { + for (JsonNode key : keysNode) { + tagKeys.add(key.asText()); + } + } + dynamoDbService.untagResource(resourceArn, tagKeys, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListTagsOfResource(JsonNode request, String region) { + String resourceArn = request.path("ResourceArn").asText(); + Map tags; + try { + tags = dynamoDbService.listTagsOfResource(resourceArn, region); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + throw new AwsException("AccessDeniedException", + "User is not authorized to perform: dynamodb:ListTagsOfResource on resource: " + + resourceArn, 400); + } + throw e; + } + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode tagsArray = objectMapper.createArrayNode(); + for (Map.Entry entry : tags.entrySet()) { + ObjectNode tagNode = objectMapper.createObjectNode(); + tagNode.put("Key", entry.getKey()); + tagNode.put("Value", entry.getValue()); + tagsArray.add(tagNode); + } + response.set("Tags", tagsArray); + return Response.ok(response).build(); + } + + private Response handlePutResourcePolicy(JsonNode request, String region) { + String resourceArn = request.path("ResourceArn").asText(); + if (!isValidDynamoDbTableArn(resourceArn)) { + throw new AwsException("ValidationException", + "Invalid ResourceArn: " + resourceArn, 400); + } + if (!request.hasNonNull("Policy")) { + throw new AwsException("ValidationException", + "1 validation error detected: Value null at 'policy' failed to satisfy constraint: " + + "Member must not be null", 400); + } + String policy = request.path("Policy").asText(); + String expectedRevisionId = request.has("ExpectedRevisionId") + ? request.get("ExpectedRevisionId").asText() : null; + + String revisionId = dynamoDbService.putResourcePolicy(resourceArn, policy, expectedRevisionId, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("RevisionId", revisionId); + return Response.ok(response).build(); + } + + private Response handleGetResourcePolicy(JsonNode request, String region) { + String resourceArn = request.path("ResourceArn").asText(); + if (!isValidDynamoDbTableArn(resourceArn)) { + throw new AwsException("ValidationException", + "Invalid ResourceArn: " + resourceArn, 400); + } + DynamoDbService.ResourcePolicyResult result = dynamoDbService.getResourcePolicy(resourceArn, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("Policy", result.policy()); + response.put("RevisionId", result.revisionId()); + return Response.ok(response).build(); + } + + private Response handleDeleteResourcePolicy(JsonNode request, String region) { + String resourceArn = request.path("ResourceArn").asText(); + if (!isValidDynamoDbTableArn(resourceArn)) { + throw new AwsException("ValidationException", + "Invalid ResourceArn: " + resourceArn, 400); + } + String expectedRevisionId = request.has("ExpectedRevisionId") + ? request.get("ExpectedRevisionId").asText() : null; + + String revisionId = dynamoDbService.deleteResourcePolicy(resourceArn, expectedRevisionId, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("RevisionId", revisionId); + return Response.ok(response).build(); + } + + private Response handleEnableKinesisStreamingDestination(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + String streamArn = request.path("StreamArn").asText(); + JsonNode precisionNode = request.path("EnableKinesisStreamingConfiguration") + .path("ApproximateCreationDateTimePrecision"); + String precision = precisionNode.isMissingNode() || precisionNode.isNull() + ? KinesisStreamingDestination.PRECISION_MILLISECOND : precisionNode.asText(); + if (!KinesisStreamingDestination.PRECISION_MILLISECOND.equals(precision) + && !KinesisStreamingDestination.PRECISION_MICROSECOND.equals(precision)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + precision + + "' at 'enableKinesisStreamingConfiguration.approximateCreationDateTimePrecision' " + + "failed to satisfy constraint: Member must satisfy enum value set: [MILLISECOND, MICROSECOND]", + 400); + } + + String resolvedTableName = tableService.enableKinesisStreamingDestination( + tableName, streamArn, precision, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("TableName", resolvedTableName); + response.put("StreamArn", streamArn); + response.put("DestinationStatus", "ACTIVE"); + response.put("DestinationStatusDescription", "Kinesis streaming is enabled for this table"); + response.putObject("EnableKinesisStreamingConfiguration") + .put("ApproximateCreationDateTimePrecision", precision); + return Response.ok(response).build(); + } + + private Response handleDisableKinesisStreamingDestination(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + String streamArn = request.path("StreamArn").asText(); + + String resolvedTableName = tableService.disableKinesisStreamingDestination(tableName, streamArn, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("TableName", resolvedTableName); + response.put("StreamArn", streamArn); + response.put("DestinationStatus", "DISABLED"); + response.put("DestinationStatusDescription", "Kinesis streaming is disabled for this table"); + return Response.ok(response).build(); + } + + private Response handleDescribeKinesisStreamingDestination(JsonNode request, String region) { + String tableName = request.path("TableName").asText(); + TableDefinition table = dynamoDbService.describeTable(tableName, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("TableName", table.getTableName()); + + ArrayNode destinations = objectMapper.createArrayNode(); + for (KinesisStreamingDestination dest : table.getKinesisStreamingDestinations()) { + ObjectNode destNode = objectMapper.createObjectNode(); + destNode.put("StreamArn", dest.getStreamArn()); + destNode.put("DestinationStatus", dest.getDestinationStatus()); + destNode.put("DestinationStatusDescription", dest.getDestinationStatusDescription()); + destNode.put("ApproximateCreationDateTimePrecision", + dest.getApproximateCreationDateTimePrecision()); + destinations.add(destNode); + } + response.set("KinesisDataStreamDestinations", destinations); + return Response.ok(response).build(); + } + + /** + * Builds a ConsumedCapacity node if the request includes ReturnConsumedCapacity. + * Uses simple estimates: 0.5 RCU per item read, 1.0 WCU per item written. + */ + private void validateItemSets(JsonNode item) { + if (item == null || !item.isObject()) return; + item.fields().forEachRemaining(entry -> { + JsonNode attr = entry.getValue(); + checkAttrSets(attr); + }); + } + + private void checkAttrSets(JsonNode attr) { + if (attr == null) return; + if (attr.has("NULL") && !attr.get("NULL").asBoolean()) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: Null attribute value types must have the value of true", 400); + } + if (attr.has("SS")) { + JsonNode ss = attr.get("SS"); + if (ss.isEmpty()) throw new AwsException("ValidationException", + "One or more parameter values were invalid: An string set may not be empty", 400); + Set seen = new HashSet<>(); + for (JsonNode e : ss) { + if (!seen.add(e.asText())) throw new AwsException("ValidationException", + "One or more parameter values were invalid: Input collection " + formatSetForError(ss) + " contains duplicates.", 400); + } + } else if (attr.has("NS")) { + JsonNode ns = attr.get("NS"); + if (ns.isEmpty()) throw new AwsException("ValidationException", + "One or more parameter values were invalid: An number set may not be empty", 400); + Set seen = new HashSet<>(); + for (JsonNode e : ns) { + if (!seen.add(e.asText())) throw new AwsException("ValidationException", + "One or more parameter values were invalid: Input collection " + formatSetForError(ns) + " contains duplicates.", 400); + } + } else if (attr.has("BS")) { + JsonNode bs = attr.get("BS"); + if (bs.isEmpty()) throw new AwsException("ValidationException", + "One or more parameter values were invalid: Binary sets should not be empty", 400); + Set seen = new HashSet<>(); + for (JsonNode e : bs) { + // A binary set names its type, and AWS leaves out the space before "of". + if (!seen.add(e.asText())) throw new AwsException("ValidationException", + "One or more parameter values were invalid: Input collection " + formatSetForError(bs) + + "of type BS contains duplicates.", 400); + } + } else if (attr.has("M")) { + attr.get("M").fields().forEachRemaining(e -> checkAttrSets(e.getValue())); + } else if (attr.has("L")) { + attr.get("L").forEach(this::checkAttrSets); + } + } + + // ── Expression token utilities ── + + private static void extractPrefixedTokens(String expr, char prefix, Set out) { + if (expr == null) return; + int i = 0; + while (i < expr.length()) { + if (expr.charAt(i) == prefix) { + int start = i++; + while (i < expr.length() && (Character.isLetterOrDigit(expr.charAt(i)) || expr.charAt(i) == '_')) i++; + if (i > start + 1) out.add(expr.substring(start, i)); + } else { + i++; + } + } + } + + private static Set extractHashTokens(String... expressions) { + Set tokens = new LinkedHashSet<>(); + for (String expr : expressions) extractPrefixedTokens(expr, '#', tokens); + return tokens; + } + + private static Set extractColonTokens(String... expressions) { + Set tokens = new LinkedHashSet<>(); + for (String expr : expressions) extractPrefixedTokens(expr, ':', tokens); + return tokens; + } + + /** + * Rejects ExpressionAttributeNames/Values supplied when the request carries no expression to + * reference them. AWS answers this sub-case with "<param> can only be specified when using + * expressions: <nullExpressionParams>" rather than the "unused in expressions" wording used + * once an alias is merely unreferenced (#2893). {@code nullExpressionParams} must spell the absent + * expression parameter(s) exactly as AWS reports them for the operation, e.g. "ConditionExpression is null". + * EAV is checked before EAN to match the pre-existing PutItem guard. + */ + private static void rejectExprAttrsWithoutExpression(JsonNode exprAttrNames, JsonNode exprAttrValues, + boolean hasAnyExpression, String nullExpressionParams) { + if (hasAnyExpression) { + return; + } + if (exprAttrValues != null) { + throw new AwsException("ValidationException", + "ExpressionAttributeValues can only be specified when using expressions: " + nullExpressionParams, 400); + } + if (exprAttrNames != null) { + throw new AwsException("ValidationException", + "ExpressionAttributeNames can only be specified when using expressions: " + nullExpressionParams, 400); + } + } + + private static void checkUnusedEan(JsonNode exprAttrNames, Set usedHashTokens) { + if (exprAttrNames == null) return; + List unused = new ArrayList<>(); + exprAttrNames.fieldNames().forEachRemaining(k -> { + if (!usedHashTokens.contains(k)) unused.add(k); + }); + if (!unused.isEmpty()) { + throw new AwsException("ValidationException", + "Value provided in ExpressionAttributeNames unused in expressions: keys: {" + + String.join(", ", unused) + "}", 400); + } + } + + private static void checkUnusedEav(JsonNode exprAttrValues, Set usedColonTokens) { + if (exprAttrValues == null) return; + List unused = new ArrayList<>(); + exprAttrValues.fieldNames().forEachRemaining(k -> { + if (!usedColonTokens.contains(k)) unused.add(k); + }); + if (!unused.isEmpty()) { + throw new AwsException("ValidationException", + "Value provided in ExpressionAttributeValues unused in expressions: keys: {" + + String.join(", ", unused) + "}", 400); + } + } + + private String formatSetForError(JsonNode arr) { + StringBuilder sb = new StringBuilder("["); + boolean first = true; + for (JsonNode e : arr) { + if (!first) sb.append(", "); + sb.append(e.asText()); + first = false; + } + sb.append("]"); + return sb.toString(); + } + + // Filters items to only include the attributes projected into the given index. + private List applyIndexProjection(List items, TableDefinition table, + DynamoDbAccessPath accessPath, String select) { + if ("ALL_ATTRIBUTES".equals(select) || "ALL".equals(accessPath.projectionType())) { + return items; + } + + Set allowed = accessPath.projectedAttributeNames(table); + return items.stream() + .map(item -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) item, allowed)) + .toList(); + } + + /** + * Half a read unit per 4KB read, doubled for a strongly consistent read, with the + * half-unit minimum DynamoDB charges even when nothing is found. + */ + static double readCapacityUnits(long bytes, boolean consistentRead) { + var units = Math.max(1, (bytes + 4095) / 4096) * 0.5; + return consistentRead ? units * 2 : units; + } + + /** + * Write-side ConsumedCapacity with the per-index arms DynamoDB reports under + * INDEXES. oldItem and newItem are the stored images around the write; the new + * image is normalized the way storage normalizes it so an identical overwrite + * compares equal. + */ + private void addWriteConsumedCapacity(ObjectNode response, JsonNode request, String tableName, + String region, JsonNode oldItem, JsonNode newItem) { + String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); + if ("NONE".equals(returnCC)) return; + TableDefinition table = dynamoDbService.requireTableForItemCall(tableName, region); + var cost = DynamoDbWriteCapacity.forWrite(table, oldItem, + newItem != null ? DynamoDbNumberUtils.normalizeNumbersInItem(newItem) : null); + response.set("ConsumedCapacity", + writeCapacityNode(tableName, cost, "INDEXES".equals(returnCC))); + } + + private void addTransactWriteConsumedCapacity(ObjectNode response, JsonNode request, + DynamoDbService.TransactWriteResult result) { + addPerTableConsumedCapacity(response, request, result.capacity(), + result.replayed() ? "ReadCapacityUnits" : "WriteCapacityUnits"); + } + + private void addPerTableConsumedCapacity(ObjectNode response, JsonNode request, + Map capacityByTable, + String unitsField) { + String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); + if ("NONE".equals(returnCC) || capacityByTable.isEmpty()) { + return; + } + ArrayNode entries = objectMapper.createArrayNode(); + capacityByTable.forEach((tableName, cost) -> + entries.add(writeCapacityNode(tableName, cost, "INDEXES".equals(returnCC), unitsField))); + response.set("ConsumedCapacity", entries); + } + + private ObjectNode writeCapacityNode(String tableName, DynamoDbWriteCapacity.Cost cost, + boolean withBreakdown) { + return writeCapacityNode(tableName, cost, withBreakdown, null); + } + + private ObjectNode writeCapacityNode(String tableName, DynamoDbWriteCapacity.Cost cost, + boolean withBreakdown, String unitsField) { + ObjectNode cc = objectMapper.createObjectNode(); + cc.put("TableName", DynamoDbTableNames.resolve(tableName)); + cc.setAll(capacityUnitsNode(cost.total(), unitsField)); + if (withBreakdown) { + cc.set("Table", capacityUnitsNode(cost.table(), unitsField)); + if (!cost.gsi().isEmpty()) { + cc.set("GlobalSecondaryIndexes", capacityUnitsMap(cost.gsi(), unitsField)); + } + if (!cost.lsi().isEmpty()) { + cc.set("LocalSecondaryIndexes", capacityUnitsMap(cost.lsi(), unitsField)); + } + if (!cost.vectorBytes().isEmpty()) { + cc.set("VectorIndexes", vectorWriteBytesMap(cost.vectorBytes())); + } + } + return cc; + } + + /** A vector index meters bytes processed, so it carries no CapacityUnits of its own. */ + private ObjectNode vectorWriteBytesMap(Map bytesByIndex) { + ObjectNode node = objectMapper.createObjectNode(); + bytesByIndex.forEach((indexName, bytes) -> { + ObjectNode entry = objectMapper.createObjectNode(); + entry.put("VectorWriteRequestBytes", bytes); + node.set(indexName, entry); + }); + return node; + } + + private ObjectNode capacityUnitsMap(Map unitsByIndex, String unitsField) { + ObjectNode node = objectMapper.createObjectNode(); + unitsByIndex.forEach((indexName, units) -> node.set(indexName, capacityUnitsNode(units, unitsField))); + return node; + } + + private ObjectNode capacityUnitsNode(double units, String unitsField) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("CapacityUnits", units); + if (unitsField != null) { + node.put(unitsField, units); + } + return node; + } + + private void addConsumedCapacity(ObjectNode response, JsonNode request, String tableName, + double cu, DynamoDbAccessPath accessPath) { + String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); + if ("NONE".equals(returnCC)) return; + + ObjectNode cc = objectMapper.createObjectNode(); + cc.put("TableName", DynamoDbTableNames.resolve(tableName)); + cc.put("CapacityUnits", cu); + + if ("INDEXES".equals(returnCC)) { + ObjectNode tableCap = objectMapper.createObjectNode(); + if (accessPath != null && accessPath.isIndex()) { + tableCap.put("CapacityUnits", 0.0); + cc.set("Table", tableCap); + ObjectNode indexCaps = objectMapper.createObjectNode(); + ObjectNode indexCap = objectMapper.createObjectNode(); + indexCap.put("CapacityUnits", cu); + indexCaps.set(accessPath.indexName(), indexCap); + cc.set(accessPath.isGlobalSecondaryIndex() + ? "GlobalSecondaryIndexes" : "LocalSecondaryIndexes", indexCaps); + } else { + tableCap.put("CapacityUnits", cu); + cc.set("Table", tableCap); + } + } + + response.set("ConsumedCapacity", cc); + } + + /** + * Builds a list-style ConsumedCapacity for batch operations. + */ + private void addBatchConsumedCapacity(ObjectNode response, JsonNode request, + Map tableItems, boolean isWrite) { + String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); + if ("NONE".equals(returnCC)) return; + + ArrayNode ccArray = objectMapper.createArrayNode(); + for (String tableName : tableItems.keySet()) { + ObjectNode cc = objectMapper.createObjectNode(); + cc.put("TableName", DynamoDbTableNames.resolve(tableName)); + cc.put("CapacityUnits", isWrite ? 1.0 : 0.5); + if ("INDEXES".equals(returnCC)) { + ObjectNode tableCap = objectMapper.createObjectNode(); + tableCap.put("CapacityUnits", isWrite ? 1.0 : 0.5); + cc.set("Table", tableCap); + } + ccArray.add(cc); + } + response.set("ConsumedCapacity", ccArray); + } + + private ObjectNode tableToNode(TableDefinition table) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("TableName", table.getTableName()); + node.put("TableId", table.getTableId()); + node.put("TableStatus", table.getTableStatus()); + node.put("TableArn", table.getTableArn()); + node.put("CreationDateTime", table.getCreationDateTime().getEpochSecond()); + node.put("ItemCount", table.getItemCount()); + node.put("TableSizeBytes", table.getTableSizeBytes()); + node.put("DeletionProtectionEnabled", table.isDeletionProtectionEnabled()); + + if ("PAY_PER_REQUEST".equals(table.getBillingMode())) { + ObjectNode billing = objectMapper.createObjectNode(); + billing.put("BillingMode", "PAY_PER_REQUEST"); + billing.put("LastUpdateToPayPerRequestDateTime", + table.getCreationDateTime().getEpochSecond()); + node.set("BillingModeSummary", billing); + } + + // TableClassSummary always present; defaults to STANDARD. + ObjectNode tableClassSummary = objectMapper.createObjectNode(); + tableClassSummary.put("TableClass", + table.getTableClass() != null ? table.getTableClass() : "STANDARD"); + node.set("TableClassSummary", tableClassSummary); + + if (table.getOnDemandMaxReadRequestUnits() != null + || table.getOnDemandMaxWriteRequestUnits() != null) { + ObjectNode odt = objectMapper.createObjectNode(); + if (table.getOnDemandMaxReadRequestUnits() != null) { + odt.put("MaxReadRequestUnits", table.getOnDemandMaxReadRequestUnits()); + } + if (table.getOnDemandMaxWriteRequestUnits() != null) { + odt.put("MaxWriteRequestUnits", table.getOnDemandMaxWriteRequestUnits()); + } + node.set("OnDemandThroughput", odt); + } + + ObjectNode warmThroughput = objectMapper.createObjectNode(); + warmThroughput.put("Status", "ACTIVE"); + warmThroughput.put("ReadUnitsPerSecond", 0); + warmThroughput.put("WriteUnitsPerSecond", 0); + node.set("WarmThroughput", warmThroughput); + + // Global-table replicas. In a single-process emulator every region is served by this same + // table, so a replica is metadata; AWS reports each as an ACTIVE Replica and marks the table + // a 2019.11.21 global table. A global table also lists its own home region as a replica, so it + // is appended (once) after the tracked ones; a plain table (no replicas, no home) has neither. + List replicaRegions = table.getReplicaRegions(); + String homeRegion = table.getGlobalTableHomeRegion(); + LinkedHashSet regions = new LinkedHashSet<>( + replicaRegions != null ? replicaRegions : List.of()); + if (homeRegion != null && !homeRegion.isBlank()) { + regions.add(homeRegion); + } + if (!regions.isEmpty()) { + ArrayNode replicas = objectMapper.createArrayNode(); + for (String replicaRegion : regions) { + ObjectNode replica = objectMapper.createObjectNode(); + replica.put("RegionName", replicaRegion); + replica.put("ReplicaStatus", "ACTIVE"); + replicas.add(replica); + } + node.set("Replicas", replicas); + node.put("GlobalTableVersion", "2019.11.21"); + } + + ArrayNode keySchemaArray = objectMapper.createArrayNode(); + for (var ks : table.getKeySchema()) { + ObjectNode ksNode = objectMapper.createObjectNode(); + ksNode.put("AttributeName", ks.getAttributeName()); + ksNode.put("KeyType", ks.getKeyType()); + keySchemaArray.add(ksNode); + } + node.set("KeySchema", keySchemaArray); + + ArrayNode attrDefsArray = objectMapper.createArrayNode(); + for (var ad : table.getAttributeDefinitions()) { + ObjectNode adNode = objectMapper.createObjectNode(); + adNode.put("AttributeName", ad.getAttributeName()); + adNode.put("AttributeType", ad.getAttributeType()); + attrDefsArray.add(adNode); + } + node.set("AttributeDefinitions", attrDefsArray); + + ObjectNode ptNode = objectMapper.createObjectNode(); + ptNode.put("ReadCapacityUnits", table.getProvisionedThroughput().getReadCapacityUnits()); + ptNode.put("WriteCapacityUnits", table.getProvisionedThroughput().getWriteCapacityUnits()); + ptNode.put("NumberOfDecreasesToday", table.getProvisionedThroughput().getNumberOfDecreasesToday()); + node.set("ProvisionedThroughput", ptNode); + + if (table.isSseEnabled()) { + ObjectNode sseDescription = objectMapper.createObjectNode(); + sseDescription.put("Status", "ENABLED"); + String sseType = table.getSseType() != null ? table.getSseType() : SSE_TYPE_KMS; + sseDescription.put("SSEType", sseType); + if (SSE_TYPE_KMS.equals(sseType)) { + sseDescription.put("KMSMasterKeyArn", table.getKmsMasterKeyArn() != null + ? table.getKmsMasterKeyArn() + : NativeDynamoDbTableService.defaultKmsMasterKeyArn( + AwsArnUtils.regionOrDefault(table.getTableArn(), "us-east-1"))); + } + node.set("SSEDescription", sseDescription); + } + + List gsis = table.getGlobalSecondaryIndexes(); + if (gsis != null && !gsis.isEmpty()) { + ArrayNode gsiArray = objectMapper.createArrayNode(); + for (GlobalSecondaryIndex gsi : gsis) { + ObjectNode gsiNode = objectMapper.createObjectNode(); + gsiNode.put("IndexName", gsi.getIndexName()); + gsiNode.put("IndexArn", gsi.getIndexArn()); + gsiNode.put("IndexStatus", "ACTIVE"); + + ArrayNode gsiKeySchema = objectMapper.createArrayNode(); + for (var ks : gsi.getKeySchema()) { + ObjectNode ksNode = objectMapper.createObjectNode(); + ksNode.put("AttributeName", ks.getAttributeName()); + ksNode.put("KeyType", ks.getKeyType()); + gsiKeySchema.add(ksNode); + } + gsiNode.set("KeySchema", gsiKeySchema); + + ObjectNode projection = objectMapper.createObjectNode(); + projection.put("ProjectionType", + gsi.getProjectionType() != null ? gsi.getProjectionType() : "ALL"); + if ("INCLUDE".equals(gsi.getProjectionType())){ + ArrayNode nonKeyAttributes = objectMapper.createArrayNode(); + for (var attr : gsi.getNonKeyAttributes()){ + nonKeyAttributes.add(attr); + } + projection.put("NonKeyAttributes", nonKeyAttributes); + } + gsiNode.set("Projection", projection); + + ObjectNode gsiPt = objectMapper.createObjectNode(); + gsiPt.put("ReadCapacityUnits", gsi.getProvisionedThroughput().getReadCapacityUnits()); + gsiPt.put("WriteCapacityUnits", gsi.getProvisionedThroughput().getWriteCapacityUnits()); + gsiPt.put("NumberOfDecreasesToday", gsi.getProvisionedThroughput().getNumberOfDecreasesToday()); + gsiNode.set("ProvisionedThroughput", gsiPt); + gsiNode.put("IndexSizeBytes", gsi.getIndexSizeBytes()); + gsiNode.put("ItemCount", gsi.getItemCount()); + + if (gsi.getOnDemandMaxReadRequestUnits() != null + || gsi.getOnDemandMaxWriteRequestUnits() != null) { + ObjectNode gsiOdt = objectMapper.createObjectNode(); + if (gsi.getOnDemandMaxReadRequestUnits() != null) { + gsiOdt.put("MaxReadRequestUnits", gsi.getOnDemandMaxReadRequestUnits()); + } + if (gsi.getOnDemandMaxWriteRequestUnits() != null) { + gsiOdt.put("MaxWriteRequestUnits", gsi.getOnDemandMaxWriteRequestUnits()); + } + gsiNode.set("OnDemandThroughput", gsiOdt); + } + + gsiArray.add(gsiNode); + } + node.set("GlobalSecondaryIndexes", gsiArray); + } + + List lsis = table.getLocalSecondaryIndexes(); + if (lsis != null && !lsis.isEmpty()) { + ArrayNode lsiArray = objectMapper.createArrayNode(); + for (LocalSecondaryIndex lsi : lsis) { + ObjectNode lsiNode = objectMapper.createObjectNode(); + lsiNode.put("IndexName", lsi.getIndexName()); + lsiNode.put("IndexArn", lsi.getIndexArn()); + + ArrayNode lsiKeySchema = objectMapper.createArrayNode(); + for (var ks : lsi.getKeySchema()) { + ObjectNode ksNode = objectMapper.createObjectNode(); + ksNode.put("AttributeName", ks.getAttributeName()); + ksNode.put("KeyType", ks.getKeyType()); + lsiKeySchema.add(ksNode); + } + lsiNode.set("KeySchema", lsiKeySchema); + + ObjectNode projection = objectMapper.createObjectNode(); + projection.put("ProjectionType", + lsi.getProjectionType() != null ? lsi.getProjectionType() : "ALL"); + lsiNode.set("Projection", projection); + + lsiNode.put("IndexSizeBytes", lsi.getIndexSizeBytes()); + lsiNode.put("ItemCount", lsi.getItemCount()); + + lsiArray.add(lsiNode); + } + node.set("LocalSecondaryIndexes", lsiArray); + } + + List vectorIndexes = table.getVectorIndexes(); + if (!vectorIndexes.isEmpty()) { + ArrayNode vectorIndexArray = objectMapper.createArrayNode(); + for (VectorIndex vectorIndex : vectorIndexes) { + vectorIndexArray.add(vectorIndexToNode(vectorIndex)); + } + node.set("VectorIndexes", vectorIndexArray); + } + + if (table.getStreamArn() != null) { + ObjectNode streamSpecNode = objectMapper.createObjectNode(); + streamSpecNode.put("StreamEnabled", table.isStreamEnabled()); + streamSpecNode.put("StreamViewType", table.getStreamViewType()); + node.set("StreamSpecification", streamSpecNode); + node.put("LatestStreamArn", table.getStreamArn()); + String label = table.getStreamArn().contains("/stream/") + ? table.getStreamArn().substring(table.getStreamArn().lastIndexOf("/stream/") + 8) + : ""; + node.put("LatestStreamLabel", label); + } + + return node; + } + + /** + * Renders a VectorIndexDescription. ItemCount and IndexSizeBytes are always 0. AWS refreshes + * those two roughly every six hours, so a freshly built index reports 0 for both there too. + */ + private ObjectNode vectorIndexToNode(VectorIndex vectorIndex) { + ObjectNode vectorIndexNode = objectMapper.createObjectNode(); + vectorIndexNode.put("IndexName", vectorIndex.getIndexName()); + + ObjectNode vectorAttribute = objectMapper.createObjectNode(); + vectorAttribute.put("AttributeName", vectorIndex.getVectorAttributeName()); + vectorIndexNode.set("VectorAttribute", vectorAttribute); + + List searchSchema = vectorIndex.getSearchSchema(); + if (searchSchema != null && !searchSchema.isEmpty()) { + ArrayNode searchSchemaArray = objectMapper.createArrayNode(); + for (SearchSchemaElement element : searchSchema) { + ObjectNode elementNode = objectMapper.createObjectNode(); + elementNode.put("AttributeName", element.getAttributeName()); + elementNode.put("SearchSchemaElementType", element.getSearchSchemaElementType()); + searchSchemaArray.add(elementNode); + } + vectorIndexNode.set("SearchSchema", searchSchemaArray); + } + + ObjectNode projection = objectMapper.createObjectNode(); + projection.put("ProjectionType", + vectorIndex.getProjectionType() != null ? vectorIndex.getProjectionType() : "ALL"); + if ("INCLUDE".equals(vectorIndex.getProjectionType())) { + ArrayNode nonKeyAttributes = objectMapper.createArrayNode(); + for (String attr : vectorIndex.getNonKeyAttributes()) { + nonKeyAttributes.add(attr); + } + projection.set("NonKeyAttributes", nonKeyAttributes); + } + vectorIndexNode.set("Projection", projection); + + vectorIndexNode.put("Dimensions", vectorIndex.getDimensions()); + vectorIndexNode.put("DistanceFunction", vectorIndex.getDistanceFunction()); + vectorIndexNode.put("IndexStatus", vectorIndex.getIndexStatus()); + if (dynamoDbService.reportsVectorIndexBackfilling(vectorIndex)) { + vectorIndexNode.put("Backfilling", dynamoDbService.isVectorIndexBackfilling(vectorIndex)); + } + vectorIndexNode.put("IndexSizeBytes", 0); + vectorIndexNode.put("ItemCount", 0); + vectorIndexNode.put("IndexArn", vectorIndex.getIndexArn()); + return vectorIndexNode; + } + + private ObjectNode continuousBackupsDescriptionNode(TableDefinition table) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("ContinuousBackupsStatus", "ENABLED"); + + ObjectNode pitrNode = objectMapper.createObjectNode(); + pitrNode.put("PointInTimeRecoveryStatus", + table.isPointInTimeRecoveryEnabled() ? "ENABLED" : "DISABLED"); + if (table.isPointInTimeRecoveryEnabled()) { + pitrNode.put("RecoveryPeriodInDays", table.getPointInTimeRecoveryRecoveryPeriodInDays()); + } + node.set("PointInTimeRecoveryDescription", pitrNode); + return node; + } + + private Response handleExportTable(JsonNode request, String region) { + Map params = new java.util.HashMap<>(); + request.fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().isTextual() + ? e.getValue().asText() : e.getValue())); + + io.github.hectorvent.floci.services.dynamodb.model.ExportDescription desc = + dynamoDbService.exportTable(params, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("ExportDescription", objectMapper.valueToTree(desc)); + return Response.ok(response).build(); + } + + private Response handleDescribeExport(JsonNode request, String region) { + String exportArn = request.path("ExportArn").asText(); + io.github.hectorvent.floci.services.dynamodb.model.ExportDescription desc = + dynamoDbService.describeExport(exportArn); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("ExportDescription", objectMapper.valueToTree(desc)); + return Response.ok(response).build(); + } + + private Response handleListExports(JsonNode request, String region) { + String tableArn = request.has("TableArn") ? request.get("TableArn").asText() : null; + Integer maxResults = request.has("MaxResults") ? request.get("MaxResults").asInt() : null; + String nextToken = request.has("NextToken") && !request.get("NextToken").isNull() + ? request.get("NextToken").asText() : null; + + DynamoDbService.ListExportsResult result = dynamoDbService.listExports(tableArn, maxResults, nextToken); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode summaries = objectMapper.createArrayNode(); + for (io.github.hectorvent.floci.services.dynamodb.model.ExportSummary s : result.exportSummaries()) { + summaries.add(objectMapper.valueToTree(s)); + } + response.set("ExportSummaries", summaries); + if (result.nextToken() != null) { + response.put("NextToken", result.nextToken()); + } + 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) { + requireValidReturnConsumedCapacity(request); + String statement = request.path("Statement").asText(); + List parameters = toPartiQLParams(request.path("Parameters")); + DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(statement, parameters); + PartiQLExecuteContext ctx = PartiQLExecuteContext.builder() + .limit(request.has("Limit") ? request.get("Limit").asInt() : null) + .nextToken(request.has("NextToken") ? request.get("NextToken").asText() : null) + .consistentRead(request.path("ConsistentRead").asBoolean(false)) + .tokenBinding(partiQLHandler.tokenBinding(statement, parameters)); + DynamoDbPartiQLHandler.Result result = partiQLHandler.execute(stmt, ctx, region); + ObjectNode response = result.body(); + String returnCC = request.path("ReturnConsumedCapacity").asText("NONE"); + if (!"NONE".equals(returnCC)) { + response.set("ConsumedCapacity", + writeCapacityNode(stmt.table(), result.capacity(), "INDEXES".equals(returnCC))); + } + return Response.ok(response).build(); + } + + private Response handleExecuteTransaction(JsonNode request, String region) { + JsonNode stmts = request.path("TransactStatements"); + if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) { + throw new AwsException("ValidationException", "TransactStatements must not be empty", 400); + } + List validationErrors = new ArrayList<>(); + addReturnConsumedCapacityError(request, validationErrors); + throwValidationErrors(validationErrors); + try { + List statements = new ArrayList<>(); + for (int i = 0; i < stmts.size(); i++) { + JsonNode s = stmts.get(i); + List parameters = toPartiQLParams(s.path("Parameters")); + statements.add(inTransactStatement(i, + () -> DynamoDbPartiQLParser.parse(s.path("Statement").asText(), parameters))); + } + long reads = statements.stream().filter(DynamoDbPartiQLParser.Stmt.Select.class::isInstance).count(); + if (reads > 0 && reads < statements.size()) { + throw new AwsException("ValidationException", + "ExecuteTransaction API does not support both read and write operations in the same request.", 400); + } + if (reads == statements.size()) { + return executeTransactionReads(statements.stream() + .map(DynamoDbPartiQLParser.Stmt.Select.class::cast) + .toList(), request, region); + } + List members = new ArrayList<>(); + for (int i = 0; i < statements.size(); i++) { + DynamoDbPartiQLParser.Stmt stmt = statements.get(i); + members.add(inTransactStatement(i, () -> partiQLHandler.toTransactItem(stmt, region))); + } + List transactItems = cancelOnMemberReasons(members); + DynamoDbService.TransactWriteResult result = dynamoDbService.transactWriteItems(transactItems, region, + request.path("ClientRequestToken").asText(null), request); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("Responses", objectMapper.createArrayNode()); + addTransactWriteConsumedCapacity(resp, request, result); + return Response.ok(resp).build(); + } catch (TransactionCanceledException e) { + ObjectNode body = objectMapper.createObjectNode(); + body.put("__type", "TransactionCanceledException"); + body.put("message", e.getMessage()); + ArrayNode reasons = body.putArray("CancellationReasons"); + for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) { + ObjectNode r = objectMapper.createObjectNode(); + r.put("Code", reason.code().isEmpty() ? "None" : reason.code()); + if (!reason.code().isEmpty()) { + r.put("Message", reason.message() != null ? reason.message() : "The conditional request failed"); + } + if (reason.item() != null) { + r.set("Item", reason.item()); + } + reasons.add(r); + } + return Response.status(400).entity(body).build(); + } + } + + private Response executeTransactionReads(List selects, JsonNode request, + String region) { + List members = new ArrayList<>(); + for (int i = 0; i < selects.size(); i++) { + DynamoDbPartiQLParser.Stmt.Select select = selects.get(i); + members.add(inTransactStatement(i, () -> partiQLHandler.toTransactGetItem(select, region))); + } + List getItems = cancelOnMemberReasons(members); + + DynamoDbService.TransactGetResult result = dynamoDbService.transactGetItems(getItems, region); + requireOneReadPerItem(getItems, region); + List results = result.items(); + ArrayNode responses = objectMapper.createArrayNode(); + for (int i = 0; i < results.size(); i++) { + JsonNode item = partiQLHandler.projectSelected(selects.get(i), results.get(i)); + ObjectNode entry = objectMapper.createObjectNode(); + if (item != null) { + entry.set("Item", item); + } + responses.add(entry); + } + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("Responses", responses); + addPerTableConsumedCapacity(resp, request, result.capacity(), "ReadCapacityUnits"); + return Response.ok(resp).build(); + } + + private static List cancelOnMemberReasons(List members) { + List items = new ArrayList<>(); + List reasons = new ArrayList<>(); + boolean cancelled = false; + for (DynamoDbPartiQLHandler.TransactMember member : members) { + cancelled |= member.reason() != null; + items.add(member.item()); + reasons.add(member.reason() != null ? member.reason() : new TransactionCanceledException.CancellationReason("", null)); + } + if (cancelled) { + throw new TransactionCanceledException(reasons); + } + return items; + } + + private void requireOneReadPerItem(List getItems, String region) { + Set> items = new HashSet<>(); + for (JsonNode getItem : getItems) { + JsonNode get = getItem.path("Get"); + String tableName = get.path("TableName").asText(); + TableDefinition table = dynamoDbService.findTable(tableName, region).orElseThrow(); + String itemKey = dynamoDbService.buildItemKey(table, get.path("Key"), true); + if (!items.add(List.of(tableName, itemKey))) { + throw new AwsException("ValidationException", + "Transaction request cannot include multiple operations on one item", 400); + } + } + } + + private T inTransactStatement(int index, Supplier member) { + try { + return member.get(); + } catch (AwsException e) { + if (!"ValidationException".equals(e.getErrorCode())) { + throw e; + } + throw new AwsException("ValidationException", + "Validation failed in TransactStatements[" + index + "]: " + e.getMessage(), 400); + } + } + + private Response handleBatchExecuteStatement(JsonNode request, String region) { + requireValidReturnConsumedCapacity(request); + JsonNode stmts = request.path("Statements"); + if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) { + throw new AwsException("ValidationException", "Statements must not be empty", 400); + } + ArrayNode responses = objectMapper.createArrayNode(); + Map capacity = new LinkedHashMap<>(); + for (JsonNode s : stmts) { + responses.add(batchMemberResponse(s, region, capacity)); + } + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("Responses", responses); + addPerTableConsumedCapacity(resp, request, capacity, null); + return Response.ok(resp).build(); + } + + private ObjectNode batchMemberResponse(JsonNode statement, String region, + Map capacity) { + ObjectNode slot = objectMapper.createObjectNode(); + String tableName = null; + try { + DynamoDbPartiQLParser.Stmt stmt = parsePartiQLStatement(statement); + tableName = stmt.table(); + if (stmt instanceof DynamoDbPartiQLParser.Stmt.Select select) { + requireBatchSelectReadsByKey(select, region); + } + DynamoDbPartiQLHandler.Result result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder() + .consistentRead(statement.path("ConsistentRead").asBoolean(false)), region); + JsonNode firstItem = result.body().path("Items").path(0); + if (!firstItem.isMissingNode()) { + slot.set("Item", firstItem); + } + slot.put("TableName", tableName); + capacity.merge(tableName, result.capacity(), DynamoDbWriteCapacity.Cost::plus); + } catch (AwsException e) { + ObjectNode err = objectMapper.createObjectNode(); + err.put("Code", batchMemberErrorCode(e.getErrorCode())); + err.put("Message", e.getMessage()); + slot.set("Error", err); + if (tableName != null && batchMemberReachedItsTable(e)) { + slot.put("TableName", tableName); + } + } + return slot; + } + + private static String batchMemberErrorCode(String errorCode) { + if ("ValidationException".equals(errorCode)) { + return "ValidationError"; + } + return errorCode.endsWith("Exception") + ? errorCode.substring(0, errorCode.length() - "Exception".length()) + : errorCode; + } + + private static boolean batchMemberReachedItsTable(AwsException e) { + return e instanceof ItemNestingExceededException + || "ConditionalCheckFailedException".equals(e.getErrorCode()) + || "DuplicateItemException".equals(e.getErrorCode()); + } + + // BatchExecuteStatement only runs SELECT statements that resolve through + // the table's primary key: index-qualified statements and partial-key + // WHERE clauses are rejected per statement (characterised on real AWS, + // eu-west-1, 2026-09-02). + private void requireBatchSelectReadsByKey(DynamoDbPartiQLParser.Stmt.Select select, String region) { + if (select.index() != null) { + throw batchSelectNeedsKey(); + } + TableDefinition table = dynamoDbService.requireTableForItemCall(select.table(), region); + DynamoDbPartiQLHandler.requireReadsWithinLimit(table, select.where()); + if (!DynamoDbPartiQLHandler.namesOnlyTheKey(table, select.where())) { + throw batchSelectNeedsKey(); + } + } + + private static AwsException batchSelectNeedsKey() { + return new AwsException("ValidationException", + "Select statements within BatchExecuteStatement must specify the primary key in the where clause.", 400); + } + + private DynamoDbPartiQLParser.Stmt parsePartiQLStatement(JsonNode statement) { + return DynamoDbPartiQLParser.parse(statement.path("Statement").asText(), + toPartiQLParams(statement.path("Parameters"))); + } + + private List toPartiQLParams(JsonNode node) { + if (node == null || node.isMissingNode() || !node.isArray()) { + return Collections.emptyList(); + } + List params = new ArrayList<>(); + for (JsonNode parameter : node) { + DynamoDbAttributeValueValidator.requireParameterNestingWithinLimit(parameter); + checkAttrSets(parameter); + params.add(parameter); + } + return params; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java new file mode 100644 index 0000000000..a94dcf9734 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java @@ -0,0 +1,183 @@ +package io.github.hectorvent.floci.services.dynamodb; + +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord; +import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; +import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription; +import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.List; + +/** + * DynamoDB Streams JSON protocol handler of the native engine, reached through the native backend. + * Handles requests with X-Amz-Target prefix {@code DynamoDBStreams_20120810.}. + */ +@ApplicationScoped +public class NativeDynamoDbStreamsJsonHandler { + + private static final Logger LOG = Logger.getLogger(NativeDynamoDbStreamsJsonHandler.class); + + private final DynamoDbStreamService streamService; + private final DynamoDbService dynamoDbService; + private final ObjectMapper objectMapper; + + @Inject + public NativeDynamoDbStreamsJsonHandler(DynamoDbStreamService streamService, DynamoDbService dynamoDbService, + ObjectMapper objectMapper) { + this.streamService = streamService; + this.dynamoDbService = dynamoDbService; + this.objectMapper = objectMapper; + } + + public Response handle(String action, JsonNode request, String region) { + return switch (action) { + case "ListStreams" -> handleListStreams(request, region); + case "DescribeStream" -> handleDescribeStream(request, region); + case "GetShardIterator" -> handleGetShardIterator(request, region); + case "GetRecords" -> handleGetRecords(request, region); + default -> { + yield Response.status(400) + .entity(new AwsErrorResponse("UnknownOperationException", "Operation " + action + " is not supported.")) + .build(); + } + }; + } + + private Response handleListStreams(JsonNode request, String region) { + String tableNameFilter = request.has("TableName") ? request.get("TableName").asText() : null; + + List streams = streamService.listStreams(tableNameFilter, region); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode streamList = objectMapper.createArrayNode(); + for (StreamDescription sd : streams) { + ObjectNode entry = objectMapper.createObjectNode(); + entry.put("StreamArn", sd.getStreamArn()); + entry.put("StreamLabel", sd.getStreamLabel()); + entry.put("TableName", sd.getTableName()); + streamList.add(entry); + } + response.set("Streams", streamList); + return Response.ok(response).build(); + } + + private Response handleDescribeStream(JsonNode request, String region) { + String streamArn = request.path("StreamArn").asText(); + StreamDescription sd = streamService.describeStream(streamArn); + + // Fetch key schema from the table + List keySchema = List.of(); + try { + TableDefinition table = dynamoDbService.describeTable(sd.getTableName(), region); + keySchema = table.getKeySchema(); + } catch (AwsException e) { + if (!"ResourceNotFoundException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("Table {0} of stream {1} not found, describing the stream without a KeySchema", + sd.getTableName(), streamArn); + } + + ObjectNode response = objectMapper.createObjectNode(); + response.set("StreamDescription", describeStreamToNode(sd, keySchema)); + return Response.ok(response).build(); + } + + private ObjectNode describeStreamToNode(StreamDescription sd, List keySchema) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("StreamArn", sd.getStreamArn()); + node.put("StreamLabel", sd.getStreamLabel()); + node.put("StreamStatus", sd.getStreamStatus()); + node.put("StreamViewType", sd.getStreamViewType()); + node.put("TableName", sd.getTableName()); + node.put("CreationRequestDateTime", sd.getCreationDateTime().getEpochSecond()); + + ArrayNode keySchemaArray = objectMapper.createArrayNode(); + for (KeySchemaElement ks : keySchema) { + ObjectNode ksNode = objectMapper.createObjectNode(); + ksNode.put("AttributeName", ks.getAttributeName()); + ksNode.put("KeyType", ks.getKeyType()); + keySchemaArray.add(ksNode); + } + node.set("KeySchema", keySchemaArray); + + ArrayNode shards = objectMapper.createArrayNode(); + ObjectNode shard = objectMapper.createObjectNode(); + shard.put("ShardId", DynamoDbStreamService.SHARD_ID); + ObjectNode seqRange = objectMapper.createObjectNode(); + seqRange.put("StartingSequenceNumber", sd.getStartingSequenceNumber()); + shard.set("SequenceNumberRange", seqRange); + shards.add(shard); + node.set("Shards", shards); + + node.putNull("LastEvaluatedShardId"); + return node; + } + + private Response handleGetShardIterator(JsonNode request, String region) { + String streamArn = request.path("StreamArn").asText(); + String shardId = request.path("ShardId").asText(); + String iteratorType = request.path("ShardIteratorType").asText(); + String sequenceNumber = request.has("SequenceNumber") + ? request.get("SequenceNumber").asText() : null; + + String iterator = streamService.getShardIterator(streamArn, shardId, iteratorType, sequenceNumber); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("ShardIterator", iterator); + return Response.ok(response).build(); + } + + private Response handleGetRecords(JsonNode request, String region) { + String shardIterator = request.path("ShardIterator").asText(); + Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null; + + DynamoDbStreamService.GetRecordsResult result = streamService.getRecords(shardIterator, limit); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode recordsArray = objectMapper.createArrayNode(); + for (DynamoDbStreamRecord record : result.records()) { + recordsArray.add(recordToNode(record)); + } + response.set("Records", recordsArray); + response.put("NextShardIterator", result.nextShardIterator()); + + return Response.ok(response).build(); + } + + private ObjectNode recordToNode(DynamoDbStreamRecord record) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("eventID", record.getEventId()); + node.put("eventName", record.getEventName()); + node.put("eventVersion", record.getEventVersion()); + node.put("eventSource", record.getEventSource()); + node.put("awsRegion", record.getAwsRegion()); + + ObjectNode dynamodb = objectMapper.createObjectNode(); + dynamodb.put("ApproximateCreationDateTime", record.getApproximateCreationDateTime()); + if (record.getKeys() != null) { + dynamodb.set("Keys", record.getKeys()); + } + if (record.getNewImage() != null) { + dynamodb.set("NewImage", record.getNewImage()); + } + if (record.getOldImage() != null) { + dynamodb.set("OldImage", record.getOldImage()); + } + dynamodb.put("SequenceNumber", record.getSequenceNumber()); + dynamodb.put("SizeBytes", 100); + dynamodb.put("StreamViewType", record.getStreamViewType()); + node.set("dynamodb", dynamodb); + + return node; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelector.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelector.java new file mode 100644 index 0000000000..48d345f2fd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelector.java @@ -0,0 +1,36 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; + +/** + * The one immutable DynamoDB backend selection. Native is the only engine today; a configurable + * choice arrives with the alternative engine. {@link NativeDynamoDbBackend} is typed to its concrete + * class, so these producers are the only unqualified beans for the three seam interfaces. + */ +@ApplicationScoped +public class DynamoDbBackendSelector { + + private final NativeDynamoDbBackend nativeBackend; + + @Inject + public DynamoDbBackendSelector(NativeDynamoDbBackend nativeBackend) { + this.nativeBackend = nativeBackend; + } + + @Produces + DynamoDbOperations operations() { + return nativeBackend; + } + + @Produces + DynamoDbItemAccess itemAccess() { + return nativeBackend; + } + + @Produces + DynamoDbTableAccess tableAccess() { + return nativeBackend; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbItemAccess.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbItemAccess.java new file mode 100644 index 0000000000..f3936225fd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbItemAccess.java @@ -0,0 +1,28 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; + +import java.util.List; + +/** Typed item operations for Java consumers that work with DynamoDB items directly. */ +public interface DynamoDbItemAccess { + + record ScanPage(List items, int scannedCount, JsonNode lastEvaluatedKey) {} + + void putItem(Scope scope, String tableName, JsonNode item, String conditionExpression, + JsonNode expressionAttributeNames, JsonNode expressionAttributeValues); + + JsonNode getItem(Scope scope, String tableName, JsonNode key); + + void deleteItem(Scope scope, String tableName, JsonNode key, String conditionExpression, + JsonNode expressionAttributeNames, JsonNode expressionAttributeValues); + + /** Returns only the image ReturnValues asked for: the new item for ALL_NEW, the old item for ALL_OLD, otherwise null. */ + JsonNode updateItem(Scope scope, String tableName, JsonNode key, JsonNode attributeUpdates, + String updateExpression, JsonNode expressionAttributeNames, + JsonNode expressionAttributeValues, String returnValues, String conditionExpression); + + ScanPage scan(Scope scope, String tableName, String filterExpression, JsonNode expressionAttributeNames, + JsonNode expressionAttributeValues, JsonNode scanFilter, Integer limit, JsonNode exclusiveStartKey); +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbOperations.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbOperations.java new file mode 100644 index 0000000000..566d2a0902 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbOperations.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * The one raw entry point for DynamoDB and DynamoDB Streams wire operations. {@code action} is a + * free string on purpose, so an alternative engine can forward every operation it supports. An AWS + * error surfaces either as a thrown {@code AwsException}, which propagates unchanged, or as a + * non-2xx {@link Reply} carrying the AWS error body. Implementations must not mutate the request body. + * + *

{@code execute} throws {@code Exception} because the native handler throws checked Jackson + * exceptions, which the CBOR controller maps to a 400 SerializationException; wrapping them would + * change wire behavior. + */ +public interface DynamoDbOperations { + + enum Api { DYNAMODB, DYNAMODB_STREAMS } + + record Scope(String accountId, String region) { + public Scope { + if (accountId == null || accountId.isBlank()) { + throw new IllegalArgumentException("accountId is required"); + } + if (region == null || region.isBlank()) { + throw new IllegalArgumentException("region is required"); + } + } + } + + record Call(Scope scope, Api api, String action, JsonNode body) { + public Call { + Objects.requireNonNull(scope, "scope is required"); + Objects.requireNonNull(api, "api is required"); + Objects.requireNonNull(action, "action is required"); + } + } + + record Reply(int status, JsonNode body, Map> headers) { + public Reply { + headers = headers == null ? Map.of() : Map.copyOf(headers); + } + } + + Reply execute(Call call) throws Exception; +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java new file mode 100644 index 0000000000..7f03bae5f2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import io.github.hectorvent.floci.core.resource.ExplorerResource; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; +import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex; +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.TableDefinition; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** Typed table operations for Java consumers that manage DynamoDB tables directly. */ +public interface DynamoDbTableAccess { + + TableDefinition createTable(Scope scope, String tableName, List keySchema, + List attributeDefinitions, Long readCapacity, + Long writeCapacity, List globalSecondaryIndexes, + List localSecondaryIndexes); + + TableDefinition describeTable(Scope scope, String tableName); + + Optional findTable(Scope scope, String tableName); + + /** + * The direct engine delete, with no deletion-protection check. The public DeleteTable wire + * operation, which checks deletion protection, goes through {@link DynamoDbOperations}. + */ + void deleteTable(Scope scope, String tableName); + + TableDefinition enableStream(Scope scope, String tableName, String viewType); + + TableDefinition disableStream(Scope scope, String tableName); + + Map listTagsOfResource(Scope scope, String resourceArn); + + void tagResource(Scope scope, String resourceArn, Map tags); + + void untagResource(Scope scope, String resourceArn, List tagKeys); + + TableDefinition applyReplicaUpdates(Scope scope, String tableName, List addRegions, + List removeRegions); + + TableDefinition ensureGlobalTable(Scope scope, String tableName); + + List resources(String accountId); +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java new file mode 100644 index 0000000000..230db5390a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java @@ -0,0 +1,185 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.core.resource.ExplorerResource; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbStreamsJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex; +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.TableDefinition; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Typed; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * The native engine behind the DynamoDB seam. Raw calls go to the native wire handlers and typed + * calls go straight to {@link DynamoDbService}, each under the scope's account. + */ +@ApplicationScoped +@Typed(NativeDynamoDbBackend.class) +public class NativeDynamoDbBackend implements DynamoDbOperations, DynamoDbItemAccess, DynamoDbTableAccess { + + private final NativeDynamoDbJsonHandler jsonHandler; + private final NativeDynamoDbStreamsJsonHandler streamsHandler; + private final DynamoDbService dynamoDbService; + private final ObjectMapper objectMapper; + + @Inject + public NativeDynamoDbBackend(NativeDynamoDbJsonHandler jsonHandler, + NativeDynamoDbStreamsJsonHandler streamsHandler, + DynamoDbService dynamoDbService, ObjectMapper objectMapper) { + this.jsonHandler = jsonHandler; + this.streamsHandler = streamsHandler; + this.dynamoDbService = dynamoDbService; + this.objectMapper = objectMapper; + } + + @Override + public Reply execute(Call call) throws Exception { + String region = call.scope().region(); + return RequestScopes.callAsChecked(call.scope().accountId(), () -> reply(switch (call.api()) { + case DYNAMODB -> jsonHandler.handle(call.action(), call.body(), region); + case DYNAMODB_STREAMS -> streamsHandler.handle(call.action(), call.body(), region); + })); + } + + private Reply reply(Response response) { + Object entity = response.getEntity(); + JsonNode body; + if (entity == null) { + body = null; + } else if (entity instanceof JsonNode node) { + body = node; + } else { + body = objectMapper.valueToTree(entity); + } + return new Reply(response.getStatus(), body, response.getStringHeaders()); + } + + @Override + public void putItem(Scope scope, String tableName, JsonNode item, String conditionExpression, + JsonNode expressionAttributeNames, JsonNode expressionAttributeValues) { + RequestScopes.runAs(scope.accountId(), () -> dynamoDbService.putItem(tableName, item, conditionExpression, + expressionAttributeNames, expressionAttributeValues, scope.region(), "NONE")); + } + + @Override + public JsonNode getItem(Scope scope, String tableName, JsonNode key) { + return RequestScopes.callAs(scope.accountId(), () -> dynamoDbService.getItem(tableName, key, scope.region())); + } + + @Override + public void deleteItem(Scope scope, String tableName, JsonNode key, String conditionExpression, + JsonNode expressionAttributeNames, JsonNode expressionAttributeValues) { + RequestScopes.runAs(scope.accountId(), () -> dynamoDbService.deleteItem(tableName, key, conditionExpression, + expressionAttributeNames, expressionAttributeValues, scope.region(), "NONE")); + } + + @Override + public JsonNode updateItem(Scope scope, String tableName, JsonNode key, JsonNode attributeUpdates, + String updateExpression, JsonNode expressionAttributeNames, + JsonNode expressionAttributeValues, String returnValues, String conditionExpression) { + DynamoDbService.UpdateResult result = RequestScopes.callAs(scope.accountId(), () -> + dynamoDbService.updateItem(tableName, key, attributeUpdates, updateExpression, + expressionAttributeNames, expressionAttributeValues, returnValues, conditionExpression, + scope.region(), "NONE")); + if ("ALL_NEW".equals(returnValues)) { + return result.newItem(); + } else if ("ALL_OLD".equals(returnValues)) { + return result.oldItem(); + } else { + return null; + } + } + + @Override + public ScanPage scan(Scope scope, String tableName, String filterExpression, JsonNode expressionAttributeNames, + JsonNode expressionAttributeValues, JsonNode scanFilter, Integer limit, + JsonNode exclusiveStartKey) { + DynamoDbService.ScanResult result = RequestScopes.callAs(scope.accountId(), () -> + dynamoDbService.scan(tableName, filterExpression, expressionAttributeNames, + expressionAttributeValues, scanFilter, limit, exclusiveStartKey, scope.region())); + return new ScanPage(result.items(), result.scannedCount(), result.lastEvaluatedKey()); + } + + @Override + public TableDefinition createTable(Scope scope, String tableName, List keySchema, + List attributeDefinitions, Long readCapacity, + Long writeCapacity, List globalSecondaryIndexes, + List localSecondaryIndexes) { + return RequestScopes.callAs(scope.accountId(), () -> dynamoDbService.createTable(tableName, keySchema, + attributeDefinitions, readCapacity, writeCapacity, globalSecondaryIndexes, localSecondaryIndexes, + scope.region())); + } + + @Override + public TableDefinition describeTable(Scope scope, String tableName) { + return RequestScopes.callAs(scope.accountId(), () -> dynamoDbService.describeTable(tableName, scope.region())); + } + + @Override + public Optional findTable(Scope scope, String tableName) { + return RequestScopes.callAs(scope.accountId(), () -> dynamoDbService.findTable(tableName, scope.region())); + } + + @Override + public void deleteTable(Scope scope, String tableName) { + RequestScopes.runAs(scope.accountId(), () -> dynamoDbService.deleteTable(tableName, scope.region())); + } + + @Override + public TableDefinition enableStream(Scope scope, String tableName, String viewType) { + return RequestScopes.callAs(scope.accountId(), + () -> dynamoDbService.enableStream(tableName, viewType, scope.region())); + } + + @Override + public TableDefinition disableStream(Scope scope, String tableName) { + return RequestScopes.callAs(scope.accountId(), () -> dynamoDbService.disableStream(tableName, scope.region())); + } + + @Override + public Map listTagsOfResource(Scope scope, String resourceArn) { + return RequestScopes.callAs(scope.accountId(), + () -> dynamoDbService.listTagsOfResource(resourceArn, scope.region())); + } + + @Override + public void tagResource(Scope scope, String resourceArn, Map tags) { + RequestScopes.runAs(scope.accountId(), () -> dynamoDbService.tagResource(resourceArn, tags, scope.region())); + } + + @Override + public void untagResource(Scope scope, String resourceArn, List tagKeys) { + RequestScopes.runAs(scope.accountId(), + () -> dynamoDbService.untagResource(resourceArn, tagKeys, scope.region())); + } + + @Override + public TableDefinition applyReplicaUpdates(Scope scope, String tableName, List addRegions, + List removeRegions) { + return RequestScopes.callAs(scope.accountId(), + () -> dynamoDbService.applyReplicaUpdates(tableName, addRegions, removeRegions, scope.region())); + } + + @Override + public TableDefinition ensureGlobalTable(Scope scope, String tableName) { + return RequestScopes.callAs(scope.accountId(), + () -> dynamoDbService.ensureGlobalTable(tableName, scope.region())); + } + + @Override + public List resources(String accountId) { + return RequestScopes.callAs(accountId, dynamoDbService::getResources); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java index 9e3581c22c..4b14be11fc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java @@ -34,7 +34,8 @@ import io.github.hectorvent.floci.services.iot.rules.RuleSqlContext; import io.github.hectorvent.floci.services.iot.rules.RuleSqlEvaluator; import io.github.hectorvent.floci.services.iot.rules.RuleSqlParseException; import io.github.hectorvent.floci.services.iot.rules.RuleSqlParser; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; import io.github.hectorvent.floci.services.firehose.FirehoseService; import io.github.hectorvent.floci.services.firehose.model.Record; import io.github.hectorvent.floci.services.kinesis.KinesisService; @@ -117,7 +118,7 @@ public class IotService { private final SnsService snsService; private final S3Service s3Service; private final KinesisService kinesisService; - private final DynamoDbService dynamoDbService; + private final DynamoDbFacade dynamoDb; private final LambdaService lambdaService; private final FirehoseService firehoseService; private final CloudWatchLogsService cloudWatchLogsService; @@ -136,7 +137,7 @@ public class IotService { SnsService snsService, S3Service s3Service, KinesisService kinesisService, - DynamoDbService dynamoDbService, + DynamoDbFacade dynamoDb, LambdaService lambdaService, FirehoseService firehoseService, CloudWatchLogsService cloudWatchLogsService, @@ -156,7 +157,7 @@ public class IotService { storageFactory.create("iot", "iot-thing-groups.json", new TypeReference>() {}), storageFactory.create("iot", "iot-thing-group-memberships.json", new TypeReference>>() {}), config, regionResolver, objectMapper, publishEventRecorder, mqttBrokerService, sqsService, snsService, - s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService, certificateAuthority, + s3Service, kinesisService, dynamoDb, lambdaService, firehoseService, cloudWatchLogsService, certificateAuthority, policyEvaluator); } @@ -182,7 +183,7 @@ public class IotService { SnsService snsService, S3Service s3Service, KinesisService kinesisService, - DynamoDbService dynamoDbService, + DynamoDbFacade dynamoDb, LambdaService lambdaService, FirehoseService firehoseService, CloudWatchLogsService cloudWatchLogsService, @@ -210,7 +211,7 @@ public class IotService { this.snsService = snsService; this.s3Service = s3Service; this.kinesisService = kinesisService; - this.dynamoDbService = dynamoDbService; + this.dynamoDb = dynamoDb; this.lambdaService = lambdaService; this.firehoseService = firehoseService; this.cloudWatchLogsService = cloudWatchLogsService; @@ -1527,7 +1528,10 @@ public class IotService { case "dynamoDBv2" -> { String tableName = action.path("putItem").path("tableName").asText(null); if (tableName != null && !tableName.isBlank()) { - dynamoDbService.putItem(tableName, toDynamoDbItem(payload), region); + // An MQTT publish evaluates rules with no request account, so the write names the rule's owner explicitly. + Scope scope = new Scope( + AwsArnUtils.accountOrDefault(rule.getRuleArn(), config.defaultAccountId()), region); + dynamoDb.items().putItem(scope, tableName, toDynamoDbItem(payload), null, null, null); } } case "lambda" -> { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java index fe80a5f380..187f363c23 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java @@ -8,8 +8,10 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestScopes; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbItemAccess.ScanPage; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord; import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; @@ -39,7 +41,7 @@ public class RedshiftDynamoDbZeroEtlConsumer { private final Vertx vertx; private final DynamoDbStreamService streamService; - private final DynamoDbService dynamoDbService; + private final DynamoDbFacade dynamoDb; private final RedshiftService redshiftService; private final RedshiftZeroEtlWriter writer; private final ObjectMapper objectMapper; @@ -55,32 +57,32 @@ public class RedshiftDynamoDbZeroEtlConsumer { @Inject public RedshiftDynamoDbZeroEtlConsumer(Vertx vertx, DynamoDbStreamService streamService, - DynamoDbService dynamoDbService, + DynamoDbFacade dynamoDb, RedshiftService redshiftService, RedshiftZeroEtlWriter writer, ObjectMapper objectMapper, EmulatorConfig config) { - this(vertx, streamService, dynamoDbService, redshiftService, writer, objectMapper, + this(vertx, streamService, dynamoDb, redshiftService, writer, objectMapper, config.services().redshift().pollIntervalMs()); } RedshiftDynamoDbZeroEtlConsumer(DynamoDbStreamService streamService, - DynamoDbService dynamoDbService, + DynamoDbFacade dynamoDb, RedshiftService redshiftService, RedshiftZeroEtlWriter writer) { - this(null, streamService, dynamoDbService, redshiftService, writer, new ObjectMapper(), 1000); + this(null, streamService, dynamoDb, redshiftService, writer, new ObjectMapper(), 1000); } private RedshiftDynamoDbZeroEtlConsumer(Vertx vertx, DynamoDbStreamService streamService, - DynamoDbService dynamoDbService, + DynamoDbFacade dynamoDb, RedshiftService redshiftService, RedshiftZeroEtlWriter writer, ObjectMapper objectMapper, long pollIntervalMs) { this.vertx = vertx; this.streamService = streamService; - this.dynamoDbService = dynamoDbService; + this.dynamoDb = dynamoDb; this.redshiftService = redshiftService; this.writer = writer; this.objectMapper = objectMapper; @@ -141,11 +143,12 @@ public class RedshiftDynamoDbZeroEtlConsumer { RequestScopes.runAs(integration.getAccountId(), () -> { String tableName = extractTableName(integration.getSourceStreamArn()); String region = AwsArnUtils.parse(integration.getSourceStreamArn()).region(); - TableDefinition table = dynamoDbService.describeTable(tableName, region); + Scope scope = new Scope(integration.getAccountId(), region); + TableDefinition table = dynamoDb.tables().describeTable(scope, tableName); JsonNode exclusiveStartKey = parseBackfillKey(integration.getBackfillLastEvaluatedKey()); - DynamoDbService.ScanResult result = dynamoDbService.scan(tableName, null, null, null, null, - BATCH_SIZE, exclusiveStartKey, region); + ScanPage result = dynamoDb.items().scan(scope, tableName, null, null, null, null, + BATCH_SIZE, exclusiveStartKey); if (!result.items().isEmpty()) { List records = result.items().stream() .map(item -> toBackfillRecord(integration, item, table)) diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 653d4f7b7a..b17afb038d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -10,10 +10,13 @@ import io.github.hectorvent.floci.core.common.CsvParser; import io.github.hectorvent.floci.core.common.CustomResourceLiveness; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.core.common.XmlParser; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbItemAccess; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; @@ -68,9 +71,6 @@ import io.vertx.mutiny.core.Vertx; import io.vertx.mutiny.ext.web.client.HttpRequest; import io.vertx.mutiny.ext.web.client.HttpResponse; import io.vertx.mutiny.ext.web.client.WebClient; -import io.quarkus.arc.Arc; -import io.quarkus.arc.ArcContainer; -import io.quarkus.arc.ManagedContext; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; @@ -234,7 +234,7 @@ public class AslExecutor { private final LambdaExecutorService lambdaExecutor; private final LambdaTargetResolver targetResolver; - private final DynamoDbService dynamoDbService; + private final DynamoDbFacade dynamoDb; private final DynamoDbJsonHandler dynamoDbJsonHandler; private final SqsJsonHandler sqsJsonHandler; private final SnsJsonHandler snsJsonHandler; @@ -267,7 +267,7 @@ public class AslExecutor { @Inject public AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver, - DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler, + DynamoDbFacade dynamoDb, DynamoDbJsonHandler dynamoDbJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, CloudFormationQueryHandler cloudFormationHandler, Ec2Service ec2Service, S3Service s3Service, @@ -277,7 +277,7 @@ public class AslExecutor { ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator, Instance sfnService, EmulatorConfig config, Vertx vertx, CustomResourceLiveness customResourceLiveness) { - this(lambdaExecutor, targetResolver, dynamoDbService, dynamoDbJsonHandler, + this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService, schedulerController, rdsDataService, @@ -286,7 +286,7 @@ public class AslExecutor { } AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver, - DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler, + DynamoDbFacade dynamoDb, DynamoDbJsonHandler dynamoDbJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, CloudFormationQueryHandler cloudFormationHandler, Ec2Service ec2Service, S3Service s3Service, @@ -300,7 +300,7 @@ public class AslExecutor { this.customResourceLiveness = customResourceLiveness; this.lambdaExecutor = lambdaExecutor; this.targetResolver = targetResolver; - this.dynamoDbService = dynamoDbService; + this.dynamoDb = dynamoDb; this.dynamoDbJsonHandler = dynamoDbJsonHandler; this.sqsJsonHandler = sqsJsonHandler; this.snsJsonHandler = snsJsonHandler; @@ -336,7 +336,7 @@ public class AslExecutor { } AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore, - DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler, + DynamoDbFacade dynamoDb, DynamoDbJsonHandler dynamoDbJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, CloudFormationQueryHandler cloudFormationHandler, Ec2Service ec2Service, S3Service s3Service, @@ -347,7 +347,7 @@ public class AslExecutor { Instance sfnService, EmulatorConfig config, Vertx vertx, CustomResourceLiveness customResourceLiveness, Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride) { - this(lambdaExecutor, new LambdaTargetResolver(functionStore, null), dynamoDbService, dynamoDbJsonHandler, + this(lambdaExecutor, new LambdaTargetResolver(functionStore, null), dynamoDb, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService, schedulerController, null, objectMapper, jsonataEvaluator, sfnService, config, @@ -361,7 +361,7 @@ public class AslExecutor { } AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore, - DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler, + DynamoDbFacade dynamoDb, DynamoDbJsonHandler dynamoDbJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, CloudFormationQueryHandler cloudFormationHandler, Ec2Service ec2Service, S3Service s3Service, @@ -371,7 +371,7 @@ public class AslExecutor { ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator, Instance sfnService, EmulatorConfig config, Vertx vertx, CustomResourceLiveness customResourceLiveness) { - this(lambdaExecutor, new LambdaTargetResolver(functionStore, null), dynamoDbService, dynamoDbJsonHandler, + this(lambdaExecutor, new LambdaTargetResolver(functionStore, null), dynamoDb, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService, schedulerController, null, objectMapper, jsonataEvaluator, sfnService, config, @@ -474,33 +474,12 @@ public class AslExecutor { * pool would otherwise run with no active scope and resolve its Task integrations against the * default account instead of the execution's. Each branch thread therefore activates its own * scope here, mirroring how {@link #executeAsync}/{@link #executeSync} wrap {@code doExecute}. + * Delegates to {@link RequestScopes#callAsChecked}, which restores a previously active scope's + * account so a reused thread does not keep the execution's account. */ private T callUnderExecutionAccount(StateMachine sm, Callable body) throws Exception { String accountId = AwsArnUtils.accountOrDefault(sm.getStateMachineArn(), null); - ArcContainer container = Arc.container(); - if (accountId == null || accountId.isBlank() || container == null || !container.isRunning()) { - return body.call(); - } - ManagedContext requestContext = container.requestContext(); - boolean alreadyActive = requestContext.isActive(); - if (!alreadyActive) { - requestContext.activate(); - } - // Execution runs on a background worker that normally has no active scope. If it did run - // inside an already-active scope, restore its previous account afterwards so we don't leave - // the execution's account behind on a reused thread. - RequestContext ctx = container.instance(RequestContext.class).get(); - String previousAccountId = alreadyActive ? ctx.getAccountId() : null; - try { - ctx.setAccountId(accountId); - return body.call(); - } finally { - if (!alreadyActive) { - requestContext.terminate(); - } else { - ctx.setAccountId(previousAccountId); - } - } + return RequestScopes.callAsChecked(accountId == null || accountId.isBlank() ? null : accountId, body); } private void doExecute(StateMachine sm, Execution exec, List history, @@ -1974,6 +1953,7 @@ public class AslExecutor { private JsonNode invokeDynamoDb(String operation, JsonNode input, String region) { String tableName = input.path("TableName").asText(); + Scope scope = dynamoDb.scope(region); switch (operation) { case "putItem" -> { JsonNode item = input.path("Item"); @@ -1983,12 +1963,12 @@ public class AslExecutor { ? input.get("ExpressionAttributeNames") : null; JsonNode exprAttrValues = input.has("ExpressionAttributeValues") ? input.get("ExpressionAttributeValues") : null; - dynamoDbService.putItem(tableName, item, conditionExpr, exprAttrNames, exprAttrValues, region, "NONE"); + dynamoDb.items().putItem(scope, tableName, item, conditionExpr, exprAttrNames, exprAttrValues); return objectMapper.createObjectNode(); } case "getItem" -> { JsonNode key = input.path("Key"); - JsonNode item = dynamoDbService.getItem(tableName, key, region); + JsonNode item = dynamoDb.items().getItem(scope, tableName, key); ObjectNode result = objectMapper.createObjectNode(); if (item != null) { result.set("Item", item); @@ -2003,7 +1983,7 @@ public class AslExecutor { ? input.get("ExpressionAttributeNames") : null; JsonNode exprAttrValues = input.has("ExpressionAttributeValues") ? input.get("ExpressionAttributeValues") : null; - dynamoDbService.deleteItem(tableName, key, conditionExpr, exprAttrNames, exprAttrValues, region, "NONE"); + dynamoDb.items().deleteItem(scope, tableName, key, conditionExpr, exprAttrNames, exprAttrValues); return objectMapper.createObjectNode(); } case "scan" -> { @@ -2015,10 +1995,10 @@ public class AslExecutor { ? input.get("ExpressionAttributeValues") : null; Integer limit = input.has("Limit") ? input.get("Limit").asInt() : null; JsonNode scanFilter = input.has("ScanFilter") ? input.get("ScanFilter") : null; - DynamoDbService.ScanResult scanResult = dynamoDbService.scan( - tableName, filterExpression, exprAttrNames, exprAttrValues, scanFilter, limit, null, null, region); + DynamoDbItemAccess.ScanPage scanResult = dynamoDb.items().scan( + scope, tableName, filterExpression, exprAttrNames, exprAttrValues, scanFilter, limit, null); ObjectNode response = objectMapper.createObjectNode(); - com.fasterxml.jackson.databind.node.ArrayNode items = objectMapper.createArrayNode(); + ArrayNode items = objectMapper.createArrayNode(); scanResult.items().forEach(items::add); response.set("Items", items); response.put("Count", scanResult.items().size()); @@ -2039,16 +2019,13 @@ public class AslExecutor { ? input.get("ConditionExpression").asText() : null; String returnValues = input.path("ReturnValues").asText("NONE"); - DynamoDbService.UpdateResult result = dynamoDbService.updateItem( - tableName, key, attributeUpdates, updateExpression, - exprAttrNames, exprAttrValues, returnValues, - conditionExpression, region, "NONE"); + JsonNode attributes = dynamoDb.items().updateItem( + scope, tableName, key, attributeUpdates, updateExpression, + exprAttrNames, exprAttrValues, returnValues, conditionExpression); ObjectNode response = objectMapper.createObjectNode(); - if ("ALL_NEW".equals(returnValues) && result.newItem() != null) { - response.set("Attributes", result.newItem()); - } else if ("ALL_OLD".equals(returnValues) && result.oldItem() != null) { - response.set("Attributes", result.oldItem()); + if (attributes != null) { + response.set("Attributes", attributes); } return response; } @@ -2075,9 +2052,6 @@ public class AslExecutor { int status = response.getStatus(); if (status >= 400) { - if (entity instanceof AwsErrorResponse err) { - throw new FailStateException("DynamoDb." + err.type(), err.message()); - } if (entity instanceof JsonNode errorNode) { String errorName = errorNode.path("__type").asText("UnknownError"); String errorMessage = errorNode.path("message").asText( diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java index cd66db7bec..4d544422f9 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java @@ -3,7 +3,9 @@ package io.github.hectorvent.floci.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.backend.NativeDynamoDbBackend; import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; import io.github.hectorvent.floci.services.ec2.Ec2Service; @@ -43,7 +45,7 @@ class IamConditionContextResolverTest { private final ObjectMapper mapper = new ObjectMapper(); private DynamoDbService dynamoDbService; - private Instance dynamoDbServiceInstance; + private Instance dynamoDbFacadeInstance; private Ec2Service ec2Service; private S3Service s3Service; private RequestContext requestContext; @@ -54,9 +56,11 @@ class IamConditionContextResolverTest { @BeforeEach void setUp() { dynamoDbService = mock(DynamoDbService.class); - dynamoDbServiceInstance = mock(Instance.class); - when(dynamoDbServiceInstance.isResolvable()).thenReturn(true); - when(dynamoDbServiceInstance.get()).thenReturn(dynamoDbService); + NativeDynamoDbBackend dynamoDbBackend = new NativeDynamoDbBackend(null, null, dynamoDbService, mapper); + dynamoDbFacadeInstance = mock(Instance.class); + when(dynamoDbFacadeInstance.isResolvable()).thenReturn(true); + when(dynamoDbFacadeInstance.get()).thenReturn(new DynamoDbFacade(dynamoDbBackend, dynamoDbBackend, + new RegionResolver("us-east-1", "000000000000"))); ec2Service = mock(Ec2Service.class); Instance ec2ServiceInstance = mock(Instance.class); when(ec2ServiceInstance.isResolvable()).thenReturn(true); @@ -70,7 +74,7 @@ class IamConditionContextResolverTest { config = mock(EmulatorConfig.class); when(config.defaultRegion()).thenReturn("us-east-1"); resolver = new IamConditionContextResolver( - dynamoDbServiceInstance, ec2ServiceInstance, s3ServiceInstance, requestContext, config); + dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, requestContext, config); } /** A form request whose body can be read again, as a real request's restored stream can. */ diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 200406f847..9ee2e15b0c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint; import io.github.hectorvent.floci.services.acm.AcmService; import io.github.hectorvent.floci.services.apigateway.ApiGatewayService; @@ -102,7 +103,9 @@ import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService; import io.github.hectorvent.floci.services.cognito.CognitoService; import io.github.hectorvent.floci.services.docdb.DocDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.backend.NativeDynamoDbBackend; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecr.EcrService; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -265,7 +268,9 @@ final class CfnProvisionerFixture { discovered.add(new SnsCfnProvisioner(snsService)); } if (dynamoDbService != null) { - discovered.add(new DynamoDbCfnProvisioner(dynamoDbService)); + NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDbService, objectMapper); + discovered.add(new DynamoDbCfnProvisioner(new DynamoDbFacade(backend, backend, + new RegionResolver("us-east-1", "000000000000")))); } if (ssmService != null) { discovered.add(new SsmCfnProvisioner(ssmService)); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java index 6d39784cbf..1d0b88d0fa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java @@ -3,9 +3,12 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.backend.NativeDynamoDbBackend; import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; import org.junit.jupiter.api.Test; @@ -42,8 +45,10 @@ class DynamoDbCfnProvisionerTest { private static final String STREAM_ARN = TABLE_ARN + "/stream/2026-01-01T00:00:00.000"; private final DynamoDbService dynamoDb = mock(DynamoDbService.class); - private final DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(dynamoDb); private final ObjectMapper mapper = new ObjectMapper(); + private final NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDb, mapper); + private final DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner( + new DynamoDbFacade(backend, backend, new RegionResolver("us-east-1", "000000000000"))); private ProvisionContext ctx() { CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGsiSortKeyRestartTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGsiSortKeyRestartTest.java index 84486b2a33..1ef2fcdd78 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGsiSortKeyRestartTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGsiSortKeyRestartTest.java @@ -42,10 +42,10 @@ class DynamoDbGsiSortKeyRestartTest { return store; } - private DynamoDbJsonHandler handlerFor(StorageBackend store) { + private NativeDynamoDbJsonHandler handlerFor(StorageBackend store) { DynamoDbService service = new DynamoDbService( store, null, new RegionResolver(REGION, "000000000000"), null, null); - return new DynamoDbJsonHandler(service, null, null, mapper); + return new NativeDynamoDbJsonHandler(service, null, null, mapper); } private ObjectNode createTableWithGsiSortKeyRequest() { @@ -82,7 +82,7 @@ class DynamoDbGsiSortKeyRestartTest { void otherTablesSurviveEvenWhenOneHasAGsiRangeKey(@TempDir Path tmp) throws Exception { Path file = tmp.resolve("dynamodb-tables.json"); StorageBackend store = diskStore(file); - DynamoDbJsonHandler handler = handlerFor(store); + NativeDynamoDbJsonHandler handler = handlerFor(store); handler.handle("CreateTable", createTableWithGsiSortKeyRequest(), REGION); ObjectNode plainTable = mapper.createObjectNode(); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbItemSizeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbItemSizeServiceTest.java index c46c7d8b7c..15d3eb1d02 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbItemSizeServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbItemSizeServiceTest.java @@ -34,12 +34,12 @@ class DynamoDbItemSizeServiceTest { private static final int SHORT_KEY_BYTES = 3; private DynamoDbService service; - private DynamoDbJsonHandler handler; + private NativeDynamoDbJsonHandler handler; @BeforeEach void setUp() { service = new DynamoDbService(new InMemoryStorage<>()); - handler = new DynamoDbJsonHandler(service, null, null, new ObjectMapper()); + handler = new NativeDynamoDbJsonHandler(service, null, null, new ObjectMapper()); service.createTable(TABLE, List.of(new KeySchemaElement("pk", "HASH")), List.of(new AttributeDefinition("pk", "S")), 5L, 5L, REGION); } diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamViewTypeDurabilityTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamViewTypeDurabilityTest.java index 7f79d856c3..d93e4ed5c4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamViewTypeDurabilityTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamViewTypeDurabilityTest.java @@ -42,11 +42,11 @@ class DynamoDbStreamViewTypeDurabilityTest { return store; } - private DynamoDbJsonHandler handlerFor(StorageBackend store, + private NativeDynamoDbJsonHandler handlerFor(StorageBackend store, DynamoDbStreamService streams) { DynamoDbService service = new DynamoDbService( store, null, new RegionResolver(REGION, "000000000000"), streams, null); - return new DynamoDbJsonHandler(service, streams, null, mapper); + return new NativeDynamoDbJsonHandler(service, streams, null, mapper); } private ObjectNode createTableRequest(String viewType) { @@ -92,7 +92,7 @@ class DynamoDbStreamViewTypeDurabilityTest { Path file = tmp.resolve("tables.json"); StorageBackend store = diskStore(file); DynamoDbStreamService streams = new DynamoDbStreamService(mapper, store); - DynamoDbJsonHandler handler = handlerFor(store, streams); + NativeDynamoDbJsonHandler handler = handlerFor(store, streams); handler.handle("CreateTable", createTableRequest("NEW_AND_OLD_IMAGES"), REGION); handler.handle("UpdateTable", updateViewTypeRequest("KEYS_ONLY"), REGION); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandlerTest.java similarity index 99% rename from src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java rename to src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandlerTest.java index 83f32015f7..5c743fb980 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandlerTest.java @@ -28,17 +28,17 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.*; -class DynamoDbJsonHandlerTest { +class NativeDynamoDbJsonHandlerTest { private DynamoDbService service; private ObjectMapper mapper; - private DynamoDbJsonHandler handler; + private NativeDynamoDbJsonHandler handler; @BeforeEach void setUp() { service = new DynamoDbService(new InMemoryStorage<>()); mapper = new ObjectMapper(); - handler = new DynamoDbJsonHandler(service, null, null, mapper); + handler = new NativeDynamoDbJsonHandler(service, null, null, mapper); } private TableDefinition createUsersTable(String region) { @@ -368,7 +368,7 @@ class DynamoDbJsonHandlerTest { TypeReference> typeReference = new TypeReference<>() {}; DynamoDbService persistentService = new DynamoDbService(new PersistentStorage<>(tableFile, typeReference)); - DynamoDbJsonHandler persistentHandler = new DynamoDbJsonHandler(persistentService, null, null, mapper); + NativeDynamoDbJsonHandler persistentHandler = new NativeDynamoDbJsonHandler(persistentService, null, null, mapper); ObjectNode createRequest = mapper.createObjectNode(); createRequest.put("TableName", "PersistedSseTable"); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelectionTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelectionTest.java new file mode 100644 index 0000000000..8f24febc52 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbBackendSelectionTest.java @@ -0,0 +1,90 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.resource.ResourceProvider; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; +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.Scope; +import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; +import io.quarkus.arc.ClientProxy; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** The one DynamoDB backend CDI selects, and the one Resource Explorer provider in front of it. */ +@QuarkusTest +class DynamoDbBackendSelectionTest { + + private static final String REGION = "us-east-1"; + private static final Scope ACCOUNT_A = new Scope("210987654321", REGION); + private static final Scope ACCOUNT_B = new Scope("321098765432", REGION); + + @Inject + DynamoDbOperations operations; + + @Inject + DynamoDbItemAccess items; + + @Inject + DynamoDbTableAccess tables; + + // Collected exactly as ResourceExplorer2Service collects its providers. + @Inject + Instance providers; + + @Inject + ObjectMapper mapper; + + @Test + void everyCapabilityIsTheOneNativeBackend() { + Object backend = ClientProxy.unwrap(operations); + + assertInstanceOf(NativeDynamoDbBackend.class, backend); + assertSame(backend, ClientProxy.unwrap(items)); + assertSame(backend, ClientProxy.unwrap(tables)); + } + + @Test + void theFacadeIsTheOnlyDynamoDbTableProvider() { + List dynamoDbProviders = providers.stream() + .filter(provider -> provider.getSupportedResourceTypes().stream() + .anyMatch(type -> "dynamodb:table".equals(type.resourceType()))) + .toList(); + + assertEquals(1, dynamoDbProviders.size()); + assertInstanceOf(DynamoDbFacade.class, ClientProxy.unwrap(dynamoDbProviders.get(0))); + } + + @Test + void callsRunUnderTheScopeAccount() throws Exception { + String tableName = "backend-scope-" + UUID.randomUUID(); + tables.createTable(ACCOUNT_A, tableName, List.of(new KeySchemaElement("id", "HASH")), + List.of(new AttributeDefinition("id", "S")), 5L, 5L, List.of(), List.of()); + try { + assertTrue(tables.findTable(ACCOUNT_B, tableName).isEmpty()); + assertTrue(tables.findTable(ACCOUNT_A, tableName).isPresent()); + + ObjectNode body = mapper.createObjectNode().put("TableName", tableName); + AwsException notFound = assertThrows(AwsException.class, + () -> operations.execute(new Call(ACCOUNT_B, Api.DYNAMODB, "DescribeTable", body))); + assertEquals("ResourceNotFoundException", notFound.getErrorCode()); + assertEquals(200, operations.execute(new Call(ACCOUNT_A, Api.DYNAMODB, "DescribeTable", body)).status()); + } finally { + tables.deleteTable(ACCOUNT_A, tableName); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java new file mode 100644 index 0000000000..dfa88e4f5f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java @@ -0,0 +1,199 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.FlociCertificateAuthority; +import io.github.hectorvent.floci.core.common.IamConditionContextResolver; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.resource.SupportedResourceType; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.DynamoDbCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext; +import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; +import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend.Invocation; +import io.github.hectorvent.floci.services.firehose.FirehoseService; +import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator; +import io.github.hectorvent.floci.services.iot.IotMqttBrokerService; +import io.github.hectorvent.floci.services.iot.IotPublishEventRecorder; +import io.github.hectorvent.floci.services.iot.IotService; +import io.github.hectorvent.floci.services.kinesis.KinesisService; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.sns.SnsService; +import io.github.hectorvent.floci.services.sqs.SqsService; +import jakarta.enterprise.inject.Instance; +import jakarta.ws.rs.container.ContainerRequestContext; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The facade Java consumers of DynamoDB reach the engine through: it hands out the selected + * capabilities, scopes to the ambient account, and each consumer gives it the account and region + * it means. Every case runs against a recording backend, so nothing here touches native state. + */ +class DynamoDbFacadeTest { + + private static final String DEFAULT_ACCOUNT = "000000000000"; + private static final String DEFAULT_REGION = "us-east-1"; + private static final String OWNER_ACCOUNT = "111122223333"; + private static final String OTHER_REGION = "eu-west-1"; + + private final ObjectMapper mapper = new ObjectMapper(); + private final RecordingDynamoDbBackend backend = new RecordingDynamoDbBackend(); + private final DynamoDbFacade facade = + new DynamoDbFacade(backend, backend, new RegionResolver(DEFAULT_REGION, DEFAULT_ACCOUNT)); + + @Test + void scopeIsTheAmbientAccountInTheGivenRegion() { + assertEquals(new Scope(DEFAULT_ACCOUNT, OTHER_REGION), facade.scope(OTHER_REGION)); + } + + @Test + void resourcesAreListedForTheAmbientAccount() { + assertEquals(List.of(RecordingDynamoDbBackend.RESOURCE), facade.getResources()); + assertEquals(List.of(new Invocation("resources", DEFAULT_ACCOUNT, null)), backend.invocations()); + } + + @Test + void supportedResourceTypeIsTheDynamoDbTable() { + assertEquals(Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true)), + facade.getSupportedResourceTypes()); + } + + @Test + void capabilitiesAreTheSelectedOnes() { + RecordingDynamoDbBackend items = new RecordingDynamoDbBackend(); + RecordingDynamoDbBackend tables = new RecordingDynamoDbBackend(); + DynamoDbFacade split = new DynamoDbFacade(items, tables, new RegionResolver(DEFAULT_REGION, DEFAULT_ACCOUNT)); + + assertSame(items, split.items()); + assertSame(tables, split.tables()); + } + + @Test + void cloudFormationTableUsesTheStackRegion() throws Exception { + DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(facade); + StackResource table = cfnResource("Orders", "AWS::DynamoDB::Table"); + + provisioner.provision(table, mapper.readTree("{\"TableName\":\"orders\"}"), + cfnContext(DEFAULT_ACCOUNT, OTHER_REGION)); + provisioner.delete("AWS::DynamoDB::Table", "orders", OTHER_REGION); + + assertEquals(List.of( + new Invocation("createTable", DEFAULT_ACCOUNT, OTHER_REGION), + new Invocation("listTagsOfResource", DEFAULT_ACCOUNT, OTHER_REGION), + new Invocation("deleteTable", DEFAULT_ACCOUNT, OTHER_REGION)), backend.invocations()); + } + + @Test + void cloudFormationProvisionsUnderTheStackAccountRatherThanTheAmbientOne() throws Exception { + DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(facade); + ProvisionContext stack = cfnContext(OWNER_ACCOUNT, OTHER_REGION); + + provisioner.provision(cfnResource("Orders", "AWS::DynamoDB::GlobalTable"), mapper.readTree(""" + {"TableName": "orders", "Replicas": [{"Region": "us-west-2"}]} + """), stack); + provisioner.provision(cfnResource("OrdersReplica", "Custom::DynamoDBReplica"), mapper.readTree(""" + {"TableName": "orders", "Region": "ap-south-1"} + """), stack); + + assertEquals(List.of( + new Invocation("createTable", OWNER_ACCOUNT, OTHER_REGION), + new Invocation("listTagsOfResource", OWNER_ACCOUNT, OTHER_REGION), + new Invocation("describeTable", OWNER_ACCOUNT, OTHER_REGION), + new Invocation("ensureGlobalTable", OWNER_ACCOUNT, OTHER_REGION), + new Invocation("applyReplicaUpdates", OWNER_ACCOUNT, OTHER_REGION), + new Invocation("applyReplicaUpdates", OWNER_ACCOUNT, OTHER_REGION)), backend.invocations()); + } + + @Test + void iotDynamoDbRuleActionWritesAsTheRuleOwnerInTheRuleRegion() throws Exception { + // The rule is created by OWNER_ACCOUNT in OTHER_REGION, then fires with no request account, + // as an MQTT publish does: the action must write as the rule's owner, not the ambient default. + IotService iot = iotService(new RegionResolver(OTHER_REGION, OWNER_ACCOUNT)); + iot.createTopicRule("toTable", mapper.readTree(""" + {"sql": "SELECT * FROM 'devices/+/metrics'", + "actions": [{"dynamoDBv2": {"putItem": {"tableName": "metrics"}, + "roleArn": "arn:aws:iam::111122223333:role/rule"}}]} + """), OTHER_REGION); + + iot.publish("devices/d1/metrics", "{\"t\":1}".getBytes(StandardCharsets.UTF_8), false, 0, null, "sensor-1"); + + assertEquals(List.of(new Invocation("putItem", OWNER_ACCOUNT, OTHER_REGION)), backend.invocations()); + } + + @Test + @SuppressWarnings("unchecked") + void iamConditionContextFindsTheTableInTheRequestRegion() throws Exception { + Instance dynamoDb = mock(Instance.class); + when(dynamoDb.isResolvable()).thenReturn(true); + when(dynamoDb.get()).thenReturn(facade); + RequestContext requestContext = new RequestContext(); + requestContext.setRegion(OTHER_REGION); + IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb, + mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class)); + ContainerRequestContext request = mock(ContainerRequestContext.class); + JsonNode body = mapper.readTree(""" + {"TableName": "recorded-table", "Key": {"id": {"S": "USER_alice"}}} + """); + when(request.getProperty("floci.bufferedJsonBody")).thenReturn(body); + + Map> conditions = resolver.resolve("dynamodb", "dynamodb:GetItem", request); + + assertEquals(List.of("USER_alice"), conditions.get("dynamodb:LeadingKeys")); + assertEquals(List.of(new Invocation("findTable", DEFAULT_ACCOUNT, OTHER_REGION)), backend.invocations()); + } + + private StackResource cfnResource(String logicalId, String type) { + StackResource resource = new StackResource(); + resource.setLogicalId(logicalId); + resource.setResourceType(type); + resource.setAttributes(new HashMap<>()); + return resource; + } + + private ProvisionContext cfnContext(String accountId, String region) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> { + JsonNode node = invocation.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0)); + return new ProvisionContext(engine, region, accountId, "stack"); + } + + private IotService iotService(RegionResolver regionResolver) { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT)); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.defaultRegion()).thenReturn(DEFAULT_REGION); + when(config.defaultAccountId()).thenReturn(DEFAULT_ACCOUNT); + when(config.services().iot().ruleSqlStrict()).thenReturn(false); + return new IotService(storageFactory, config, regionResolver, mapper, new IotPublishEventRecorder(), + mock(IotMqttBrokerService.class), mock(SqsService.class), mock(SnsService.class), + mock(S3Service.class), mock(KinesisService.class), facade, mock(LambdaService.class), + mock(FirehoseService.class), mock(CloudWatchLogsService.class), + mock(FlociCertificateAuthority.class), new IamPolicyEvaluator(mapper)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java new file mode 100644 index 0000000000..fa1fbe7cb7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java @@ -0,0 +1,195 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.KinesisStreamingForwarder; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbStreamsJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService; +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 io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; +import io.github.hectorvent.floci.services.kinesis.KinesisService; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** The native engine behind the DynamoDB seam, and the thin public handlers in front of it. */ +class DynamoDbNativeBackendTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final Scope SCOPE = new Scope(ACCOUNT, REGION); + private static final String TABLE = "orders"; + + private final ObjectMapper mapper = new ObjectMapper(); + private NativeDynamoDbBackend backend; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT)); + DynamoDbStreamService streams = new DynamoDbStreamService(mapper, storageFactory); + DynamoDbService service = new DynamoDbService(storageFactory, new RegionResolver(REGION, ACCOUNT), streams, + mock(KinesisStreamingForwarder.class), null, mapper, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS)); + NativeDynamoDbTableService tables = new NativeDynamoDbTableService(service, streams, mock(KinesisService.class)); + backend = new NativeDynamoDbBackend(new NativeDynamoDbJsonHandler(service, tables, mapper), + new NativeDynamoDbStreamsJsonHandler(streams, service, mapper), service, mapper); + } + + private Reply call(Api api, String action, JsonNode body) throws Exception { + return backend.execute(new Call(SCOPE, api, action, body)); + } + + private Reply createTable(String extraFields) throws Exception { + return call(Api.DYNAMODB, "CreateTable", json(""" + {"TableName":"%s", + "KeySchema":[{"AttributeName":"id","KeyType":"HASH"}], + "AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"}], + "BillingMode":"PAY_PER_REQUEST"%s} + """.formatted(TABLE, extraFields))); + } + + private JsonNode json(String text) throws Exception { + return mapper.readTree(text); + } + + @Test + void rawDeleteTableHonoursDeletionProtectionWhileTypedDeleteDoesNot() throws Exception { + createTable(",\"DeletionProtectionEnabled\":true"); + + AwsException refused = assertThrows(AwsException.class, + () -> call(Api.DYNAMODB, "DeleteTable", json("{\"TableName\":\"" + TABLE + "\"}"))); + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(backend.findTable(SCOPE, TABLE).isPresent()); + + backend.deleteTable(SCOPE, TABLE); + + assertTrue(backend.findTable(SCOPE, TABLE).isEmpty()); + } + + @Test + void typedUpdateItemReturnsOnlyTheRequestedImage() throws Exception { + backend.createTable(SCOPE, TABLE, List.of(new KeySchemaElement("id", "HASH")), + List.of(new AttributeDefinition("id", "S")), 5L, 5L, List.of(), List.of()); + JsonNode key = json("{\"id\":{\"S\":\"k\"}}"); + backend.putItem(SCOPE, TABLE, json("{\"id\":{\"S\":\"k\"},\"n\":{\"N\":\"1\"}}"), null, null, null); + JsonNode names = json("{\"#n\":\"n\"}"); + + JsonNode newImage = backend.updateItem(SCOPE, TABLE, key, null, "SET #n = :v", names, + json("{\":v\":{\"N\":\"2\"}}"), "ALL_NEW", null); + JsonNode oldImage = backend.updateItem(SCOPE, TABLE, key, null, "SET #n = :v", names, + json("{\":v\":{\"N\":\"3\"}}"), "ALL_OLD", null); + JsonNode none = backend.updateItem(SCOPE, TABLE, key, null, "SET #n = :v", names, + json("{\":v\":{\"N\":\"4\"}}"), "NONE", null); + JsonNode updatedNew = backend.updateItem(SCOPE, TABLE, key, null, "SET #n = :v", names, + json("{\":v\":{\"N\":\"5\"}}"), "UPDATED_NEW", null); + + assertEquals(json("{\"id\":{\"S\":\"k\"},\"n\":{\"N\":\"2\"}}"), newImage); + assertEquals(json("{\"id\":{\"S\":\"k\"},\"n\":{\"N\":\"2\"}}"), oldImage); + assertNull(none); + assertNull(updatedNew); + assertEquals(json("{\"id\":{\"S\":\"k\"},\"n\":{\"N\":\"5\"}}"), backend.getItem(SCOPE, TABLE, key)); + } + + @Test + void unknownActionRepliesWithAJsonErrorBody() throws Exception { + Reply reply = call(Api.DYNAMODB, "NoSuchAction", mapper.createObjectNode()); + + assertEquals(400, reply.status()); + assertEquals("UnknownOperationException", reply.body().path("__type").asText()); + assertEquals("Operation NoSuchAction is not supported.", reply.body().path("message").asText()); + } + + @Test + void rawCallsRoundTripAnItem() throws Exception { + JsonNode item = json("{\"id\":{\"S\":\"a\"},\"v\":{\"S\":\"x\"}}"); + + assertEquals(200, createTable("").status()); + ObjectNode put = mapper.createObjectNode().put("TableName", TABLE); + put.set("Item", item); + assertEquals(200, call(Api.DYNAMODB, "PutItem", put).status()); + ObjectNode get = mapper.createObjectNode().put("TableName", TABLE); + get.set("Key", json("{\"id\":{\"S\":\"a\"}}")); + Reply reply = call(Api.DYNAMODB, "GetItem", get); + + assertEquals(200, reply.status()); + assertEquals(item, reply.body().path("Item")); + } + + @Test + void streamsCallsReachTheStreamsHandler() throws Exception { + createTable(",\"StreamSpecification\":{\"StreamEnabled\":true,\"StreamViewType\":\"NEW_IMAGE\"}"); + + Reply reply = call(Api.DYNAMODB_STREAMS, "ListStreams", mapper.createObjectNode()); + + assertEquals(200, reply.status()); + assertTrue(reply.body().path("Streams").isArray()); + assertEquals(TABLE, reply.body().path("Streams").path(0).path("TableName").asText()); + } + + @Test + void scopeRejectsBlankAccountAndRegion() { + IllegalArgumentException account = assertThrows(IllegalArgumentException.class, () -> new Scope(" ", REGION)); + IllegalArgumentException region = assertThrows(IllegalArgumentException.class, () -> new Scope(ACCOUNT, "")); + + assertTrue(account.getMessage().contains("accountId")); + assertTrue(region.getMessage().contains("region")); + assertThrows(IllegalArgumentException.class, () -> new Scope(null, REGION)); + assertThrows(IllegalArgumentException.class, () -> new Scope(ACCOUNT, null)); + } + + @Test + void thinHandlersPassTheCallersScopeAndRebuildTheReply() throws Exception { + List calls = new ArrayList<>(); + JsonNode replyBody = json("{\"ok\":true}"); + DynamoDbOperations recording = call -> { + calls.add(call); + return new Reply(201, replyBody, Map.of("X-Test", List.of("a", "b"))); + }; + RegionResolver resolver = new RegionResolver("eu-west-1", "111122223333"); + JsonNode request = mapper.createObjectNode(); + + Response response = new DynamoDbJsonHandler(recording, resolver).handle("GetItem", request, "ap-south-1"); + new DynamoDbJsonHandler(recording, resolver).handle("GetItem", request, null); + new DynamoDbStreamsJsonHandler(recording, resolver).handle("ListStreams", request, "ap-south-1"); + + assertEquals(new Call(new Scope("111122223333", "ap-south-1"), Api.DYNAMODB, "GetItem", request), + calls.get(0)); + assertSame(request, calls.get(0).body()); + assertEquals(new Scope("111122223333", "eu-west-1"), calls.get(1).scope()); + assertEquals(Api.DYNAMODB_STREAMS, calls.get(2).api()); + assertEquals(201, response.getStatus()); + assertSame(replyBody, response.getEntity()); + assertEquals(List.of("a", "b"), response.getStringHeaders().get("X-Test")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java new file mode 100644 index 0000000000..05f110463d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java @@ -0,0 +1,151 @@ +package io.github.hectorvent.floci.services.dynamodb.backend; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.resource.ExplorerResource; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; +import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex; +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.TableDefinition; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * A DynamoDB backend with no state: each typed call is recorded with the account and region it + * was given and answered with a canned value, so a test can see exactly what a consumer asked for. + */ +public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, DynamoDbTableAccess { + + /** One typed call. {@code region} is null for {@code resources}, which takes an account only. */ + public record Invocation(String method, String accountId, String region) { + + public static Invocation of(String method, Scope scope) { + return new Invocation(method, scope.accountId(), scope.region()); + } + } + + public static final String TABLE_NAME = "recorded-table"; + public static final String TABLE_ARN = "arn:aws:dynamodb:us-east-1:000000000000:table/" + TABLE_NAME; + public static final ExplorerResource RESOURCE = new ExplorerResource(TABLE_ARN, "dynamodb:table", "dynamodb", + "us-east-1", "000000000000", Instant.EPOCH, Map.of()); + + private final List invocations = new CopyOnWriteArrayList<>(); + + public List invocations() { + return List.copyOf(invocations); + } + + private TableDefinition record(String method, Scope scope) { + invocations.add(Invocation.of(method, scope)); + TableDefinition table = new TableDefinition(); + table.setTableName(TABLE_NAME); + table.setTableArn(TABLE_ARN); + table.setKeySchema(List.of(new KeySchemaElement("id", "HASH"))); + return table; + } + + @Override + public void putItem(Scope scope, String tableName, JsonNode item, String conditionExpression, + JsonNode expressionAttributeNames, JsonNode expressionAttributeValues) { + record("putItem", scope); + } + + @Override + public JsonNode getItem(Scope scope, String tableName, JsonNode key) { + record("getItem", scope); + return null; + } + + @Override + public void deleteItem(Scope scope, String tableName, JsonNode key, String conditionExpression, + JsonNode expressionAttributeNames, JsonNode expressionAttributeValues) { + record("deleteItem", scope); + } + + @Override + public JsonNode updateItem(Scope scope, String tableName, JsonNode key, JsonNode attributeUpdates, + String updateExpression, JsonNode expressionAttributeNames, + JsonNode expressionAttributeValues, String returnValues, String conditionExpression) { + record("updateItem", scope); + return null; + } + + @Override + public ScanPage scan(Scope scope, String tableName, String filterExpression, JsonNode expressionAttributeNames, + JsonNode expressionAttributeValues, JsonNode scanFilter, Integer limit, + JsonNode exclusiveStartKey) { + record("scan", scope); + return new ScanPage(List.of(), 0, null); + } + + @Override + public TableDefinition createTable(Scope scope, String tableName, List keySchema, + List attributeDefinitions, Long readCapacity, + Long writeCapacity, List globalSecondaryIndexes, + List localSecondaryIndexes) { + return record("createTable", scope); + } + + @Override + public TableDefinition describeTable(Scope scope, String tableName) { + return record("describeTable", scope); + } + + @Override + public Optional findTable(Scope scope, String tableName) { + return Optional.of(record("findTable", scope)); + } + + @Override + public void deleteTable(Scope scope, String tableName) { + record("deleteTable", scope); + } + + @Override + public TableDefinition enableStream(Scope scope, String tableName, String viewType) { + return record("enableStream", scope); + } + + @Override + public TableDefinition disableStream(Scope scope, String tableName) { + return record("disableStream", scope); + } + + @Override + public Map listTagsOfResource(Scope scope, String resourceArn) { + record("listTagsOfResource", scope); + return Map.of(); + } + + @Override + public void tagResource(Scope scope, String resourceArn, Map tags) { + record("tagResource", scope); + } + + @Override + public void untagResource(Scope scope, String resourceArn, List tagKeys) { + record("untagResource", scope); + } + + @Override + public TableDefinition applyReplicaUpdates(Scope scope, String tableName, List addRegions, + List removeRegions) { + return record("applyReplicaUpdates", scope); + } + + @Override + public TableDefinition ensureGlobalTable(Scope scope, String tableName) { + return record("ensureGlobalTable", scope); + } + + @Override + public List resources(String accountId) { + invocations.add(new Invocation("resources", accountId, null)); + return List.of(RESOURCE); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java index 1faa712958..0ddbf43887 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java @@ -8,7 +8,10 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbItemAccess; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope; +import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbTableAccess; import io.github.hectorvent.floci.services.firehose.FirehoseService; import io.github.hectorvent.floci.services.firehose.model.Record; import io.github.hectorvent.floci.services.iot.model.IotPolicy; @@ -42,6 +45,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -68,7 +72,7 @@ class IotServiceTest { private final ObjectMapper mapper = new ObjectMapper(); private final SqsService sqs = mock(SqsService.class); private final LambdaService lambda = mock(LambdaService.class); - private final DynamoDbService dynamoDb = mock(DynamoDbService.class); + private final DynamoDbItemAccess dynamoDb = mock(DynamoDbItemAccess.class); private final FirehoseService firehose = mock(FirehoseService.class); private final CloudWatchLogsService logs = mock(CloudWatchLogsService.class); private IotService service; @@ -101,7 +105,7 @@ class IotServiceTest { mock(SnsService.class), mock(S3Service.class), mock(KinesisService.class), - dynamoDb, + new DynamoDbFacade(dynamoDb, mock(DynamoDbTableAccess.class), new RegionResolver(REGION, ACCOUNT)), lambda, firehose, logs, @@ -452,7 +456,8 @@ class IotServiceTest { private JsonNode capturedDynamoDbItem(String tableName) { ArgumentCaptor item = ArgumentCaptor.forClass(ObjectNode.class); - verify(dynamoDb).putItem(eq(tableName), item.capture(), eq(REGION)); + verify(dynamoDb).putItem(eq(new Scope(ACCOUNT, REGION)), eq(tableName), item.capture(), + isNull(), isNull(), isNull()); return item.getValue(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTestSupport.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTestSupport.java index fb9176c7fb..12579bf540 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTestSupport.java +++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTestSupport.java @@ -7,7 +7,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.firehose.FirehoseService; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator; import io.github.hectorvent.floci.services.iot.model.IotCertificate; @@ -74,7 +74,7 @@ final class IotServiceTestSupport { mock(SnsService.class), mock(S3Service.class), mock(KinesisService.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(LambdaService.class), mock(FirehoseService.class), mock(CloudWatchLogsService.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java index 7610d7a966..0420cdcb3d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java @@ -3,9 +3,13 @@ package io.github.hectorvent.floci.services.redshift; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; 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.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService; +import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend; +import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend.Invocation; import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord; import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; @@ -39,6 +43,9 @@ class RedshiftDynamoDbZeroEtlConsumerTest { @Inject DynamoDbService dynamoDbService; + @Inject + DynamoDbFacade dynamoDb; + @Test void writesRecordsAndAdvancesCheckpointOnlyAfterSuccessfulBatch() { DynamoDbStreamService streamService = mock(DynamoDbStreamService.class); @@ -58,7 +65,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest { .thenReturn(record.getSequenceNumber()); RedshiftDynamoDbZeroEtlConsumer consumer = - new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer); + new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer); consumer.pollOnce(integration); verify(writer).createLandingTable(integration.getAccountId(), "warehouse", "floci_zetl_orders"); @@ -92,7 +99,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest { assertThrows(AwsException.class, () -> dynamoDbService.describeTable(tableName, "us-east-1")); RedshiftDynamoDbZeroEtlConsumer consumer = - new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer); + new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer); consumer.pollOnce(integration); assertFalse(integration.isBackfillCompleted()); @@ -129,7 +136,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest { assertThrows(AwsException.class, () -> dynamoDbService.describeTable(tableName, "us-east-1")); RedshiftDynamoDbZeroEtlConsumer consumer = - new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer); + new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer); consumer.pollOnce(integration); assertTrue(integration.isBackfillCompleted()); @@ -156,7 +163,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest { }); RedshiftDynamoDbZeroEtlConsumer consumer = - new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer); + new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDb, redshiftService, writer); consumer.pollOnce(integration); integration.setBackfillCompleted(false); consumer.pollOnce(integration); @@ -168,6 +175,21 @@ class RedshiftDynamoDbZeroEtlConsumerTest { captor.getAllValues().get(1).get(0).getEventId()); } + @Test + void backfillReadsTheTableAsTheIntegrationAccountInTheStreamRegion() { + RecordingDynamoDbBackend backend = new RecordingDynamoDbBackend(); + DynamoDbFacade recording = new DynamoDbFacade(backend, backend, new RegionResolver("us-east-1", "000000000000")); + Integration integration = integration("orders"); + integration.setSourceStreamArn("arn:aws:dynamodb:eu-west-1:111111111111:table/orders/stream/one"); + + new RedshiftDynamoDbZeroEtlConsumer(mock(DynamoDbStreamService.class), recording, + mock(RedshiftService.class), mock(RedshiftZeroEtlWriter.class)).pollOnce(integration); + + assertEquals(List.of( + new Invocation("describeTable", "111111111111", "eu-west-1"), + new Invocation("scan", "111111111111", "eu-west-1")), backend.invocations()); + } + private static ObjectNode itemWithId(String id) { ObjectNode item = MAPPER.createObjectNode(); ObjectNode idAttr = MAPPER.createObjectNode(); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayAndMathIntrinsicsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayAndMathIntrinsicsTest.java index d75d082185..327566336c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayAndMathIntrinsicsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayAndMathIntrinsicsTest.java @@ -4,8 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -53,7 +53,7 @@ class AslExecutorArrayAndMathIntrinsicsTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorBranchHistoryEventsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorBranchHistoryEventsTest.java index f6244ec5aa..72aae4e4bb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorBranchHistoryEventsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorBranchHistoryEventsTest.java @@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -67,7 +67,7 @@ class AslExecutorBranchHistoryEventsTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java index 1330516f07..e10b1256fe 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -83,7 +83,7 @@ class AslExecutorCatchTest { executor = new AslExecutor( lambdaExecutor, functionStore, - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorChoiceRuntimeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorChoiceRuntimeTest.java index cf0e74356f..1c440d93b7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorChoiceRuntimeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorChoiceRuntimeTest.java @@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -46,7 +46,7 @@ class AslExecutorChoiceRuntimeTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCustomResourceLivenessTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCustomResourceLivenessTest.java index 6e2517f17b..a69d0e6661 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCustomResourceLivenessTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCustomResourceLivenessTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.CustomResourceLiveness; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -77,7 +77,7 @@ class AslExecutorCustomResourceLivenessTest { executor = new AslExecutor( lambdaExecutor, functionStore, - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java index c7b6762e4e..cc1886da4b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy; @@ -65,7 +65,7 @@ class AslExecutorEcsRunTaskModeTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java index 73755408f0..73f955b822 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -75,7 +75,7 @@ class AslExecutorErrorTerminationTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFailStateErrorCauseTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFailStateErrorCauseTest.java index d0742136ad..cea21b4107 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFailStateErrorCauseTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFailStateErrorCauseTest.java @@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -53,7 +53,7 @@ class AslExecutorFailStateErrorCauseTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(io.github.hectorvent.floci.services.sns.SnsJsonHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHistoryEventLimitTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHistoryEventLimitTest.java index b88284f30f..349e5d2bb6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHistoryEventLimitTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHistoryEventLimitTest.java @@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -190,7 +190,7 @@ class AslExecutorHistoryEventLimitTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java index 85fddde727..759d5b6a75 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; @@ -162,7 +162,7 @@ class AslExecutorHttpInvokeTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicFunctionsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicFunctionsTest.java index 0ccb9b19d7..366768793d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicFunctionsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicFunctionsTest.java @@ -5,8 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -56,7 +56,7 @@ class AslExecutorIntrinsicFunctionsTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicMissingArgumentTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicMissingArgumentTest.java index af14abc139..67dce70661 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicMissingArgumentTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicMissingArgumentTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.sns.SnsJsonHandler; @@ -36,7 +36,7 @@ class AslExecutorIntrinsicMissingArgumentTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java index 951680a08b..6f87c6b083 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java @@ -4,8 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -41,7 +41,7 @@ class AslExecutorJsonMergeTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java index 8bbb67082c..17b3cbfd84 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaAliasStore; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; @@ -86,7 +86,7 @@ class AslExecutorLambdaInvokeResultTest { executor = new AslExecutor( lambdaExecutor, new LambdaTargetResolver(functionStore, aliasStore), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java index bd200cf8da..b71c86502f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -56,7 +56,7 @@ class AslExecutorMockedResponsesTest { executor = new AslExecutor( lambdaExecutor, mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedQueryLanguageTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedQueryLanguageTest.java index a938daed97..58afdb2f4f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedQueryLanguageTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedQueryLanguageTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -60,7 +60,7 @@ class AslExecutorNestedQueryLanguageTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java index 489c82e297..558b053606 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -72,7 +72,7 @@ class AslExecutorNestedStartExecutionTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java index 94a682427a..4ad4413d84 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.sns.SnsJsonHandler; @@ -35,7 +35,7 @@ class AslExecutorPathIntrinsicsTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultPathTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultPathTest.java index d9697788e0..2206fed367 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultPathTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultPathTest.java @@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -45,7 +45,7 @@ class AslExecutorResultPathTest { void setUp() { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(CloudFormationQueryHandler.class), mock(Ec2Service.class), mock(S3Service.class), mock(EcsService.class), mock(EcsJsonHandler.class), mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java index 8123d3597c..bcea754cd4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java @@ -6,8 +6,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -62,7 +62,7 @@ class AslExecutorResultWriterTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java index 474fa64ea1..8b726afeab 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java @@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -77,7 +77,7 @@ class AslExecutorRetryTest { executor = new AslExecutor( lambdaExecutor, functionStore, - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorStatePathTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorStatePathTest.java index c0b7852ab2..4a2d1342ce 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorStatePathTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorStatePathTest.java @@ -4,8 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -39,7 +39,7 @@ class AslExecutorStatePathTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java index 3d050de6e4..2252436fab 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java @@ -2,8 +2,11 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend; +import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend.Invocation; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -59,17 +62,24 @@ class AslExecutorTaskHistoryEventsTest { @Inject Vertx vertx; + @Inject + RegionResolver regionResolver; + @BeforeEach void setUp() { lambdaExecutor = mock(LambdaExecutorService.class); functionStore = mock(LambdaFunctionStore.class); + executor = newExecutor(mock(DynamoDbFacade.class)); + } + + private AslExecutor newExecutor(DynamoDbFacade dynamoDb) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30); - executor = new AslExecutor( + return new AslExecutor( lambdaExecutor, functionStore, - mock(DynamoDbService.class), + dynamoDb, mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), @@ -86,6 +96,36 @@ class AslExecutorTaskHistoryEventsTest { mock(io.github.hectorvent.floci.core.common.CustomResourceLiveness.class)); } + /** + * The optimized DynamoDB integration scopes to the ambient account, which the executor sets to + * the one in the state machine ARN, and to the state machine's region. + */ + @Test + void optimizedDynamoDbTaskRunsAsTheExecutionAccountInTheStateMachineRegion() { + RecordingDynamoDbBackend backend = new RecordingDynamoDbBackend(); + AslExecutor recordingExecutor = newExecutor(new DynamoDbFacade(backend, backend, regionResolver)); + StateMachine stateMachine = new StateMachine(); + stateMachine.setName("ddb"); + stateMachine.setStateMachineArn("arn:aws:states:eu-west-1:111122223333:stateMachine:ddb"); + stateMachine.setRoleArn("arn:aws:iam::111122223333:role/test-role"); + stateMachine.setDefinition(""" + {"StartAt": "Put", "States": {"Put": {"Type": "Task", + "Resource": "arn:aws:states:::dynamodb:putItem", + "Parameters": {"TableName": "orders", "Item": {"id": {"S": "k1"}}}, "End": true}}} + """); + Execution execution = new Execution(); + execution.setName("ddb-execution"); + execution.setExecutionArn("arn:aws:states:eu-west-1:111122223333:execution:ddb:ddb-execution"); + execution.setStateMachineArn(stateMachine.getStateMachineArn()); + execution.setInput("{}"); + + recordingExecutor.executeSync(stateMachine, execution, new ArrayList<>(), (updated, events) -> { + }); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertEquals(List.of(new Invocation("putItem", "111122223333", "eu-west-1")), backend.invocations()); + } + @Test void mockedTaskEmitsScheduledStartedSucceededInOrder() throws Exception { var mocks = testCase(Map.of("Send", List.of( diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java index eb04d15ee5..77d8d7c8c9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java @@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.s3.S3Service; @@ -53,7 +53,7 @@ class AslExecutorTerminalStateTest { executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorWaitStateTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorWaitStateTest.java index 1fcfa145df..d86119a813 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorWaitStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorWaitStateTest.java @@ -4,8 +4,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.CustomResourceLiveness; import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; -import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; @@ -166,7 +166,7 @@ class AslExecutorWaitStateTest { return new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), - mock(DynamoDbService.class), + mock(DynamoDbFacade.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 0a8d58b061..d1122577db 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -432,8 +432,8 @@ deferred_handlers: - { path: src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java } # non-tabular doc (grouped/inline); separate docs effort - { path: src/main/java/io/github/hectorvent/floci/services/configservice/ConfigServiceJsonHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/cur/CurJsonHandler.java } # no standalone action table yet - - { path: src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java } # multi-table doc - - { path: src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamsJsonHandler.java } # multi-table doc + - { path: src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java } # multi-table doc + - { path: src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java } # multi-table doc - { path: src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java } # doc packs multiple actions per row (`A` / `B`) + REST endpoints; needs de-grouping - { path: src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java } # non-tabular doc (grouped/inline)