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.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-25 14:57:13 -04:00
1 parent 0be4d07111
commit 5bad6774f6
59 files changed
+4716 -3488

No files matched your search

@@ -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> dynamoDbService;
private final Instance<DynamoDbFacade> dynamoDbFacade;
private final Instance<Ec2Service> ec2Service;
private final Instance<S3Service> s3Service;
private final RequestContext requestContext;
private final EmulatorConfig config;
@Inject
public IamConditionContextResolver(Instance<DynamoDbService> dynamoDbService,
public IamConditionContextResolver(Instance<DynamoDbFacade> dynamoDbFacade,
Instance<Ec2Service> ec2Service,
Instance<S3Service> 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);
}
/**
@@ -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> T callAs(String accountId, Supplier<T> 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> T callAsChecked(String accountId, Callable<T> 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();
@@ -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<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
List<String> 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<String> existing = table.getReplicaRegions();
List<String> 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");
}
@@ -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<ExplorerResource> getResources() {
return tables.resources(regionResolver.getAccountId());
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true));
}
}
File diff suppressed because it is too large. Load diff
@@ -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);
}
}
@@ -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<JsonNode> 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<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (TableDefinition table : tableStore.scan(k -> true)) {
@@ -5033,9 +5030,4 @@ public class DynamoDbService implements ResourceProvider {
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true));
}
}
@@ -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<StreamDescription> 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<KeySchemaElement> 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<KeySchemaElement> 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)));
}
}
@@ -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<StreamDescription> 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<KeySchemaElement> 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<KeySchemaElement> 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;
}
}
@@ -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;
}
}
@@ -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<JsonNode> 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);
}
@@ -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.
*
* <p>{@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<String, List<String>> headers) {
public Reply {
headers = headers == null ? Map.of() : Map.copyOf(headers);
}
}
Reply execute(Call call) throws Exception;
}
@@ -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<KeySchemaElement> keySchema,
List<AttributeDefinition> attributeDefinitions, Long readCapacity,
Long writeCapacity, List<GlobalSecondaryIndex> globalSecondaryIndexes,
List<LocalSecondaryIndex> localSecondaryIndexes);
TableDefinition describeTable(Scope scope, String tableName);
Optional<TableDefinition> 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<String, String> listTagsOfResource(Scope scope, String resourceArn);
void tagResource(Scope scope, String resourceArn, Map<String, String> tags);
void untagResource(Scope scope, String resourceArn, List<String> tagKeys);
TableDefinition applyReplicaUpdates(Scope scope, String tableName, List<String> addRegions,
List<String> removeRegions);
TableDefinition ensureGlobalTable(Scope scope, String tableName);
List<ExplorerResource> resources(String accountId);
}
@@ -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<KeySchemaElement> keySchema,
List<AttributeDefinition> attributeDefinitions, Long readCapacity,
Long writeCapacity, List<GlobalSecondaryIndex> globalSecondaryIndexes,
List<LocalSecondaryIndex> 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<TableDefinition> 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<String, String> listTagsOfResource(Scope scope, String resourceArn) {
return RequestScopes.callAs(scope.accountId(),
() -> dynamoDbService.listTagsOfResource(resourceArn, scope.region()));
}
@Override
public void tagResource(Scope scope, String resourceArn, Map<String, String> tags) {
RequestScopes.runAs(scope.accountId(), () -> dynamoDbService.tagResource(resourceArn, tags, scope.region()));
}
@Override
public void untagResource(Scope scope, String resourceArn, List<String> tagKeys) {
RequestScopes.runAs(scope.accountId(),
() -> dynamoDbService.untagResource(resourceArn, tagKeys, scope.region()));
}
@Override
public TableDefinition applyReplicaUpdates(Scope scope, String tableName, List<String> addRegions,
List<String> 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<ExplorerResource> resources(String accountId) {
return RequestScopes.callAs(accountId, dynamoDbService::getResources);
}
}
@@ -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<Map<String, IotThingGroup>>() {}),
storageFactory.create("iot", "iot-thing-group-memberships.json", new TypeReference<Map<String, Set<String>>>() {}),
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" -> {
@@ -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<DynamoDbStreamRecord> records = result.items().stream()
.map(item -> toBackfillRecord(integration, item, table))
@@ -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<StepFunctionsService> 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<StepFunctionsService> 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<StepFunctionsService> 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> T callUnderExecutionAccount(StateMachine sm, Callable<T> 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<HistoryEvent> 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(