software.amazon.awssdk
iotdataplane
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index ac99fa2376..150f887c22 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -763,6 +763,7 @@ public interface EmulatorConfig {
RedshiftDataServiceConfig redshiftData();
RedshiftServerlessServiceConfig redshiftServerless();
EventBridgeServiceConfig eventbridge();
+ EventBridgeV2ServiceConfig eventbridgev2();
CloudMapServiceConfig cloudmap();
EmrServiceConfig emr();
WafV2ServiceConfig wafv2();
@@ -1989,6 +1990,11 @@ public interface EmulatorConfig {
boolean enabled();
}
+ interface EventBridgeV2ServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface CloudMapServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
index fd382dc77e..c19f8af0df 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
@@ -12,6 +12,7 @@ import com.google.gson.JsonParseException;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
+import io.github.hectorvent.floci.services.eventbridgev2.EventBridgeV2Handler;
import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
import io.github.hectorvent.floci.services.marketplace.MarketplaceEntitlementController;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
@@ -34,6 +35,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
@@ -41,7 +43,7 @@ import java.util.zip.GZIPInputStream;
* via either smithy-rpc-v2-cbor path routing or the legacy X-Amz-Target header.
*
* Currently supported services: DynamoDB (incl. Streams), SQS, SNS, Kinesis,
- * Step Functions, and CloudWatch Metrics.
+ * Step Functions, CloudWatch Metrics, and EventBridge V2.
*
* Requests run on virtual threads, as in {@link AwsJsonController}, so a ReceiveMessage or
* GetActivityTask long poll does not hold one of the shared request workers while it waits.
@@ -69,6 +71,7 @@ public class AwsJsonCborController {
private final StepFunctionsJsonHandler sfnJsonHandler;
private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler;
private final MarketplaceEntitlementController marketplaceEntitlementController;
+ private final EventBridgeV2Handler eventBridgeV2Handler;
@Inject
public AwsJsonCborController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -79,7 +82,8 @@ public class AwsJsonCborController {
KinesisJsonHandler kinesisJsonHandler,
StepFunctionsJsonHandler sfnJsonHandler,
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler,
- MarketplaceEntitlementController marketplaceEntitlementController) {
+ MarketplaceEntitlementController marketplaceEntitlementController,
+ EventBridgeV2Handler eventBridgeV2Handler) {
this.objectMapper = objectMapper;
this.catalog = catalog;
this.regionResolver = regionResolver;
@@ -91,6 +95,7 @@ public class AwsJsonCborController {
this.sfnJsonHandler = sfnJsonHandler;
this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler;
this.marketplaceEntitlementController = marketplaceEntitlementController;
+ this.eventBridgeV2Handler = eventBridgeV2Handler;
}
@@ -110,7 +115,15 @@ public class AwsJsonCborController {
* without booting Quarkus.
*/
static byte[] nodeToSmithyCbor(JsonNode node) throws Exception {
- return writeCbor(node, false);
+ return nodeToSmithyCbor(node, Set.of());
+ }
+
+ /**
+ * As {@link #nodeToSmithyCbor(JsonNode)}, also tagging the members named, wherever they appear, as timestamps:
+ * a service whose model names its timestamps otherwise than {@link #isTimestampField} expects declares them.
+ */
+ static byte[] nodeToSmithyCbor(JsonNode node, Set timestampMembers) throws Exception {
+ return writeCbor(node, false, timestampMembers);
}
/**
@@ -121,14 +134,15 @@ public class AwsJsonCborController {
* newer smithy-rpc-v2-cbor protocol, and {@link #writeCborTimestamp} for why.
*/
static byte[] nodeToLegacyCbor(JsonNode node) throws Exception {
- return writeCbor(node, true);
+ return writeCbor(node, true, Set.of());
}
- private static byte[] writeCbor(JsonNode node, boolean legacyDialect) throws Exception {
+ private static byte[] writeCbor(JsonNode node, boolean legacyDialect, Set timestampMembers)
+ throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
CBORFactory factory = (CBORFactory) CBOR_MAPPER.getFactory();
try (CBORGenerator gen = factory.createGenerator(out)) {
- writeNodeToCbor(gen, node, false, legacyDialect);
+ writeNodeToCbor(gen, node, false, legacyDialect, timestampMembers);
}
return out.toByteArray();
}
@@ -141,16 +155,18 @@ public class AwsJsonCborController {
* object fields and is propagated into array elements, so both scalar timestamps and
* elements of timestamp lists are tagged. {@code legacyDialect} selects which of the
* two wire conventions tag(1) uses - see {@link #nodeToSmithyCbor}/{@link #nodeToLegacyCbor}.
+ * {@code timestampMembers} are field names tagged besides those the heuristic matches.
*/
private static void writeNodeToCbor(CBORGenerator gen, JsonNode node, boolean numberIsTimestamp,
- boolean legacyDialect) throws Exception {
+ boolean legacyDialect, Set timestampMembers) throws Exception {
if (node.isObject()) {
gen.writeStartObject();
Iterator> fields = node.fields();
while (fields.hasNext()) {
Map.Entry entry = fields.next();
gen.writeFieldName(entry.getKey());
- writeNodeToCbor(gen, entry.getValue(), isTimestampField(entry.getKey()), legacyDialect);
+ boolean timestamp = isTimestampField(entry.getKey()) || timestampMembers.contains(entry.getKey());
+ writeNodeToCbor(gen, entry.getValue(), timestamp, legacyDialect, timestampMembers);
}
gen.writeEndObject();
} else if (node.isArray()) {
@@ -158,7 +174,7 @@ public class AwsJsonCborController {
for (JsonNode item : node) {
// Propagate the timestamp context so every element of a timestamp list
// (e.g. CloudWatch GetMetricData MetricDataResults[].Timestamps) is tagged.
- writeNodeToCbor(gen, item, numberIsTimestamp, legacyDialect);
+ writeNodeToCbor(gen, item, numberIsTimestamp, legacyDialect, timestampMembers);
}
gen.writeEndArray();
} else if (numberIsTimestamp && node.isNumber()) {
@@ -319,7 +335,7 @@ public class AwsJsonCborController {
JsonNode responseNode = delegated.getEntity() instanceof JsonNode
? (JsonNode) delegated.getEntity()
: objectMapper.valueToTree(delegated.getEntity());
- byte[] cborBytes = nodeToSmithyCbor(responseNode);
+ byte[] cborBytes = nodeToSmithyCbor(responseNode, timestampMembers(serviceId));
String responseContentType = responseContentType(httpHeaders);
return Response.status(delegated.getStatus())
.header("smithy-protocol", "rpc-v2-cbor")
@@ -499,10 +515,19 @@ public class AwsJsonCborController {
case "states" -> sfnJsonHandler.handle(operation, request, region);
case "monitoring" -> cloudWatchMetricsJsonHandler.handle(operation, request, region);
case "marketplace" -> marketplaceEntitlementController.handle(operation, request, region);
+ case "eventsv2" -> eventBridgeV2Handler.handle(operation, request, region);
default -> null;
};
}
+ /** The timestamp members a service's responses carry under names {@link #isTimestampField} does not match. */
+ private Set timestampMembers(String serviceId) {
+ return catalog.byCborSdkServiceId(serviceId)
+ .filter(descriptor -> "eventsv2".equals(descriptor.externalKey()))
+ .map(descriptor -> EventBridgeV2Handler.TIMESTAMP_MEMBERS)
+ .orElse(Set.of());
+ }
+
private Response cborUnknownOperationError(String message, HttpHeaders httpHeaders) {
return cborErrorResponse(
new AwsException("UnknownOperationException", message, 404),
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index e0bb0696de..867bb0bb95 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -1350,7 +1350,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
.filter(scope -> scope.equals(catalog.canonicalCredentialScope(scope)))
.sorted()
.findFirst()
- .orElse(descriptor.externalKey());
+ .orElse(catalog.canonicalCredentialScope(descriptor.externalKey()));
}
/** The same contexts with every object-tag key removed, keeping the principal and global keys. */
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java
index 8651ad79fa..2c86a521d6 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java
@@ -129,16 +129,19 @@ final class RequestResourceMembers {
* it connects to). A type whose ARN is all an id its service mints is named instead by the members its service
* finds it by, {@code find}, each one value, in the order its service reads them, filling none of its variables
* and read no other way, in the caller's account (a scalable target by its service namespace, resource id and
- * scalable dimension).
+ * scalable dimension). A resource with an {@code endpoint} applies only to a request the service of that endpoint
+ * prefix serves, where two APIs share the operation's name and nothing in a request tells them apart
+ * (EventBridge's {@code events} and EventBridge V2's {@code eventsv2}); null for every request.
*/
record Resource(List types, Member arn, Map fill, Map> when,
Map> unless, Map absent, Map arnOf,
- Member account, String before, Map fixed, boolean made, List find) {
+ Member account, String before, Map fixed, boolean made, List find,
+ String endpoint) {
Resource(List types, Member arn, Map fill, Map> when,
Map> unless, Map absent, Map arnOf,
- Member account, String before, Map fixed, boolean made) {
- this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, List.of());
+ Member account, String before, Map fixed, boolean made, String endpoint) {
+ this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, List.of(), endpoint);
}
}
@@ -247,6 +250,11 @@ final class RequestResourceMembers {
+ resource.path("made") + ", which is not true");
}
boolean made = resource.has("made");
+ String endpoint = resource.has("endpoint") ? resource.path("endpoint").asText("") : null;
+ if (endpoint != null && endpoint.isEmpty()) {
+ throw new IllegalStateException(RESOURCE_NAME + " serves a resource of " + operation
+ + " on no endpoint prefix");
+ }
String before = resource.has("before") ? resource.path("before").asText("") : null;
if (before != null && before.length() != 1) {
throw new IllegalStateException(RESOURCE_NAME + " reads a member for " + operation
@@ -263,7 +271,7 @@ final class RequestResourceMembers {
+ " and finds its resource by " + resource.path("find") + " too");
}
return new Resource(types, arnMember(operation, resource.path("arn").asText("")), Map.of(), Map.of(),
- Map.of(), Map.of(), Map.of(), null, before, Map.of(), made);
+ Map.of(), Map.of(), Map.of(), null, before, Map.of(), made, endpoint);
}
String type = resource.path("type").asText("");
ArnFormat format = formats.get(type);
@@ -330,7 +338,7 @@ final class RequestResourceMembers {
+ " from " + account.name() + ", no member of one account or a type of none");
}
return new Resource(List.of(type), null, Map.copyOf(fill), when, unless, Map.copyOf(absent), Map.copyOf(arnOf),
- account, before, Map.copyOf(fixed), made, List.copyOf(find));
+ account, before, Map.copyOf(fixed), made, List.copyOf(find), endpoint);
}
/** The values each member named in {@code when} or {@code unless} may have, an empty one for the member absent. */
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
index 7b13d40a06..72300aea28 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
@@ -69,7 +69,8 @@ public final class RequestResources {
public static List of(String operation, ContainerRequestContext ctx, String partition, String region,
String accountId, StoredResourceArns stored) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
- List resources = operation == null ? null : table.operations().get(operation);
+ List resources = operation == null ? null
+ : served(table.operations().get(operation), ctx);
if (resources == null || resources.isEmpty()) {
return List.of();
}
@@ -117,7 +118,7 @@ public final class RequestResources {
RequestResourceMembers.Table table = RequestResourceMembers.table();
List creates = operation == null ? null : table.creates().get(operation);
List made = operation == null || creates != null ? List.of()
- : table.operations().getOrDefault(operation, List.of()).stream()
+ : served(table.operations().getOrDefault(operation, List.of()), ctx).stream()
.filter(RequestResourceMembers.Resource::made).toList();
if (creates == null && made.isEmpty()) {
return List.of();
@@ -149,6 +150,23 @@ public final class RequestResources {
return List.copyOf(arns);
}
+ /**
+ * The resources that apply to a request of the service serving it: one with an {@code endpoint} applies only to
+ * a request the service of that endpoint prefix serves, read from the claim of the service whose handler runs it
+ * and never from the request's members, which a caller could add to a request of the other API. A request no
+ * service is known to serve keeps them all, which can only check it on more.
+ */
+ private static List served(List resources,
+ ContainerRequestContext ctx) {
+ String endpoint = ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
+ && claim.service() != null ? claim.service().externalKey() : null;
+ if (resources == null || endpoint == null) {
+ return resources;
+ }
+ return resources.stream().filter(resource -> resource.endpoint() == null
+ || resource.endpoint().equals(endpoint)).toList();
+ }
+
/** The value up to {@code separator}, which its handler drops the rest after; the whole value without one. */
private static String before(String value, String separator) {
int at = separator == null ? -1 : value.indexOf(separator);
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 4c7b702067..98c88a15ef 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -125,7 +125,8 @@ public class ResolvedServiceCatalog {
"s3express", "s3",
"iot-jobs-data", "iot",
"monitoring", "cloudwatch",
- "awsssoportal", "sso");
+ "awsssoportal", "sso",
+ "eventsv2", "events");
private final ServiceCatalog catalog;
@@ -250,6 +251,12 @@ public class ResolvedServiceCatalog {
"eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AWSEvents."), Set.of("events"), Set.of(), Set.of()),
+ // Signs as events too, which stays EventBridge's scope: it is routed by its RPC v2 path alone,
+ // and its eventsv2 key aliases to the events IAM namespace its actions live under.
+ descriptor("eventsv2", "eventbridgev2", config.services().eventbridgev2().enabled(), true,
+ "eventbridgev2", config.storage().mode(), 5000L, null, ServiceProtocol.CBOR,
+ protocols(ServiceProtocol.CBOR),
+ Set.of(), Set.of(), Set.of("AWSEventsV2"), Set.of()),
descriptor("servicediscovery", "cloudmap", config.services().cloudmap().enabled(), true,
"cloudmap", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Delivery.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Delivery.java
new file mode 100644
index 0000000000..54594535de
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Delivery.java
@@ -0,0 +1,98 @@
+package io.github.hectorvent.floci.services.eventbridgev2;
+
+import com.fasterxml.jackson.databind.JsonNode;
+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.services.eventbridgev2.model.SubscriberV2;
+import io.github.hectorvent.floci.services.sqs.SqsService;
+import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Delivers an event a subscriber's filters matched to its target, an Amazon SQS queue: one message per event,
+ * whose body {@code Transformer.Type} decides, {@code RAW} the event's data unchanged and {@code WITH_METADATA}
+ * its data, metadata and system metadata, with the queue parameters {@code SqsParameters} gives.
+ */
+@ApplicationScoped
+public class EventBridgeV2Delivery {
+
+ private static final Logger LOG = Logger.getLogger(EventBridgeV2Delivery.class);
+
+ private final SqsService sqsService;
+ private final String baseUrl;
+
+ @Inject
+ public EventBridgeV2Delivery(SqsService sqsService, EmulatorConfig config) {
+ this.sqsService = sqsService;
+ this.baseUrl = config.baseUrl();
+ }
+
+ /** Sends the event to the subscriber's queue; a delivery that fails is logged and the event dropped. */
+ public void deliver(SubscriberV2 subscriber, PublishedEvent event) {
+ String queueArn = subscriber.getInvokeConfiguration().path("TargetArn").asText();
+ try {
+ JsonNode parameters = subscriber.getInvokeConfiguration().path("SqsParameters");
+ String groupId = parameter(parameters, "MessageGroupId", event);
+ String deduplicationId = parameter(parameters, "MessageDeduplicationId", event);
+ String delay = parameter(parameters, "DelaySeconds", event);
+ Map attributes = messageAttributes(parameters.path("MessageAttributes"), event);
+ String region = AwsArnUtils.parse(queueArn).region();
+ sqsService.sendMessage(AwsArnUtils.arnToQueueUrl(queueArn, baseUrl), body(subscriber, event),
+ delay == null ? null : Integer.valueOf(delay), groupId, deduplicationId,
+ attributes.isEmpty() ? null : attributes, region);
+ LOG.debugv("EventBridge V2 subscriber {0} delivered to {1}", subscriber.getArn(), queueArn);
+ } catch (AwsException | IllegalArgumentException e) {
+ LOG.warnv("EventBridge V2 subscriber {0} failed to deliver to {1}: {2}", subscriber.getArn(), queueArn,
+ e.getMessage());
+ }
+ }
+
+ static String body(SubscriberV2 subscriber, PublishedEvent event) {
+ JsonNode transformer = subscriber.getTransformer();
+ String type = transformer == null ? "RAW" : transformer.path("Type").asText("RAW");
+ if ("WITH_METADATA".equals(type)) {
+ return event.withMetadata().toString();
+ }
+ JsonNode data = event.data();
+ return data.isTextual() ? data.textValue() : data.toString();
+ }
+
+ private static String parameter(JsonNode parameters, String name, PublishedEvent event) {
+ JsonNode value = parameters.get(name);
+ if (value == null || value.isNull()) {
+ return null;
+ }
+ return resolve(value.asText(), name, event);
+ }
+
+ private static Map messageAttributes(JsonNode attributes, PublishedEvent event) {
+ Map resolved = new LinkedHashMap<>();
+ attributes.properties().forEach(attribute -> {
+ JsonNode value = attribute.getValue();
+ String dataType = value.path("DataType").asText("String");
+ String name = resolve(attribute.getKey(), "MessageAttributes", event);
+ if (value.hasNonNull("BinaryValue")) {
+ resolved.put(name, new MessageAttributeValue(Base64.getDecoder().decode(value.get("BinaryValue").asText()),
+ dataType));
+ } else {
+ resolved.put(name, new MessageAttributeValue(
+ resolve(value.path("StringValue").asText(""), "MessageAttributes." + name, event), dataType));
+ }
+ });
+ return resolved;
+ }
+
+ private static String resolve(String value, String parameter, PublishedEvent event) {
+ Optional resolved = EventExpressions.resolve(value, event);
+ return resolved.orElseThrow(() -> new IllegalArgumentException(
+ "SqsParameters." + parameter + " expression " + value + " produced no value"));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Handler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Handler.java
new file mode 100644
index 0000000000..775d66e321
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Handler.java
@@ -0,0 +1,222 @@
+package io.github.hectorvent.floci.services.eventbridgev2;
+
+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.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.services.eventbridgev2.model.EventBusV2;
+import io.github.hectorvent.floci.services.eventbridgev2.model.SubscriberV2;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * EventBridge V2 handler, dispatched by {@code AwsJsonCborController} for Smithy RPC v2 CBOR requests to
+ * {@code /service/AWSEventsV2/operation/}.
+ */
+@ApplicationScoped
+public class EventBridgeV2Handler {
+
+ /**
+ * The response members the model types as timestamps, which the CBOR encoder tags as such: their names do not
+ * end in {@code Timestamp}, the convention it otherwise goes by.
+ */
+ public static final Set TIMESTAMP_MEMBERS = Set.of("CreationTime", "LastModifiedTime",
+ "RetentionWindowStartTime", "StartingPoint", "EndPoint");
+
+ private final EventBridgeV2Service service;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public EventBridgeV2Handler(EventBridgeV2Service service, ObjectMapper objectMapper) {
+ this.service = service;
+ this.objectMapper = objectMapper;
+ }
+
+ public Response handle(String operation, JsonNode request, String region) {
+ return switch (operation) {
+ case "CreateEventBus" -> handleCreateEventBus(request, region);
+ case "DescribeEventBus" -> handleDescribeEventBus(request, region);
+ case "DeleteEventBus" -> handleDeleteEventBus(request, region);
+ case "ListEventBuses" -> handleListEventBuses(request, region);
+ case "CreateSubscriber" -> handleCreateSubscriber(request, region);
+ case "DescribeSubscriber" -> handleDescribeSubscriber(request, region);
+ case "ListSubscribers" -> handleListSubscribers(request, region);
+ case "UpdateSubscriber" -> handleUpdateSubscriber(request, region);
+ case "DeleteSubscriber" -> handleDeleteSubscriber(request, region);
+ case "PutEvents" -> handlePutEvents(request, region);
+ default -> throw new AwsException("UnsupportedOperation",
+ "Operation " + operation + " is not supported.", 400);
+ };
+ }
+
+ private Response handleCreateEventBus(JsonNode request, String region) {
+ return Response.ok(eventBus(service.createEventBus(request, region))).build();
+ }
+
+ private Response handleDescribeEventBus(JsonNode request, String region) {
+ EventBusV2 bus = service.describeEventBus(request, region);
+ ObjectNode response = eventBus(bus);
+ response.put("LastModifiedTime", epochSeconds(bus.getLastModifiedTime()));
+ return Response.ok(response).build();
+ }
+
+ /** The members {@code CreateEventBus} and {@code DescribeEventBus} both answer with. */
+ private ObjectNode eventBus(EventBusV2 bus) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("EventBusArn", bus.getArn());
+ response.put("Name", bus.getName());
+ if (bus.getDescription() != null) {
+ response.put("Description", bus.getDescription());
+ }
+ if (bus.getKmsKeyIdentifier() != null) {
+ response.putObject("EncryptionConfiguration").put("KmsKeyIdentifier", bus.getKmsKeyIdentifier());
+ }
+ if (bus.getRetentionPeriodInDays() != null) {
+ response.putObject("StorageConfiguration").put("RetentionPeriodInDays", bus.getRetentionPeriodInDays());
+ }
+ response.put("State", bus.getState());
+ response.put("CreationTime", epochSeconds(bus.getCreationTime()));
+ return response;
+ }
+
+ private Response handleDeleteEventBus(JsonNode request, String region) {
+ service.deleteEventBus(request, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleListEventBuses(JsonNode request, String region) {
+ PaginatedResult page = service.listEventBuses(request, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode buses = response.putArray("EventBuses");
+ for (EventBusV2 bus : page.items()) {
+ ObjectNode summary = buses.addObject();
+ summary.put("Name", bus.getName());
+ summary.put("EventBusArn", bus.getArn());
+ if (bus.getDescription() != null) {
+ summary.put("Description", bus.getDescription());
+ }
+ summary.put("CreationTime", epochSeconds(bus.getCreationTime()));
+ summary.put("LastModifiedTime", epochSeconds(bus.getLastModifiedTime()));
+ summary.put("State", bus.getState());
+ summary.put("EventBusAccountId", AwsArnUtils.parse(bus.getArn()).accountId());
+ }
+ if (page.nextToken() != null) {
+ response.put("NextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleCreateSubscriber(JsonNode request, String region) {
+ SubscriberV2 subscriber = service.createSubscriber(request, region);
+ ObjectNode response = subscriberIdentity(subscriber);
+ response.put("CreationTime", epochSeconds(subscriber.getCreationTime()));
+ return Response.ok(response).build();
+ }
+
+ private Response handleUpdateSubscriber(JsonNode request, String region) {
+ SubscriberV2 subscriber = service.updateSubscriber(request, region);
+ ObjectNode response = subscriberIdentity(subscriber);
+ response.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime()));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeSubscriber(JsonNode request, String region) {
+ SubscriberV2 subscriber = service.describeSubscriber(request, region);
+ ObjectNode response = subscriberIdentity(subscriber);
+ response.set("InvokeConfiguration", subscriber.getInvokeConfiguration());
+ if (subscriber.getDescription() != null) {
+ response.put("Description", subscriber.getDescription());
+ }
+ putIfSet(response, "FilterConfiguration", subscriber.getFilterConfiguration());
+ putIfSet(response, "BatchConfiguration", subscriber.getBatchConfiguration());
+ putIfSet(response, "Transformer", subscriber.getTransformer());
+ putIfSet(response, "RetryPolicy", subscriber.getRetryPolicy());
+ putIfSet(response, "OnFailureConfiguration", subscriber.getOnFailureConfiguration());
+ putIfSet(response, "LogConfiguration", subscriber.getLogConfiguration());
+ response.put("Revoked", false);
+ response.put("CreationTime", epochSeconds(subscriber.getCreationTime()));
+ response.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime()));
+ return Response.ok(response).build();
+ }
+
+ private Response handleListSubscribers(JsonNode request, String region) {
+ PaginatedResult page = service.listSubscribers(request, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode subscribers = response.putArray("Subscribers");
+ for (SubscriberV2 subscriber : page.items()) {
+ ObjectNode summary = subscribers.addObject();
+ summary.put("SubscriberArn", subscriber.getArn());
+ summary.put("Name", subscriber.getName());
+ summary.put("EventBusArn", subscriber.getEventBusArn());
+ summary.put("TargetArn", subscriber.getInvokeConfiguration().path("TargetArn").asText());
+ summary.put("Type", subscriber.getType());
+ summary.put("Revoked", false);
+ summary.put("State", subscriber.getState());
+ summary.put("CreationTime", epochSeconds(subscriber.getCreationTime()));
+ summary.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime()));
+ summary.put("SubscriberAccountId", AwsArnUtils.parse(subscriber.getArn()).accountId());
+ }
+ if (page.nextToken() != null) {
+ response.put("NextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ /** The members {@code CreateSubscriber}, {@code UpdateSubscriber} and {@code DescribeSubscriber} all answer with. */
+ private ObjectNode subscriberIdentity(SubscriberV2 subscriber) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("SubscriberArn", subscriber.getArn());
+ response.put("Name", subscriber.getName());
+ response.put("EventBusArn", subscriber.getEventBusArn());
+ response.put("Type", subscriber.getType());
+ response.put("StartingPosition", subscriber.getStartingPosition());
+ putIfSet(response, "PointInTimeConfiguration", subscriber.getPointInTimeConfiguration());
+ response.put("State", subscriber.getState());
+ return response;
+ }
+
+ private static void putIfSet(ObjectNode response, String field, JsonNode value) {
+ if (value != null && !value.isNull()) {
+ response.set(field, value);
+ }
+ }
+
+ private Response handleDeleteSubscriber(JsonNode request, String region) {
+ service.deleteSubscriber(request, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handlePutEvents(JsonNode request, String region) {
+ List results = service.putEvents(request, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode entries = response.putArray("Entries");
+ int failed = 0;
+ for (EventBridgeV2Service.PutEventsResult result : results) {
+ ObjectNode entry = entries.addObject();
+ if (result.errorCode() != null) {
+ failed++;
+ entry.put("ErrorCode", result.errorCode());
+ entry.put("ErrorMessage", result.errorMessage());
+ } else {
+ entry.put("EventId", result.eventId());
+ entry.put("SequenceNumber", result.sequenceNumber());
+ entry.put("SuccessCode", "PUBLISHED");
+ }
+ }
+ response.put("FailedEntryCount", failed);
+ return Response.ok(response).build();
+ }
+
+ private static BigDecimal epochSeconds(Instant instant) {
+ return BigDecimal.valueOf(instant.toEpochMilli()).movePointLeft(3);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Service.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Service.java
new file mode 100644
index 0000000000..7f3fc39cfc
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Service.java
@@ -0,0 +1,900 @@
+package io.github.hectorvent.floci.services.eventbridgev2;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsJsonTimestamp;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.eventbridgev2.model.EventBusV2;
+import io.github.hectorvent.floci.services.eventbridgev2.model.SubscriberV2;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.math.BigDecimal;
+import java.security.SecureRandom;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+
+/**
+ * EventBridge V2: the {@code AWSEventsV2} Smithy RPC v2 CBOR service, distinct from EventBridge's
+ * {@code event-bus} resources and sharing nothing with them but the {@code events} signing name. Its event buses
+ * accept events with {@code PutEvents} and deliver each to every running subscriber whose filters it matches.
+ */
+@ApplicationScoped
+public class EventBridgeV2Service implements Resettable {
+ static final String ACTIVE = "ACTIVE";
+ static final String RUNNING = "RUNNING";
+
+ private static final Logger LOG = Logger.getLogger(EventBridgeV2Service.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final ObjectMapper CANONICAL = new ObjectMapper()
+ .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
+ private static final Pattern NAME = Pattern.compile("[A-Za-z0-9][.\\-_A-Za-z0-9]*");
+ private static final Pattern DESCRIPTION = Pattern.compile("[^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*");
+ private static final Pattern KMS_KEY_IDENTIFIER = Pattern.compile("[a-zA-Z0-9_\\-/:]*");
+ private static final Pattern CLIENT_TOKEN = Pattern.compile("[\\u0021-\\u007E]+");
+ private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
+ private static final Pattern TAG_KEY = Pattern.compile("\\S([\\s\\S]*\\S)?");
+ private static final Pattern TAG_VALUE = Pattern.compile("(\\S([\\s\\S]*\\S)?)?");
+ private static final Pattern ROLE_ARN = Pattern.compile(
+ "arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::\\d{12}:role/[\\w+=,.@/-]+");
+ private static final Set PARAMETER_BLOCKS = Set.of("LambdaParameters", "SqsParameters", "SnsParameters",
+ "KinesisParameters", "StepFunctionsParameters", "HttpParameters", "UniversalTargetParameters",
+ "EventBusV2Parameters");
+ private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
+ private static final int ID_LENGTH = 25;
+ private static final int MAX_TAGS = 200;
+ private static final int MAX_ENTRIES = 100;
+ private static final int MAX_LIST_RESULTS = 100;
+ private static final List UPDATABLE_SETTINGS = List.of("Description", "State", "FilterConfiguration",
+ "BatchConfiguration", "Transformer", "RetryPolicy", "OnFailureConfiguration", "LogConfiguration");
+ private static final String PUT_EVENTS_CONTENT_TYPE = "application/eventbridge+json";
+
+ private final AccountAwareStorageBackend buses;
+ private final AccountAwareStorageBackend subscribers;
+ private final RegionResolver regionResolver;
+ private final EventBridgeV2Delivery delivery;
+ private final Clock clock;
+ private final SecureRandom random = new SecureRandom();
+ private final ConcurrentMap deliveriesByBus = new ConcurrentHashMap<>();
+
+ @Inject
+ public EventBridgeV2Service(StorageFactory storageFactory, RegionResolver regionResolver,
+ EventBridgeV2Delivery delivery) {
+ this(storageFactory.create("eventbridgev2", "eventbridgev2-buses.json",
+ new TypeReference