mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(eventbridgev2): add EventBridge V2 service (#6962)
This commit is contained in:
1 parent
5680ec4b8f
commit
dfaab8ba4c
47 files changed
+4283
-217
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
* <p>
|
||||
* Currently supported services: DynamoDB (incl. Streams), SQS, SNS, Kinesis,
|
||||
* Step Functions, and CloudWatch Metrics.
|
||||
* Step Functions, CloudWatch Metrics, and EventBridge V2.
|
||||
* <p>
|
||||
* 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<String> 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<String> 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<String> timestampMembers) throws Exception {
|
||||
if (node.isObject()) {
|
||||
gen.writeStartObject();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> 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<String> 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),
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> absent, Map<String, String> arnOf,
|
||||
Member account, String before, Map<String, String> fixed, boolean made, List<Member> find) {
|
||||
Member account, String before, Map<String, String> fixed, boolean made, List<Member> find,
|
||||
String endpoint) {
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> absent, Map<String, String> arnOf,
|
||||
Member account, String before, Map<String, String> fixed, boolean made) {
|
||||
this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, List.of());
|
||||
Member account, String before, Map<String, String> 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. */
|
||||
|
||||
@@ -69,7 +69,8 @@ public final class RequestResources {
|
||||
public static List<String> of(String operation, ContainerRequestContext ctx, String partition, String region,
|
||||
String accountId, StoredResourceArns stored) {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
List<RequestResourceMembers.Resource> resources = operation == null ? null : table.operations().get(operation);
|
||||
List<RequestResourceMembers.Resource> 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<RequestResourceMembers.Created> creates = operation == null ? null : table.creates().get(operation);
|
||||
List<RequestResourceMembers.Resource> 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<RequestResourceMembers.Resource> served(List<RequestResourceMembers.Resource> 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);
|
||||
|
||||
@@ -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),
|
||||
|
||||
+98
@@ -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<String, MessageAttributeValue> 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<String, MessageAttributeValue> messageAttributes(JsonNode attributes, PublishedEvent event) {
|
||||
Map<String, MessageAttributeValue> 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<String> resolved = EventExpressions.resolve(value, event);
|
||||
return resolved.orElseThrow(() -> new IllegalArgumentException(
|
||||
"SqsParameters." + parameter + " expression " + value + " produced no value"));
|
||||
}
|
||||
}
|
||||
+222
@@ -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/<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<String> 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<EventBusV2> 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<SubscriberV2> 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<EventBridgeV2Service.PutEventsResult> 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);
|
||||
}
|
||||
}
|
||||
+900
@@ -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<String> 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<String> 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<EventBusV2> buses;
|
||||
private final AccountAwareStorageBackend<SubscriberV2> subscribers;
|
||||
private final RegionResolver regionResolver;
|
||||
private final EventBridgeV2Delivery delivery;
|
||||
private final Clock clock;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final ConcurrentMap<String, OrderedDeliveries> deliveriesByBus = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public EventBridgeV2Service(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
EventBridgeV2Delivery delivery) {
|
||||
this(storageFactory.create("eventbridgev2", "eventbridgev2-buses.json",
|
||||
new TypeReference<Map<String, EventBusV2>>() {}),
|
||||
storageFactory.create("eventbridgev2", "eventbridgev2-subscribers.json",
|
||||
new TypeReference<Map<String, SubscriberV2>>() {}),
|
||||
regionResolver, delivery, Clock.systemUTC());
|
||||
}
|
||||
|
||||
EventBridgeV2Service(AccountAwareStorageBackend<EventBusV2> buses,
|
||||
AccountAwareStorageBackend<SubscriberV2> subscribers, RegionResolver regionResolver,
|
||||
EventBridgeV2Delivery delivery, Clock clock) {
|
||||
this.buses = buses;
|
||||
this.subscribers = subscribers;
|
||||
this.regionResolver = regionResolver;
|
||||
this.delivery = delivery;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Event buses ────────────────────────────
|
||||
|
||||
/**
|
||||
* Creates an event bus, {@code ACTIVE} at once. A retry with the {@code ClientToken} of an earlier create
|
||||
* returns that bus when it repeats the request, and fails when it changes it.
|
||||
*/
|
||||
public synchronized EventBusV2 createEventBus(JsonNode request, String region) {
|
||||
String name = requireName(request);
|
||||
String description = optionalDescription(request);
|
||||
String kmsKeyIdentifier = optionalKmsKeyIdentifier(request);
|
||||
Integer retentionPeriodInDays = optionalRetentionPeriodInDays(request);
|
||||
Map<String, String> tags = readTags(request.get("Tags"));
|
||||
String clientToken = optionalClientToken(request);
|
||||
String createRequest = withoutClientToken(request);
|
||||
|
||||
if (clientToken != null) {
|
||||
Optional<EventBusV2> retried = buses.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(bus -> clientToken.equals(bus.getClientToken()))
|
||||
.findFirst();
|
||||
if (retried.isPresent()) {
|
||||
if (!createRequest.equals(retried.get().getCreateRequest())) {
|
||||
throw idempotentMismatch(clientToken);
|
||||
}
|
||||
return retried.get();
|
||||
}
|
||||
}
|
||||
String key = storageKey(region, name);
|
||||
if (buses.get(key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException", "Event bus " + name + " already exists.", 409);
|
||||
}
|
||||
|
||||
Instant now = clock.instant();
|
||||
EventBusV2 bus = new EventBusV2();
|
||||
bus.setName(name);
|
||||
bus.setArn(regionResolver.buildArn("events", region, "event-busv2/" + name + "/" + newId()));
|
||||
bus.setDescription(description);
|
||||
bus.setKmsKeyIdentifier(kmsKeyIdentifier);
|
||||
bus.setRetentionPeriodInDays(retentionPeriodInDays);
|
||||
bus.setState(ACTIVE);
|
||||
bus.setCreationTime(now);
|
||||
bus.setLastModifiedTime(now);
|
||||
bus.setTags(tags);
|
||||
bus.setClientToken(clientToken);
|
||||
bus.setCreateRequest(createRequest);
|
||||
buses.put(key, bus);
|
||||
return bus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a bus's description, KMS key, retention and tags to what the request gives, clearing those it leaves
|
||||
* out, as a CloudFormation update of the bus's template does. The name is the bus's identity and is not read.
|
||||
*/
|
||||
public synchronized EventBusV2 replaceEventBusSettings(String eventBusArn, JsonNode request, String region) {
|
||||
EventBusV2 bus = requireEventBus(eventBusArn, region);
|
||||
String description = optionalDescription(request);
|
||||
String kmsKeyIdentifier = optionalKmsKeyIdentifier(request);
|
||||
Integer retentionPeriodInDays = optionalRetentionPeriodInDays(request);
|
||||
Map<String, String> tags = readTags(request.get("Tags"));
|
||||
bus.setDescription(description);
|
||||
bus.setKmsKeyIdentifier(kmsKeyIdentifier);
|
||||
bus.setRetentionPeriodInDays(retentionPeriodInDays);
|
||||
bus.setTags(tags);
|
||||
bus.setLastModifiedTime(clock.instant());
|
||||
buses.put(storageKey(region, bus.getName()), bus);
|
||||
return bus;
|
||||
}
|
||||
|
||||
/** The bus {@code EventBusArn} names. */
|
||||
public EventBusV2 describeEventBus(JsonNode request, String region) {
|
||||
return requireEventBus(requireText(request, "EventBusArn"), region);
|
||||
}
|
||||
|
||||
/** Deletes the bus {@code EventBusArn} names. */
|
||||
public void deleteEventBus(JsonNode request, String region) {
|
||||
deleteEventBus(requireText(request, "EventBusArn"), region);
|
||||
}
|
||||
|
||||
/** Deletes a bus, which must have no subscribers left. */
|
||||
public synchronized void deleteEventBus(String eventBusArn, String region) {
|
||||
EventBusV2 bus = requireEventBus(eventBusArn, region);
|
||||
if (!subscribersOf(bus, region).isEmpty()) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Event bus " + bus.getName() + " still has subscribers; delete them first.", 409);
|
||||
}
|
||||
buses.delete(storageKey(region, bus.getName()));
|
||||
deliveriesByBus.remove(bus.getArn());
|
||||
}
|
||||
|
||||
/**
|
||||
* One page of the Region's buses in name order, those whose name starts with {@code NamePrefix}. Every bus is
|
||||
* the caller's own, so an {@code EventBusAccountId} naming another account lists none.
|
||||
*/
|
||||
public PaginatedResult<EventBusV2> listEventBuses(JsonNode request, String region) {
|
||||
String namePrefix = optionalNamePrefix(request);
|
||||
String accountId = text(request, "EventBusAccountId");
|
||||
if (accountId != null && !ACCOUNT_ID.matcher(accountId).matches()) {
|
||||
throw invalidInput("EventBusAccountId must be 12 digits.");
|
||||
}
|
||||
List<EventBusV2> listed = accountId != null && !accountId.equals(regionResolver.getAccountId())
|
||||
? List.of()
|
||||
: buses.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(bus -> namePrefix == null || bus.getName().startsWith(namePrefix))
|
||||
.toList();
|
||||
return page(listed, EventBusV2::getName, request, "event-busv2");
|
||||
}
|
||||
|
||||
// ──────────────────────────── Subscribers ────────────────────────────
|
||||
|
||||
/**
|
||||
* Creates a subscriber on a bus of the caller's, delivering each event it accepts that matches every filter
|
||||
* to its target, an Amazon SQS queue of the caller's. A retry with the {@code ClientToken} of an earlier create
|
||||
* returns that subscriber when it repeats the request, and fails when it changes it.
|
||||
*/
|
||||
public synchronized SubscriberV2 createSubscriber(JsonNode request, String region) {
|
||||
String name = requireName(request);
|
||||
String eventBusArn = requireText(request, "EventBusArn");
|
||||
JsonNode filterConfiguration = optionalStructure(request, "FilterConfiguration");
|
||||
if (filterConfiguration != null) {
|
||||
SubscriberFilters.validate(filterConfiguration);
|
||||
}
|
||||
String clientToken = optionalClientToken(request);
|
||||
String createRequest = withoutClientToken(request);
|
||||
if (clientToken != null) {
|
||||
Optional<SubscriberV2> retried = subscribers.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(subscriber -> clientToken.equals(subscriber.getClientToken()))
|
||||
.findFirst();
|
||||
if (retried.isPresent()) {
|
||||
if (!createRequest.equals(retried.get().getCreateRequest())) {
|
||||
throw idempotentMismatch(clientToken);
|
||||
}
|
||||
return retried.get();
|
||||
}
|
||||
}
|
||||
EventBusV2 bus = requireEventBus(eventBusArn, region);
|
||||
String key = subscriberKey(region, bus.getName(), name);
|
||||
if (subscribers.get(key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException",
|
||||
"Subscriber " + name + " already exists on event bus " + bus.getName() + ".", 409);
|
||||
}
|
||||
|
||||
Instant now = clock.instant();
|
||||
SubscriberV2 subscriber = new SubscriberV2();
|
||||
subscriber.setName(name);
|
||||
subscriber.setArn(regionResolver.buildArn("events", region, "subscriber/" + name + "/" + newId()));
|
||||
subscriber.setEventBusArn(bus.getArn());
|
||||
subscriber.setType(optionalEnum(request, "Type", Set.of("FIFO", "UNORDERED"), "UNORDERED"));
|
||||
subscriber.setStartingPosition(optionalEnum(request, "StartingPosition", Set.of("LATEST", "POINT_IN_TIME"),
|
||||
"LATEST"));
|
||||
subscriber.setPointInTimeConfiguration(pointInTimeConfiguration(request, subscriber.getStartingPosition()));
|
||||
applySettings(subscriber, request, filterConfiguration);
|
||||
subscriber.setCreationTime(now);
|
||||
subscriber.setLastModifiedTime(now);
|
||||
subscriber.setClientToken(clientToken);
|
||||
subscriber.setCreateRequest(createRequest);
|
||||
subscribers.put(key, subscriber);
|
||||
return subscriber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a subscriber's description, target, filters, transformer, delivery settings, state and tags to what the
|
||||
* request gives, clearing those it leaves out, as a CloudFormation update of the subscriber's template does.
|
||||
* Its name, bus, type and starting position are its identity and are not read.
|
||||
*/
|
||||
public synchronized SubscriberV2 replaceSubscriberSettings(String subscriberArn, JsonNode request, String region) {
|
||||
SubscriberV2 subscriber = requireSubscriber(subscriberArn, region);
|
||||
return changeSettings(subscriber, request, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the settings an {@code UpdateSubscriber} request gives and leaves those it omits as they are. The
|
||||
* target stays the subscriber's own: the request's {@code InvokeConfiguration} carries the role and target
|
||||
* parameters but no {@code TargetArn}. Events are not retained, so {@code ResumePosition} is checked and has no
|
||||
* effect.
|
||||
*/
|
||||
public synchronized SubscriberV2 updateSubscriber(JsonNode request, String region) {
|
||||
SubscriberV2 subscriber = requireSubscriber(requireText(request, "SubscriberArn"), region);
|
||||
optionalEnum(request, "ResumePosition", Set.of("LAST_PROCESSED", "LATEST"), null);
|
||||
JsonNode invokeConfiguration = optionalStructure(request, "InvokeConfiguration");
|
||||
if (invokeConfiguration != null && invokeConfiguration.has("TargetArn")) {
|
||||
throw invalidInput("InvokeConfiguration.TargetArn cannot be updated.");
|
||||
}
|
||||
|
||||
ObjectNode settings = currentSettings(subscriber);
|
||||
for (String field : UPDATABLE_SETTINGS) {
|
||||
if (request.hasNonNull(field)) {
|
||||
settings.set(field, request.get(field));
|
||||
}
|
||||
}
|
||||
if (invokeConfiguration != null) {
|
||||
ObjectNode invoke = invokeConfiguration.deepCopy();
|
||||
invoke.set("TargetArn", subscriber.getInvokeConfiguration().get("TargetArn"));
|
||||
settings.set("InvokeConfiguration", invoke);
|
||||
}
|
||||
return changeSettings(subscriber, settings, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a new subscriber with {@code subscriber}'s identity and {@code settings}, so a refused change changes
|
||||
* nothing and a reader sees the subscriber before or after the change, never part way through it.
|
||||
*/
|
||||
private SubscriberV2 changeSettings(SubscriberV2 subscriber, JsonNode settings, String region) {
|
||||
JsonNode filterConfiguration = optionalStructure(settings, "FilterConfiguration");
|
||||
if (filterConfiguration != null) {
|
||||
SubscriberFilters.validate(filterConfiguration);
|
||||
}
|
||||
SubscriberV2 changed = new SubscriberV2();
|
||||
applySettings(changed, settings, filterConfiguration);
|
||||
changed.setName(subscriber.getName());
|
||||
changed.setArn(subscriber.getArn());
|
||||
changed.setEventBusArn(subscriber.getEventBusArn());
|
||||
changed.setType(subscriber.getType());
|
||||
changed.setStartingPosition(subscriber.getStartingPosition());
|
||||
changed.setPointInTimeConfiguration(subscriber.getPointInTimeConfiguration());
|
||||
changed.setCreationTime(subscriber.getCreationTime());
|
||||
changed.setLastModifiedTime(clock.instant());
|
||||
changed.setClientToken(subscriber.getClientToken());
|
||||
changed.setCreateRequest(subscriber.getCreateRequest());
|
||||
subscribers.put(subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName()), changed);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** The subscriber {@code SubscriberArn} names. */
|
||||
public SubscriberV2 describeSubscriber(JsonNode request, String region) {
|
||||
return requireSubscriber(requireText(request, "SubscriberArn"), region);
|
||||
}
|
||||
|
||||
/**
|
||||
* One page of the Region's subscribers, or those of the bus {@code EventBusArn} names, whose name starts with
|
||||
* {@code NamePrefix}, in order of bus and then subscriber name.
|
||||
*/
|
||||
public PaginatedResult<SubscriberV2> listSubscribers(JsonNode request, String region) {
|
||||
String namePrefix = optionalNamePrefix(request);
|
||||
String eventBusArn = text(request, "EventBusArn");
|
||||
EventBusV2 bus = eventBusArn == null ? null : requireEventBus(eventBusArn, region);
|
||||
List<SubscriberV2> listed = (bus == null ? subscribers.scan(key -> key.startsWith(region + "::"))
|
||||
: subscribersOf(bus, region)).stream()
|
||||
.filter(subscriber -> namePrefix == null || subscriber.getName().startsWith(namePrefix))
|
||||
.toList();
|
||||
return page(listed, subscriber -> busName(subscriber.getEventBusArn()) + "::" + subscriber.getName(),
|
||||
request, "subscriber");
|
||||
}
|
||||
|
||||
/** Deletes the subscriber {@code SubscriberArn} names. */
|
||||
public void deleteSubscriber(JsonNode request, String region) {
|
||||
deleteSubscriber(requireText(request, "SubscriberArn"), region);
|
||||
}
|
||||
|
||||
public synchronized void deleteSubscriber(String subscriberArn, String region) {
|
||||
SubscriberV2 subscriber = requireSubscriber(subscriberArn, region);
|
||||
subscribers.delete(subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName()));
|
||||
}
|
||||
|
||||
public Optional<SubscriberV2> findSubscriber(String subscriberArn, String region) {
|
||||
return subscribers.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(subscriber -> subscriber.getArn().equals(subscriberArn))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public Optional<EventBusV2> findEventBus(String eventBusArn, String region) {
|
||||
return Optional.ofNullable(busName(eventBusArn))
|
||||
.flatMap(name -> buses.get(storageKey(region, name)))
|
||||
.filter(bus -> bus.getArn().equals(eventBusArn));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Events ────────────────────────────
|
||||
|
||||
/** A bus's deliveries waiting to be sent, in sequence order, and the lock held while sending them. */
|
||||
private record OrderedDeliveries(Queue<Map.Entry<SubscriberV2, PublishedEvent>> pending, ReentrantLock sending) {
|
||||
}
|
||||
|
||||
/** The outcome of one {@code PutEvents} entry: its id and sequence number, or why it was refused. */
|
||||
public record PutEventsResult(String eventId, String sequenceNumber, String errorCode, String errorMessage) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts each entry as an event in the EventBridge envelope and delivers it to every running subscriber of the
|
||||
* bus whose filters it matches. An entry whose {@code Detail} is not a JSON object is refused on its own.
|
||||
*/
|
||||
public List<PutEventsResult> putEvents(JsonNode request, String region) {
|
||||
String eventBusArn = requireText(request, "EventBusArn");
|
||||
JsonNode entries = request.get("Entries");
|
||||
if (entries == null || !entries.isArray() || entries.isEmpty() || entries.size() > MAX_ENTRIES) {
|
||||
throw invalidInput("Entries must hold 1 to " + MAX_ENTRIES + " entries.");
|
||||
}
|
||||
List<Instant> times = new ArrayList<>();
|
||||
for (JsonNode entry : entries) {
|
||||
requireText(entry, "Source");
|
||||
requireText(entry, "DetailType");
|
||||
times.add(AwsJsonTimestamp.epochSeconds(entry, "Time", "InvalidInputException"));
|
||||
}
|
||||
List<PutEventsResult> results = new ArrayList<>();
|
||||
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries = new ArrayList<>();
|
||||
OrderedDeliveries ordered;
|
||||
synchronized (this) {
|
||||
EventBusV2 bus = requireEventBus(eventBusArn, region);
|
||||
List<SubscriberV2> running = subscribersOf(bus, region).stream()
|
||||
.filter(subscriber -> RUNNING.equals(subscriber.getState()))
|
||||
.toList();
|
||||
for (int i = 0; i < entries.size(); i++) {
|
||||
JsonNode entry = entries.get(i);
|
||||
JsonNode detail = detail(entry);
|
||||
if (detail == null) {
|
||||
results.add(new PutEventsResult(null, null, "MalformedDetail", "Detail is malformed."));
|
||||
continue;
|
||||
}
|
||||
bus.setSequenceNumber(bus.getSequenceNumber() + 1);
|
||||
String sequenceNumber = Long.toString(bus.getSequenceNumber());
|
||||
PublishedEvent event = envelope(bus, entry, times.get(i), detail, sequenceNumber);
|
||||
results.add(new PutEventsResult(event.systemMetadata().get("aws:EventId").asText(), sequenceNumber,
|
||||
null, null));
|
||||
for (SubscriberV2 subscriber : running) {
|
||||
if (SubscriberFilters.matches(subscriber.getFilterConfiguration(), event)) {
|
||||
deliveries.add(Map.entry(subscriber, event));
|
||||
}
|
||||
}
|
||||
}
|
||||
buses.put(storageKey(region, bus.getName()), bus);
|
||||
ordered = deliveriesByBus.computeIfAbsent(bus.getArn(),
|
||||
arn -> new OrderedDeliveries(new ConcurrentLinkedQueue<>(), new ReentrantLock()));
|
||||
ordered.pending().addAll(deliveries);
|
||||
}
|
||||
send(ordered);
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a bus's queued deliveries in the order {@code PutEvents} queued them, which is sequence order, holding the
|
||||
* bus's sending lock, so a request that took later sequence numbers never sends ahead of an earlier one. Every
|
||||
* caller drains after queueing its own deliveries, so none is left queued, and a caller returns only once its own
|
||||
* have been sent, by itself or by the caller that held the lock before it.
|
||||
*/
|
||||
private void send(OrderedDeliveries ordered) {
|
||||
ordered.sending().lock();
|
||||
try {
|
||||
Map.Entry<SubscriberV2, PublishedEvent> next;
|
||||
while ((next = ordered.pending().poll()) != null) {
|
||||
try {
|
||||
delivery.deliver(next.getKey(), next.getValue());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "EventBridge V2 subscriber {0} failed to deliver event {1}", next.getKey().getArn(),
|
||||
next.getValue().systemMetadata().path("aws:EventId").asText());
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
ordered.sending().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private PublishedEvent envelope(EventBusV2 bus, JsonNode entry, Instant time, JsonNode detail,
|
||||
String sequenceNumber) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(bus.getArn());
|
||||
Instant ingested = clock.instant();
|
||||
String eventId = UUID.randomUUID().toString();
|
||||
|
||||
ObjectNode data = JsonNodeFactory.instance.objectNode();
|
||||
data.put("version", "0");
|
||||
data.put("id", eventId);
|
||||
data.put("detail-type", entry.get("DetailType").asText());
|
||||
data.put("source", entry.get("Source").asText());
|
||||
data.put("account", arn.accountId());
|
||||
data.put("time", (time == null ? ingested : time).truncatedTo(ChronoUnit.SECONDS).toString());
|
||||
data.put("region", arn.region());
|
||||
data.set("resources", entry.has("Resources") && entry.get("Resources").isArray()
|
||||
? entry.get("Resources") : JsonNodeFactory.instance.arrayNode());
|
||||
data.set("detail", detail);
|
||||
|
||||
ObjectNode system = JsonNodeFactory.instance.objectNode();
|
||||
system.put("ContentType", PUT_EVENTS_CONTENT_TYPE);
|
||||
JsonNode supplied = entry.path("SystemMetadata");
|
||||
if (supplied.hasNonNull("EventGroupId")) {
|
||||
system.put("EventGroupId", supplied.get("EventGroupId").asText());
|
||||
}
|
||||
if (supplied.hasNonNull("DeduplicationId")) {
|
||||
system.put("DeduplicationId", supplied.get("DeduplicationId").asText());
|
||||
}
|
||||
system.put("aws:EventId", eventId);
|
||||
system.put("aws:IngestionTime", ingested.toString());
|
||||
system.put("aws:SequenceNumber", sequenceNumber);
|
||||
system.put("aws:DeliveryType", "LIVE");
|
||||
system.put("aws:Source", entry.get("Source").asText());
|
||||
system.put("aws:DetailType", entry.get("DetailType").asText());
|
||||
return new PublishedEvent(data, JsonNodeFactory.instance.objectNode(), system);
|
||||
}
|
||||
|
||||
/** The entry's detail as a JSON object, an empty one when it gives none; null when it is not one. */
|
||||
private static JsonNode detail(JsonNode entry) {
|
||||
JsonNode detail = entry.get("Detail");
|
||||
if (detail == null || detail.isNull()) {
|
||||
return JsonNodeFactory.instance.objectNode();
|
||||
}
|
||||
try {
|
||||
JsonNode parsed = MAPPER.readTree(detail.asText());
|
||||
return parsed != null && parsed.isObject() ? parsed : null;
|
||||
} catch (Exception ignored) {
|
||||
// A Detail that is not JSON is the caller's error, reported as that entry's MalformedDetail result.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
buses.clear();
|
||||
subscribers.clear();
|
||||
deliveriesByBus.clear();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Subscriber settings ────────────────────────────
|
||||
|
||||
/** A subscriber's settings in the shape of the request that sets them, for an update to overlay. */
|
||||
private static ObjectNode currentSettings(SubscriberV2 subscriber) {
|
||||
ObjectNode settings = JsonNodeFactory.instance.objectNode();
|
||||
if (subscriber.getDescription() != null) {
|
||||
settings.put("Description", subscriber.getDescription());
|
||||
}
|
||||
settings.set("InvokeConfiguration", subscriber.getInvokeConfiguration());
|
||||
settings.set("FilterConfiguration", subscriber.getFilterConfiguration());
|
||||
settings.set("Transformer", subscriber.getTransformer());
|
||||
settings.set("BatchConfiguration", subscriber.getBatchConfiguration());
|
||||
settings.set("RetryPolicy", subscriber.getRetryPolicy());
|
||||
settings.set("OnFailureConfiguration", subscriber.getOnFailureConfiguration());
|
||||
settings.set("LogConfiguration", subscriber.getLogConfiguration());
|
||||
settings.put("State", subscriber.getState());
|
||||
settings.set("Tags", MAPPER.valueToTree(subscriber.getTags()));
|
||||
return settings;
|
||||
}
|
||||
|
||||
private void applySettings(SubscriberV2 subscriber, JsonNode request, JsonNode filterConfiguration) {
|
||||
subscriber.setDescription(optionalDescription(request));
|
||||
subscriber.setInvokeConfiguration(invokeConfiguration(request));
|
||||
subscriber.setFilterConfiguration(filterConfiguration);
|
||||
subscriber.setTransformer(transformer(request));
|
||||
subscriber.setBatchConfiguration(boundedIntegers(request, "BatchConfiguration",
|
||||
Map.of("MaxBatchSize", new int[] {1, 500}, "MaxBatchWindowInSeconds", new int[] {0, 300})));
|
||||
JsonNode retryPolicy = boundedIntegers(request, "RetryPolicy",
|
||||
Map.of("MaxRetryAttempts", new int[] {0, 185}, "MaxEventAgeInSeconds", new int[] {60, 86400}));
|
||||
if (retryPolicy != null) {
|
||||
optionalEnum(retryPolicy, "RetryStrategy", Set.of("ALL"), null);
|
||||
}
|
||||
subscriber.setRetryPolicy(retryPolicy);
|
||||
subscriber.setOnFailureConfiguration(onFailureConfiguration(request));
|
||||
JsonNode logConfiguration = optionalStructure(request, "LogConfiguration");
|
||||
if (logConfiguration != null) {
|
||||
optionalEnum(logConfiguration, "Level", Set.of("OFF", "ERROR", "INFO"), null);
|
||||
optionalEnum(logConfiguration, "IncludePayload", Set.of("FULL", "ON_ERROR_ONLY"), null);
|
||||
}
|
||||
subscriber.setLogConfiguration(logConfiguration);
|
||||
subscriber.setState(optionalEnum(request, "State", Set.of(RUNNING, "STOPPED"), RUNNING));
|
||||
subscriber.setTags(readTags(request.get("Tags")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The target and its parameters. Floci delivers to an Amazon SQS queue of the caller's, so a target of another
|
||||
* service or account, or a parameter block other than {@code SqsParameters}, is refused; a parameter is a
|
||||
* literal or a path into the event.
|
||||
*/
|
||||
private JsonNode invokeConfiguration(JsonNode request) {
|
||||
JsonNode configuration = optionalStructure(request, "InvokeConfiguration");
|
||||
if (configuration == null) {
|
||||
throw invalidInput("InvokeConfiguration is required.");
|
||||
}
|
||||
String roleArn = requireText(configuration, "RoleArn");
|
||||
if (roleArn.length() > 1600 || !ROLE_ARN.matcher(roleArn).matches()) {
|
||||
throw invalidInput("InvokeConfiguration.RoleArn must be the ARN of an IAM role.");
|
||||
}
|
||||
String targetArn = requireText(configuration, "TargetArn");
|
||||
AwsArnUtils.Arn target = AwsArnUtils.isArn(targetArn) ? AwsArnUtils.parse(targetArn) : null;
|
||||
if (target == null) {
|
||||
throw invalidInput("InvokeConfiguration.TargetArn must be an ARN.");
|
||||
}
|
||||
if (!"sqs".equals(target.service())) {
|
||||
throw invalidInput("Floci delivers EventBridge V2 events only to Amazon SQS queues; "
|
||||
+ targetArn + " is not one.");
|
||||
}
|
||||
if (!regionResolver.getAccountId().equals(target.accountId())) {
|
||||
throw invalidInput("InvokeConfiguration.TargetArn must belong to your account.");
|
||||
}
|
||||
for (String block : PARAMETER_BLOCKS) {
|
||||
if (!"SqsParameters".equals(block) && configuration.hasNonNull(block)) {
|
||||
throw invalidInput("InvokeConfiguration." + block + " does not match the target type of "
|
||||
+ targetArn + ".");
|
||||
}
|
||||
}
|
||||
JsonNode parameters = optionalStructure(configuration, "SqsParameters");
|
||||
if (parameters != null) {
|
||||
for (String name : List.of("MessageGroupId", "MessageDeduplicationId", "DelaySeconds")) {
|
||||
requireSupportedExpression(text(parameters, name), "SqsParameters." + name);
|
||||
}
|
||||
JsonNode attributes = optionalStructure(parameters, "MessageAttributes");
|
||||
if (attributes != null) {
|
||||
for (Map.Entry<String, JsonNode> attribute : attributes.properties()) {
|
||||
requireSupportedExpression(attribute.getKey(), "SqsParameters.MessageAttributes");
|
||||
JsonNode stringValue = attribute.getValue().get("StringValue");
|
||||
if (stringValue != null && stringValue.isTextual()) {
|
||||
requireSupportedExpression(stringValue.textValue(),
|
||||
"SqsParameters.MessageAttributes." + attribute.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private static void requireSupportedExpression(String value, String parameter) {
|
||||
if (value != null && !EventExpressions.isSupported(value)) {
|
||||
throw invalidInput(parameter + " is a JSONata expression Floci does not evaluate; it supports a literal "
|
||||
+ "or a path such as {% $events.SystemMetadata.EventGroupId %}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode transformer(JsonNode request) {
|
||||
JsonNode transformer = optionalStructure(request, "Transformer");
|
||||
if (transformer == null) {
|
||||
return null;
|
||||
}
|
||||
String type = optionalEnum(transformer, "Type", Set.of("RAW", "WITH_METADATA", "JSONATA"), "RAW");
|
||||
if ("JSONATA".equals(type)) {
|
||||
throw invalidInput("Floci does not evaluate a JSONATA transformer; use RAW or WITH_METADATA.");
|
||||
}
|
||||
return transformer;
|
||||
}
|
||||
|
||||
private static JsonNode onFailureConfiguration(JsonNode request) {
|
||||
JsonNode configuration = optionalStructure(request, "OnFailureConfiguration");
|
||||
if (configuration != null) {
|
||||
String arn = text(configuration, "Arn");
|
||||
if (arn != null && !AwsArnUtils.isArnFor(arn, "sqs")) {
|
||||
throw invalidInput("OnFailureConfiguration.Arn must be the ARN of an Amazon SQS queue.");
|
||||
}
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private static JsonNode pointInTimeConfiguration(JsonNode request, String startingPosition) {
|
||||
JsonNode configuration = normalizedPointInTime(optionalStructure(request, "PointInTimeConfiguration"));
|
||||
if (configuration != null) {
|
||||
optionalEnum(configuration, "PointType", Set.of("HORIZON", "TIMESTAMP"), null);
|
||||
} else if ("POINT_IN_TIME".equals(startingPosition)) {
|
||||
throw invalidInput("StartingPosition POINT_IN_TIME requires PointInTimeConfiguration.");
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* A copy of the point-in-time configuration with its {@code StartingPoint} and {@code EndPoint} as epoch
|
||||
* seconds at millisecond precision, the form a response encodes as timestamps; null when there is none.
|
||||
*/
|
||||
private static JsonNode normalizedPointInTime(JsonNode configuration) {
|
||||
if (configuration == null || configuration.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!(configuration instanceof ObjectNode structure)) {
|
||||
throw invalidInput("PointInTimeConfiguration must be a structure.");
|
||||
}
|
||||
ObjectNode normalized = structure.deepCopy();
|
||||
for (String member : List.of("StartingPoint", "EndPoint")) {
|
||||
Instant point = AwsJsonTimestamp.epochSeconds(structure, member, "InvalidInputException");
|
||||
if (point != null) {
|
||||
normalized.put(member, BigDecimal.valueOf(point.toEpochMilli()).movePointLeft(3));
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/** The structure, each named integer member of it within its bounds. */
|
||||
private static JsonNode boundedIntegers(JsonNode request, String field, Map<String, int[]> bounds) {
|
||||
JsonNode structure = optionalStructure(request, field);
|
||||
if (structure == null) {
|
||||
return null;
|
||||
}
|
||||
bounds.forEach((member, range) -> {
|
||||
JsonNode value = structure.get(member);
|
||||
if (value != null && !value.isNull() && (!value.isIntegralNumber() || !value.canConvertToInt()
|
||||
|| value.intValue() < range[0] || value.intValue() > range[1])) {
|
||||
throw invalidInput(field + "." + member + " must be between " + range[0] + " and " + range[1] + ".");
|
||||
}
|
||||
});
|
||||
return structure;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Lookups ────────────────────────────
|
||||
|
||||
private EventBusV2 requireEventBus(String eventBusArn, String region) {
|
||||
return findEventBus(eventBusArn, region).orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Event bus " + eventBusArn + " does not exist.", 404));
|
||||
}
|
||||
|
||||
private SubscriberV2 requireSubscriber(String subscriberArn, String region) {
|
||||
return findSubscriber(subscriberArn, region).orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Subscriber " + subscriberArn + " does not exist.", 404));
|
||||
}
|
||||
|
||||
private List<SubscriberV2> subscribersOf(EventBusV2 bus, String region) {
|
||||
String prefix = region + "::" + bus.getName() + "::";
|
||||
return subscribers.scan(key -> key.startsWith(prefix)).stream()
|
||||
.filter(subscriber -> bus.getArn().equals(subscriber.getEventBusArn()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** The bus name an {@code event-busv2/<name>/<id>} ARN gives; null for any other value. */
|
||||
public static String busName(String eventBusArn) {
|
||||
if (!AwsArnUtils.isArnFor(eventBusArn, "events")) {
|
||||
return null;
|
||||
}
|
||||
String[] resource = AwsArnUtils.parse(eventBusArn).resource().split("/");
|
||||
return resource.length == 3 && "event-busv2".equals(resource[0]) ? resource[1] : null;
|
||||
}
|
||||
|
||||
private String newId() {
|
||||
StringBuilder id = new StringBuilder(ID_LENGTH);
|
||||
for (int i = 0; i < ID_LENGTH; i++) {
|
||||
id.append(ID_ALPHABET.charAt(random.nextInt(ID_ALPHABET.length())));
|
||||
}
|
||||
return id.toString();
|
||||
}
|
||||
|
||||
private static String storageKey(String region, String name) {
|
||||
return region + "::" + name;
|
||||
}
|
||||
|
||||
private static String subscriberKey(String region, String busName, String name) {
|
||||
return region + "::" + busName + "::" + name;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Validation ────────────────────────────
|
||||
|
||||
private static String requireName(JsonNode request) {
|
||||
String name = text(request, "Name");
|
||||
if (name == null) {
|
||||
throw invalidInput("Name is required.");
|
||||
}
|
||||
if (name.isEmpty() || name.length() > 256 || !NAME.matcher(name).matches()) {
|
||||
throw invalidInput("Name must be 1-256 characters, start with a letter or digit, and contain only "
|
||||
+ "letters, digits, '.', '-' and '_'.");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private static String optionalNamePrefix(JsonNode request) {
|
||||
String namePrefix = text(request, "NamePrefix");
|
||||
if (namePrefix != null && (namePrefix.isEmpty() || namePrefix.length() > 256
|
||||
|| !NAME.matcher(namePrefix).matches())) {
|
||||
throw invalidInput("NamePrefix must be 1-256 characters, start with a letter or digit, and contain only "
|
||||
+ "letters, digits, '.', '-' and '_'.");
|
||||
}
|
||||
return namePrefix;
|
||||
}
|
||||
|
||||
/** One page of {@code items} in {@code cursorOf} order, as the request's {@code MaxResults} and {@code NextToken} ask. */
|
||||
private static <T> PaginatedResult<T> page(List<T> items, Function<T, String> cursorOf, JsonNode request,
|
||||
String namespace) {
|
||||
Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException");
|
||||
if (maxResults != null && (maxResults < 1 || maxResults > MAX_LIST_RESULTS)) {
|
||||
throw invalidInput("MaxResults must be between 1 and " + MAX_LIST_RESULTS + ".");
|
||||
}
|
||||
String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException");
|
||||
if (nextToken != null && (nextToken.isEmpty() || nextToken.length() > 4096)) {
|
||||
throw invalidInput("NextToken must be 1-4096 characters.");
|
||||
}
|
||||
return Pagination.paginate(items, cursorOf, maxResults == null ? MAX_LIST_RESULTS : maxResults, nextToken,
|
||||
namespace, token -> invalidInput("NextToken is not valid."));
|
||||
}
|
||||
|
||||
private static String optionalDescription(JsonNode request) {
|
||||
String description = text(request, "Description");
|
||||
if (description != null && (description.length() > 512 || !DESCRIPTION.matcher(description).matches())) {
|
||||
throw invalidInput("Description must be at most 512 characters with no control characters or line "
|
||||
+ "separators.");
|
||||
}
|
||||
return description;
|
||||
}
|
||||
|
||||
private static String optionalKmsKeyIdentifier(JsonNode request) {
|
||||
JsonNode configuration = optionalStructure(request, "EncryptionConfiguration");
|
||||
String key = configuration == null ? null : text(configuration, "KmsKeyIdentifier");
|
||||
if (key != null && (key.length() > 2048 || !KMS_KEY_IDENTIFIER.matcher(key).matches())) {
|
||||
throw invalidInput("EncryptionConfiguration.KmsKeyIdentifier is not a valid KMS key identifier.");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
private static Integer optionalRetentionPeriodInDays(JsonNode request) {
|
||||
JsonNode configuration = optionalStructure(request, "StorageConfiguration");
|
||||
JsonNode days = configuration == null ? null : configuration.get("RetentionPeriodInDays");
|
||||
if (days == null || days.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!days.canConvertToInt() || !days.isIntegralNumber() || days.intValue() < 1 || days.intValue() > 365) {
|
||||
throw invalidInput("StorageConfiguration.RetentionPeriodInDays must be between 1 and 365.");
|
||||
}
|
||||
return days.intValue();
|
||||
}
|
||||
|
||||
private static String optionalClientToken(JsonNode request) {
|
||||
String token = text(request, "ClientToken");
|
||||
if (token != null && (token.isEmpty() || token.length() > 64 || !CLIENT_TOKEN.matcher(token).matches())) {
|
||||
throw invalidInput("ClientToken must be 1-64 printable ASCII characters.");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
private static String optionalEnum(JsonNode request, String field, Set<String> values, String defaultValue) {
|
||||
String value = text(request, field);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (!values.contains(value)) {
|
||||
throw invalidInput(field + " must be one of " + String.join(", ", values.stream().sorted().toList()) + ".");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Map<String, String> readTags(JsonNode node) {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
if (node == null || node.isNull()) {
|
||||
return tags;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw invalidInput("Tags must be a map of tag keys to values.");
|
||||
}
|
||||
if (node.size() > MAX_TAGS) {
|
||||
throw invalidInput("Tags may hold at most " + MAX_TAGS + " tags.");
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> tag : node.properties()) {
|
||||
String key = tag.getKey();
|
||||
JsonNode value = tag.getValue();
|
||||
if (key.length() > 128 || !TAG_KEY.matcher(key).matches()) {
|
||||
throw invalidInput("Tag key " + key + " must be 1-128 characters and not start or end with whitespace.");
|
||||
}
|
||||
if (!value.isTextual() || value.textValue().length() > 256
|
||||
|| !TAG_VALUE.matcher(value.textValue()).matches()) {
|
||||
throw invalidInput("Tag value for " + key + " must be at most 256 characters and not start or end "
|
||||
+ "with whitespace.");
|
||||
}
|
||||
tags.put(key, value.textValue());
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/**
|
||||
* The request without its {@code ClientToken}, every object's fields in name order, so a retry that sends the same
|
||||
* values with its fields or tags in another order compares equal to the request it repeats.
|
||||
*/
|
||||
private static String withoutClientToken(JsonNode request) {
|
||||
JsonNode copy = request.deepCopy();
|
||||
if (copy instanceof ObjectNode object) {
|
||||
object.remove("ClientToken");
|
||||
}
|
||||
try {
|
||||
return CANONICAL.writeValueAsString(CANONICAL.convertValue(copy, Object.class));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw invalidInput("The request cannot be compared with the one its ClientToken was used for.");
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode optionalStructure(JsonNode request, String field) {
|
||||
JsonNode node = request.get(field);
|
||||
if (node == null || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw invalidInput(field + " must be a structure.");
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static String requireText(JsonNode request, String field) {
|
||||
String value = text(request, field);
|
||||
if (value == null || value.isEmpty()) {
|
||||
throw invalidInput(field + " is required.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String text(JsonNode request, String field) {
|
||||
JsonNode node = request.get(field);
|
||||
if (node == null || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isTextual()) {
|
||||
throw invalidInput(field + " must be a string.");
|
||||
}
|
||||
return node.textValue();
|
||||
}
|
||||
|
||||
private static AwsException idempotentMismatch(String clientToken) {
|
||||
return new AwsException("IdempotentParameterMismatchException",
|
||||
"ClientToken " + clientToken + " was used with a different request.", 409);
|
||||
}
|
||||
|
||||
private static AwsException invalidInput(String message) {
|
||||
return new AwsException("InvalidInputException", message, 400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package io.github.hectorvent.floci.services.eventbridgev2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The JSONata a target parameter may hold, as far as Floci evaluates it: a literal value, or one expression in
|
||||
* {@code {% %}} that is a path into the event, {@code $events.SystemMetadata.EventGroupId}, whose segments are
|
||||
* names, {@code "quoted"} or {@code `backquoted`} for a name such as {@code aws:EventId} or {@code detail-type}.
|
||||
*/
|
||||
final class EventExpressions {
|
||||
|
||||
private static final Pattern EXPRESSION = Pattern.compile("\\{%[\\s\\S]*%}");
|
||||
private static final Pattern PATH = Pattern.compile("\\{%\\s*\\$events((?:\\.(?:[A-Za-z_][A-Za-z0-9_]*"
|
||||
+ "|\"[^\"]+\"|`[^`]+`))+)\\s*%}");
|
||||
private static final Pattern SEGMENT = Pattern.compile("\\.([A-Za-z_][A-Za-z0-9_]*|\"([^\"]+)\"|`([^`]+)`)");
|
||||
|
||||
private EventExpressions() {
|
||||
}
|
||||
|
||||
static boolean isExpression(String value) {
|
||||
return value != null && EXPRESSION.matcher(value.trim()).matches();
|
||||
}
|
||||
|
||||
/** Whether Floci evaluates the value: a literal, or an expression that is a path into the event. */
|
||||
static boolean isSupported(String value) {
|
||||
return !isExpression(value) || PATH.matcher(value.trim()).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* The value for one event: a literal as given, a path's value as text (a string unquoted, anything else as
|
||||
* JSON), or empty when the path names nothing, which fails the delivery as AWS fails it.
|
||||
*/
|
||||
static Optional<String> resolve(String value, PublishedEvent event) {
|
||||
if (!isExpression(value)) {
|
||||
return Optional.of(value);
|
||||
}
|
||||
Matcher path = PATH.matcher(value.trim());
|
||||
if (!path.matches()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
JsonNode node = event.withMetadata();
|
||||
for (String segment : segments(path.group(1))) {
|
||||
node = node == null || !node.isObject() ? null : node.get(segment);
|
||||
}
|
||||
if (node == null || node.isNull()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(node.isTextual() ? node.textValue() : node.toString());
|
||||
}
|
||||
|
||||
private static List<String> segments(String path) {
|
||||
List<String> segments = new ArrayList<>();
|
||||
Matcher segment = SEGMENT.matcher(path);
|
||||
while (segment.find()) {
|
||||
segments.add(segment.group(2) != null ? segment.group(2)
|
||||
: segment.group(3) != null ? segment.group(3) : segment.group(1));
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package io.github.hectorvent.floci.services.eventbridgev2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* An event on an EventBridge V2 bus, in the three parts filters, transformers and target parameters address:
|
||||
* {@code Data}, the payload (for {@code PutEvents}, the EventBridge envelope); {@code Metadata}, the producer's
|
||||
* keys; and {@code SystemMetadata}, the string fields EventBridge assigns.
|
||||
*/
|
||||
record PublishedEvent(JsonNode data, ObjectNode metadata, ObjectNode systemMetadata) {
|
||||
|
||||
/** The event as {@code $events} and a {@code WITH_METADATA} delivery hold it. */
|
||||
ObjectNode withMetadata() {
|
||||
ObjectNode event = JsonNodeFactory.instance.objectNode();
|
||||
event.set("Data", data);
|
||||
event.set("Metadata", metadata);
|
||||
event.set("SystemMetadata", systemMetadata);
|
||||
return event;
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package io.github.hectorvent.floci.services.eventbridgev2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* An EventBridge V2 subscriber's {@code FilterConfiguration}: at most one EventBridge pattern for each scope of the
|
||||
* event, {@code DATA}, {@code METADATA} or {@code SYSTEM_METADATA}, every one of which an event must match.
|
||||
*/
|
||||
final class SubscriberFilters {
|
||||
|
||||
static final String WILDCARD_MESSAGE =
|
||||
"Filter pattern must not contain wildcard matchers (wildcard, anything-but wildcard)";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Set<String> SCOPES = Set.of("DATA", "METADATA", "SYSTEM_METADATA");
|
||||
private static final Set<String> NUMERIC_OPERATORS = Set.of("=", ">", ">=", "<", "<=");
|
||||
private static final int MAX_FILTERS = 50;
|
||||
private static final int MAX_PATTERN_BYTES = 4096;
|
||||
private static final int MAX_OR_COMBINATIONS = 1000;
|
||||
|
||||
private SubscriberFilters() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects a configuration AWS rejects: one with no filters or an empty pattern, two filters of one scope, a
|
||||
* pattern that is not JSON, a wildcard, a {@code METADATA} pattern of anything but exact values, a pattern
|
||||
* that is not an object, more than 1,000 {@code $or} combinations, or patterns over 4,096 bytes in all.
|
||||
*/
|
||||
static void validate(JsonNode configuration) {
|
||||
if (!configuration.isObject()) {
|
||||
throw invalid("FilterConfiguration must be a structure.");
|
||||
}
|
||||
JsonNode language = configuration.get("Language");
|
||||
if (language != null && !language.isNull() && !"EVENT_BRIDGE_PATTERN".equals(language.asText())) {
|
||||
throw invalid("FilterConfiguration.Language must be EVENT_BRIDGE_PATTERN.");
|
||||
}
|
||||
JsonNode filters = configuration.get("Filters");
|
||||
if (filters == null || !filters.isArray() || filters.isEmpty() || filters.size() > MAX_FILTERS) {
|
||||
throw invalid("FilterConfiguration.Filters must hold 1 to " + MAX_FILTERS + " filters.");
|
||||
}
|
||||
Set<String> scopes = new HashSet<>();
|
||||
int bytes = 0;
|
||||
for (JsonNode filter : filters) {
|
||||
String scope = filter.path("Scope").asText(null);
|
||||
if (scope == null || !SCOPES.contains(scope)) {
|
||||
throw invalid("Filter Scope must be DATA, METADATA or SYSTEM_METADATA.");
|
||||
}
|
||||
if (!scopes.add(scope)) {
|
||||
throw invalid("FilterConfiguration may hold at most one filter for the scope " + scope + ".");
|
||||
}
|
||||
JsonNode patternText = filter.get("Pattern");
|
||||
if (patternText == null || !patternText.isTextual() || patternText.textValue().isBlank()) {
|
||||
throw invalid("Filter Pattern must be a non-empty event pattern.");
|
||||
}
|
||||
bytes += patternText.textValue().getBytes(StandardCharsets.UTF_8).length;
|
||||
JsonNode pattern = parse(patternText.textValue());
|
||||
if (!pattern.isObject()) {
|
||||
throw invalid("Filter pattern for the scope " + scope + " must be a JSON object.");
|
||||
}
|
||||
checkMatchers(pattern);
|
||||
if ("METADATA".equals(scope) && !exactValuesOnly(pattern)) {
|
||||
throw invalid("A METADATA filter pattern must give each key a list of exact values.");
|
||||
}
|
||||
if (orCombinations(pattern) > MAX_OR_COMBINATIONS) {
|
||||
throw invalid("Filter pattern produces more than " + MAX_OR_COMBINATIONS + " combinations.");
|
||||
}
|
||||
}
|
||||
if (bytes > MAX_PATTERN_BYTES) {
|
||||
throw invalid("FilterConfiguration patterns may total at most " + MAX_PATTERN_BYTES + " bytes.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the event matches every filter of the configuration; an absent configuration matches every event. */
|
||||
static boolean matches(JsonNode configuration, PublishedEvent event) {
|
||||
if (configuration == null || configuration.isNull() || !configuration.has("Filters")) {
|
||||
return true;
|
||||
}
|
||||
for (JsonNode filter : configuration.get("Filters")) {
|
||||
JsonNode scope = switch (filter.path("Scope").asText()) {
|
||||
case "DATA" -> event.data();
|
||||
case "METADATA" -> event.metadata();
|
||||
default -> event.systemMetadata();
|
||||
};
|
||||
if (!PipesFilterMatcher.matches(parse(filter.path("Pattern").asText()), scope)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static JsonNode parse(String pattern) {
|
||||
try {
|
||||
return MAPPER.readTree(pattern);
|
||||
} catch (Exception e) {
|
||||
throw invalid("Filter pattern is not valid JSON.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a wildcard, as AWS does, and a matcher {@link PipesFilterMatcher} cannot evaluate, which would
|
||||
* otherwise match no event or every event without a word. A matcher is an object in a field's list of values;
|
||||
* an object anywhere else is a nested pattern, so a field named after an operator is matched as a field.
|
||||
*/
|
||||
private static void checkMatchers(JsonNode pattern) {
|
||||
for (Map.Entry<String, JsonNode> field : pattern.properties()) {
|
||||
JsonNode value = field.getValue();
|
||||
boolean or = "$or".equals(field.getKey());
|
||||
if (or && (!value.isArray() || value.size() < 2)) {
|
||||
throw invalid("Filter pattern $or must be a list of at least two patterns.");
|
||||
}
|
||||
if (value.isObject()) {
|
||||
checkMatchers(value);
|
||||
} else if (value.isArray()) {
|
||||
if (value.isEmpty()) {
|
||||
throw invalid("Filter pattern field " + field.getKey() + " must contain at least one value.");
|
||||
}
|
||||
for (JsonNode element : value) {
|
||||
if (or && element.isObject()) {
|
||||
checkMatchers(element);
|
||||
} else if (or) {
|
||||
throw invalid("Filter pattern $or must be a list of patterns.");
|
||||
} else if (element.isObject()) {
|
||||
checkMatcher(element);
|
||||
} else if (element.isArray()) {
|
||||
throw invalid("Filter pattern field " + field.getKey() + " must list values and matchers, "
|
||||
+ "not lists.");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw invalid("Filter pattern field " + field.getKey() + " must be a list of values or a nested "
|
||||
+ "pattern.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkMatcher(JsonNode matcher) {
|
||||
JsonNode anythingBut = matcher.get("anything-but");
|
||||
if (matcher.has("wildcard") || anythingBut != null && anythingBut.has("wildcard")) {
|
||||
throw invalid(WILDCARD_MESSAGE);
|
||||
}
|
||||
String operator = matcher.size() == 1 ? matcher.fieldNames().next() : "";
|
||||
JsonNode operand = matcher.path(operator);
|
||||
boolean supported = switch (operator) {
|
||||
case "exists" -> operand.isBoolean();
|
||||
case "prefix", "suffix" -> operand.isTextual() || ignoringCase(operand);
|
||||
case "equals-ignore-case" -> operand.isTextual();
|
||||
case "numeric" -> numericConditions(operand);
|
||||
case "anything-but" -> operand.isValueNode()
|
||||
|| operand.isArray() && !operand.isEmpty() && allValues(operand)
|
||||
|| operand.size() == 1 && (operand.path("prefix").isTextual()
|
||||
|| operand.path("suffix").isTextual() || operand.path("equals-ignore-case").isTextual()
|
||||
|| operand.path("equals-ignore-case").isArray()
|
||||
&& !operand.path("equals-ignore-case").isEmpty()
|
||||
&& allValues(operand.get("equals-ignore-case")));
|
||||
default -> false;
|
||||
};
|
||||
if (!supported) {
|
||||
throw invalid("Floci does not evaluate the filter matcher " + matcher + "; it supports exact values, "
|
||||
+ "prefix, suffix, equals-ignore-case, anything-but, numeric, exists and $or.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the operand is one or more pairs of a comparison operator and a number. */
|
||||
private static boolean numericConditions(JsonNode operand) {
|
||||
if (!operand.isArray() || operand.isEmpty() || operand.size() % 2 != 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < operand.size(); i += 2) {
|
||||
JsonNode operator = operand.get(i);
|
||||
if (!operator.isTextual() || !NUMERIC_OPERATORS.contains(operator.textValue())
|
||||
|| !operand.get(i + 1).isNumber()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean ignoringCase(JsonNode operand) {
|
||||
return operand.isObject() && operand.size() == 1 && operand.path("equals-ignore-case").isTextual();
|
||||
}
|
||||
|
||||
private static boolean allValues(JsonNode array) {
|
||||
for (JsonNode element : array) {
|
||||
if (!element.isValueNode()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean exactValuesOnly(JsonNode pattern) {
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = pattern.fields();
|
||||
while (fields.hasNext()) {
|
||||
JsonNode values = fields.next().getValue();
|
||||
if (!values.isArray() || values.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (JsonNode value : values) {
|
||||
if (!value.isTextual()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of patterns the {@code $or} lists expand to. The branches of one {@code $or} are alternatives, so
|
||||
* their counts add up; the fields of a pattern must all match, so theirs multiply. Counting stops once it passes
|
||||
* the limit.
|
||||
*/
|
||||
private static long orCombinations(JsonNode node) {
|
||||
if (!node.isObject()) {
|
||||
return 1;
|
||||
}
|
||||
long combinations = 1;
|
||||
for (Map.Entry<String, JsonNode> field : node.properties()) {
|
||||
long fieldCombinations = 0;
|
||||
if ("$or".equals(field.getKey())) {
|
||||
for (JsonNode branch : field.getValue()) {
|
||||
fieldCombinations += orCombinations(branch);
|
||||
if (fieldCombinations > MAX_OR_COMBINATIONS) {
|
||||
return fieldCombinations;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fieldCombinations = orCombinations(field.getValue());
|
||||
}
|
||||
combinations *= Math.max(1, fieldCombinations);
|
||||
if (combinations > MAX_OR_COMBINATIONS) {
|
||||
return combinations;
|
||||
}
|
||||
}
|
||||
return combinations;
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidInputException", message, 400);
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package io.github.hectorvent.floci.services.eventbridgev2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class EventBusV2 {
|
||||
private String name;
|
||||
private String arn;
|
||||
private String description;
|
||||
private String kmsKeyIdentifier;
|
||||
private Integer retentionPeriodInDays;
|
||||
private String state;
|
||||
private Instant creationTime;
|
||||
private Instant lastModifiedTime;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
private String clientToken;
|
||||
private String createRequest;
|
||||
private long sequenceNumber;
|
||||
|
||||
public EventBusV2() {
|
||||
}
|
||||
|
||||
/** The sequence number of the last event the bus accepted; the next is one more. */
|
||||
public long getSequenceNumber() {
|
||||
return sequenceNumber;
|
||||
}
|
||||
|
||||
public void setSequenceNumber(long sequenceNumber) {
|
||||
this.sequenceNumber = sequenceNumber;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getArn() {
|
||||
return arn;
|
||||
}
|
||||
|
||||
public void setArn(String arn) {
|
||||
this.arn = arn;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getKmsKeyIdentifier() {
|
||||
return kmsKeyIdentifier;
|
||||
}
|
||||
|
||||
public void setKmsKeyIdentifier(String kmsKeyIdentifier) {
|
||||
this.kmsKeyIdentifier = kmsKeyIdentifier;
|
||||
}
|
||||
|
||||
public Integer getRetentionPeriodInDays() {
|
||||
return retentionPeriodInDays;
|
||||
}
|
||||
|
||||
public void setRetentionPeriodInDays(Integer retentionPeriodInDays) {
|
||||
this.retentionPeriodInDays = retentionPeriodInDays;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public Instant getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
public void setCreationTime(Instant creationTime) {
|
||||
this.creationTime = creationTime;
|
||||
}
|
||||
|
||||
public Instant getLastModifiedTime() {
|
||||
return lastModifiedTime;
|
||||
}
|
||||
|
||||
public void setLastModifiedTime(Instant lastModifiedTime) {
|
||||
this.lastModifiedTime = lastModifiedTime;
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags == null ? new LinkedHashMap<>() : tags;
|
||||
}
|
||||
|
||||
/** The {@code ClientToken} the bus was created with, which makes a retried create return it. */
|
||||
public String getClientToken() {
|
||||
return clientToken;
|
||||
}
|
||||
|
||||
public void setClientToken(String clientToken) {
|
||||
this.clientToken = clientToken;
|
||||
}
|
||||
|
||||
/** The create request without its client token, which a retry with the same token must repeat. */
|
||||
public String getCreateRequest() {
|
||||
return createRequest;
|
||||
}
|
||||
|
||||
public void setCreateRequest(String createRequest) {
|
||||
this.createRequest = createRequest;
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
package io.github.hectorvent.floci.services.eventbridgev2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* An EventBridge V2 subscriber. The configuration structures are kept as the request gave them, as the
|
||||
* subscriber returns them.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SubscriberV2 {
|
||||
private String name;
|
||||
private String arn;
|
||||
private String eventBusArn;
|
||||
private String description;
|
||||
private String type;
|
||||
private String startingPosition;
|
||||
private String state;
|
||||
private JsonNode pointInTimeConfiguration;
|
||||
private JsonNode invokeConfiguration;
|
||||
private JsonNode filterConfiguration;
|
||||
private JsonNode transformer;
|
||||
private JsonNode batchConfiguration;
|
||||
private JsonNode retryPolicy;
|
||||
private JsonNode onFailureConfiguration;
|
||||
private JsonNode logConfiguration;
|
||||
private Instant creationTime;
|
||||
private Instant lastModifiedTime;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
private String clientToken;
|
||||
private String createRequest;
|
||||
|
||||
public SubscriberV2() {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getArn() {
|
||||
return arn;
|
||||
}
|
||||
|
||||
public void setArn(String arn) {
|
||||
this.arn = arn;
|
||||
}
|
||||
|
||||
public String getEventBusArn() {
|
||||
return eventBusArn;
|
||||
}
|
||||
|
||||
public void setEventBusArn(String eventBusArn) {
|
||||
this.eventBusArn = eventBusArn;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getStartingPosition() {
|
||||
return startingPosition;
|
||||
}
|
||||
|
||||
public void setStartingPosition(String startingPosition) {
|
||||
this.startingPosition = startingPosition;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public JsonNode getPointInTimeConfiguration() {
|
||||
return pointInTimeConfiguration;
|
||||
}
|
||||
|
||||
public void setPointInTimeConfiguration(JsonNode pointInTimeConfiguration) {
|
||||
this.pointInTimeConfiguration = pointInTimeConfiguration;
|
||||
}
|
||||
|
||||
public JsonNode getInvokeConfiguration() {
|
||||
return invokeConfiguration;
|
||||
}
|
||||
|
||||
public void setInvokeConfiguration(JsonNode invokeConfiguration) {
|
||||
this.invokeConfiguration = invokeConfiguration;
|
||||
}
|
||||
|
||||
public JsonNode getFilterConfiguration() {
|
||||
return filterConfiguration;
|
||||
}
|
||||
|
||||
public void setFilterConfiguration(JsonNode filterConfiguration) {
|
||||
this.filterConfiguration = filterConfiguration;
|
||||
}
|
||||
|
||||
public JsonNode getTransformer() {
|
||||
return transformer;
|
||||
}
|
||||
|
||||
public void setTransformer(JsonNode transformer) {
|
||||
this.transformer = transformer;
|
||||
}
|
||||
|
||||
public JsonNode getBatchConfiguration() {
|
||||
return batchConfiguration;
|
||||
}
|
||||
|
||||
public void setBatchConfiguration(JsonNode batchConfiguration) {
|
||||
this.batchConfiguration = batchConfiguration;
|
||||
}
|
||||
|
||||
public JsonNode getRetryPolicy() {
|
||||
return retryPolicy;
|
||||
}
|
||||
|
||||
public void setRetryPolicy(JsonNode retryPolicy) {
|
||||
this.retryPolicy = retryPolicy;
|
||||
}
|
||||
|
||||
public JsonNode getOnFailureConfiguration() {
|
||||
return onFailureConfiguration;
|
||||
}
|
||||
|
||||
public void setOnFailureConfiguration(JsonNode onFailureConfiguration) {
|
||||
this.onFailureConfiguration = onFailureConfiguration;
|
||||
}
|
||||
|
||||
public JsonNode getLogConfiguration() {
|
||||
return logConfiguration;
|
||||
}
|
||||
|
||||
public void setLogConfiguration(JsonNode logConfiguration) {
|
||||
this.logConfiguration = logConfiguration;
|
||||
}
|
||||
|
||||
public Instant getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
public void setCreationTime(Instant creationTime) {
|
||||
this.creationTime = creationTime;
|
||||
}
|
||||
|
||||
public Instant getLastModifiedTime() {
|
||||
return lastModifiedTime;
|
||||
}
|
||||
|
||||
public void setLastModifiedTime(Instant lastModifiedTime) {
|
||||
this.lastModifiedTime = lastModifiedTime;
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags == null ? new LinkedHashMap<>() : tags;
|
||||
}
|
||||
|
||||
public String getClientToken() {
|
||||
return clientToken;
|
||||
}
|
||||
|
||||
public void setClientToken(String clientToken) {
|
||||
this.clientToken = clientToken;
|
||||
}
|
||||
|
||||
public String getCreateRequest() {
|
||||
return createRequest;
|
||||
}
|
||||
|
||||
public void setCreateRequest(String createRequest) {
|
||||
this.createRequest = createRequest;
|
||||
}
|
||||
}
|
||||
@@ -1875,28 +1875,39 @@ public class LambdaService implements ResourceProvider {
|
||||
/** Operators AWS documents that the matcher does not implement, rejected with a clearer message. */
|
||||
private static final Set<String> UNIMPLEMENTED_FILTER_OPERATORS = Set.of("cidr", "wildcard");
|
||||
|
||||
/** Comparisons {@code matchesNumericFilter} understands. Anything else evaluates false for every record. */
|
||||
/** Comparisons {@code PipesFilterMatcher} understands. It treats a pattern with any other as matching nothing. */
|
||||
private static final Set<String> NUMERIC_COMPARISONS = Set.of("=", ">", ">=", "<", "<=");
|
||||
|
||||
/**
|
||||
* Validates the recursive shape of an EventBridge filter pattern: every field value must be either a
|
||||
* non-empty match array (a leaf) or a nested object (recursed into). A scalar or empty-array value is a
|
||||
* non-empty match array (a leaf) or a nested object (recursed into), and {@code $or} a non-empty list of
|
||||
* patterns, each validated the same way. A scalar or empty-array value is a
|
||||
* pattern the matcher can never satisfy, so, with enforcement active, it would silently drop every
|
||||
* record; reject it at create/update instead.
|
||||
*
|
||||
* <p>Match-array elements are validated against the operator set the matcher implements. This does couple
|
||||
* the validator to {@code PipesFilterMatcher}, which is deliberate: now that the pollers enforce filters,
|
||||
* a pattern the matcher cannot satisfy is destructive rather than inert. A bad operand silently corrupts
|
||||
* delivery instead of erroring, and the failure direction is not even consistent. {@code
|
||||
* {"numeric":[">","abc"]}} coerces its operand to zero and matches every positive value, {@code
|
||||
* {"numeric":[">"]}} matches every record because the comparison loop never runs, and an unknown operator
|
||||
* matches nothing, so every record is checkpointed past or deleted. Failing at create/update is the only
|
||||
* a pattern the matcher cannot evaluate is destructive rather than inert. The matcher refuses an unknown
|
||||
* operator or a bad operand such as {@code {"numeric":[">","abc"]}}, and the pollers treat a refused pattern
|
||||
* as matching nothing, so every record is checkpointed past or deleted. Failing at create/update is the only
|
||||
* point where the caller can still act on it.
|
||||
*/
|
||||
private static void validatePatternStructure(JsonNode node) {
|
||||
for (Map.Entry<String, JsonNode> entry : node.properties()) {
|
||||
JsonNode value = entry.getValue();
|
||||
if (value.isArray()) {
|
||||
if ("$or".equals(entry.getKey())) {
|
||||
if (!value.isArray() || value.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Filter Pattern field '$or' must be a non-empty list of patterns", 400);
|
||||
}
|
||||
for (JsonNode branch : value) {
|
||||
if (!branch.isObject()) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Filter Pattern field '$or' must be a non-empty list of patterns", 400);
|
||||
}
|
||||
validatePatternStructure(branch);
|
||||
}
|
||||
} else if (value.isArray()) {
|
||||
if (value.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Filter Pattern field '" + entry.getKey() + "' must have a non-empty match array", 400);
|
||||
@@ -1914,17 +1925,17 @@ public class LambdaService implements ResourceProvider {
|
||||
}
|
||||
|
||||
/**
|
||||
* A match-array element is either a literal the matcher compares directly (string, number, or null for
|
||||
* "absent") or a single-operator object. Two operators in one object is rejected because the matcher
|
||||
* A match-array element is either a literal the matcher compares directly (string, number, boolean, or
|
||||
* null) or a single-operator object. Two operators in one object is rejected because the matcher
|
||||
* tests them in a fixed order and silently honours only the first.
|
||||
*/
|
||||
private static void validateMatchElement(String field, JsonNode element) {
|
||||
if (element.isTextual() || element.isNumber() || element.isNull()) {
|
||||
if (element.isTextual() || element.isNumber() || element.isBoolean() || element.isNull()) {
|
||||
return;
|
||||
}
|
||||
if (!element.isObject()) {
|
||||
throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
|
||||
+ "' has an invalid match value: expected a string, number, null, or an operator object", 400);
|
||||
+ "' has an invalid match value: expected a string, number, boolean, null, or an operator object", 400);
|
||||
}
|
||||
List<String> operators = new ArrayList<>();
|
||||
element.fieldNames().forEachRemaining(operators::add);
|
||||
|
||||
@@ -6,12 +6,22 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* EventBridge event pattern matching, shared by EventBridge Pipes, the Lambda event source mappings and the
|
||||
* EventBridge V2 subscribers. A field's pattern is a list of alternatives, any of which matches, or a nested
|
||||
* pattern for an object; {@code $or} takes a list of patterns, any of which matches. A field whose value is an
|
||||
* array matches when any of its elements does.
|
||||
*
|
||||
* <p>A pattern the matcher cannot evaluate throws {@link IllegalArgumentException}: whether that is refused up
|
||||
* front or treated as matching nothing is the calling service's choice.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class PipesFilterMatcher {
|
||||
|
||||
@@ -55,149 +65,242 @@ public class PipesFilterMatcher {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a source record matches the pattern. A string field the pattern nests an object under is parsed as
|
||||
* JSON first, as for an SQS {@code body} or a Kinesis {@code data}. A pattern that is not valid matches nothing.
|
||||
*/
|
||||
boolean matchesRecord(JsonNode record, String pattern) {
|
||||
if (pattern == null || pattern.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
JsonNode patternNode = objectMapper.readTree(pattern);
|
||||
return matchesNode(record, patternNode);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse filter pattern: {0}", e.getMessage());
|
||||
return matches(objectMapper.readTree(pattern), record, objectMapper);
|
||||
} catch (IllegalArgumentException | IOException e) {
|
||||
LOG.warnv("Invalid filter pattern {0}: {1}", pattern, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean matchesNode(JsonNode actual, JsonNode pattern) {
|
||||
/**
|
||||
* Whether the document matches the pattern, as EventBridge matches it.
|
||||
*
|
||||
* @throws IllegalArgumentException if the pattern is not one the matcher can evaluate
|
||||
*/
|
||||
public static boolean matches(JsonNode pattern, JsonNode actual) {
|
||||
return matches(pattern, actual, null);
|
||||
}
|
||||
|
||||
/** {@code decoder}, when given, parses a string field the pattern nests an object under. */
|
||||
private static boolean matches(JsonNode pattern, JsonNode actual, ObjectMapper decoder) {
|
||||
if (!pattern.isObject()) {
|
||||
return false;
|
||||
throw new IllegalArgumentException("a pattern must be a JSON object");
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = pattern.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
String key = field.getKey();
|
||||
JsonNode patternValue = field.getValue();
|
||||
JsonNode actualValue = actual.path(key);
|
||||
|
||||
if (patternValue.isArray()) {
|
||||
if (!matchesArrayField(patternValue, actualValue)) {
|
||||
if ("$or".equals(field.getKey())) {
|
||||
if (!anyMatches(field.getValue(), actual, decoder)) {
|
||||
return false;
|
||||
}
|
||||
} else if (patternValue.isObject()) {
|
||||
JsonNode resolvedActual = resolveActualForObject(actualValue);
|
||||
if (!matchesNode(resolvedActual, patternValue)) {
|
||||
continue;
|
||||
}
|
||||
JsonNode value = actual == null || !actual.isObject() ? null : actual.get(field.getKey());
|
||||
JsonNode expected = field.getValue();
|
||||
if (expected.isObject()) {
|
||||
boolean nestedMatches = value == null
|
||||
? matches(expected, null, decoder)
|
||||
: matchesNested(expected, decoded(value, decoder), decoder);
|
||||
if (!nestedMatches) {
|
||||
return false;
|
||||
}
|
||||
} else if (expected.isArray()) {
|
||||
if (!matchesAlternatives(field.getKey(), expected, value)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
LOG.warnv("Invalid filter pattern: scalar value for key \"{0}\". " +
|
||||
"Pattern values must be arrays or objects.", key);
|
||||
return false;
|
||||
throw new IllegalArgumentException("field " + field.getKey()
|
||||
+ " must be a list of values or a nested pattern");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private JsonNode resolveActualForObject(JsonNode actualValue) {
|
||||
if (actualValue.isTextual()) {
|
||||
try {
|
||||
JsonNode parsed = objectMapper.readTree(actualValue.asText());
|
||||
if (parsed.isObject() || parsed.isArray()) {
|
||||
return parsed;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
private static boolean anyMatches(JsonNode patterns, JsonNode actual, ObjectMapper decoder) {
|
||||
if (!patterns.isArray()) {
|
||||
throw new IllegalArgumentException("$or must be a list of patterns");
|
||||
}
|
||||
return actualValue;
|
||||
}
|
||||
|
||||
private boolean matchesArrayField(JsonNode patternArray, JsonNode actualValue) {
|
||||
for (JsonNode element : patternArray) {
|
||||
if (matchesSingleElement(element, actualValue)) {
|
||||
for (JsonNode pattern : patterns) {
|
||||
if (matches(pattern, actual, decoder)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean matchesSingleElement(JsonNode element, JsonNode actualValue) {
|
||||
boolean valueExists = !actualValue.isMissingNode() && !actualValue.isNull();
|
||||
String actualStr = valueExists && actualValue.isTextual() ? actualValue.asText() : null;
|
||||
private static JsonNode decoded(JsonNode value, ObjectMapper decoder) {
|
||||
if (decoder == null || !value.isTextual()) {
|
||||
return value;
|
||||
}
|
||||
try {
|
||||
JsonNode parsed = decoder.readTree(value.textValue());
|
||||
if (parsed != null && (parsed.isObject() || parsed.isArray())) {
|
||||
return parsed;
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
// Not JSON: matched as the string it is, which a nested pattern never matches.
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
if (element.isTextual()) {
|
||||
return actualStr != null && actualStr.equals(element.asText());
|
||||
}
|
||||
if (element.isNull()) {
|
||||
return !valueExists;
|
||||
}
|
||||
if (element.isNumber()) {
|
||||
return valueExists && actualValue.isNumber()
|
||||
&& actualValue.decimalValue().compareTo(element.decimalValue()) == 0;
|
||||
}
|
||||
if (element.isObject()) {
|
||||
if (element.has("prefix")) {
|
||||
return actualStr != null && actualStr.startsWith(element.get("prefix").asText());
|
||||
}
|
||||
if (element.has("suffix")) {
|
||||
return actualStr != null && actualStr.endsWith(element.get("suffix").asText());
|
||||
}
|
||||
if (element.has("equals-ignore-case")) {
|
||||
return actualStr != null && actualStr.equalsIgnoreCase(element.get("equals-ignore-case").asText());
|
||||
}
|
||||
if (element.has("anything-but")) {
|
||||
JsonNode anythingBut = element.get("anything-but");
|
||||
if (anythingBut.isArray()) {
|
||||
if (!valueExists) {
|
||||
return true;
|
||||
}
|
||||
for (JsonNode v : anythingBut) {
|
||||
if (v.isTextual() && v.asText().equals(actualStr)) {
|
||||
return false;
|
||||
}
|
||||
if (v.isNumber() && actualValue.isNumber()
|
||||
&& actualValue.decimalValue().compareTo(v.decimalValue()) == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
private static boolean matchesNested(JsonNode pattern, JsonNode value, ObjectMapper decoder) {
|
||||
if (value.isArray()) {
|
||||
for (JsonNode element : value) {
|
||||
if (matches(pattern, element, decoder)) {
|
||||
return true;
|
||||
}
|
||||
if (anythingBut.isObject() && anythingBut.has("prefix")) {
|
||||
return !valueExists || (actualStr != null && !actualStr.startsWith(anythingBut.get("prefix").asText()));
|
||||
}
|
||||
if (anythingBut.isTextual()) {
|
||||
return !valueExists || (actualStr != null && !actualStr.equals(anythingBut.asText()));
|
||||
}
|
||||
}
|
||||
if (element.has("exists")) {
|
||||
boolean shouldExist = element.get("exists").asBoolean();
|
||||
return shouldExist == valueExists;
|
||||
return false;
|
||||
}
|
||||
return matches(pattern, value, decoder);
|
||||
}
|
||||
|
||||
/** Whether the field, absent as null, matches any of the alternatives. */
|
||||
private static boolean matchesAlternatives(String field, JsonNode alternatives, JsonNode value) {
|
||||
for (JsonNode alternative : alternatives) {
|
||||
if (alternative.isArray()) {
|
||||
throw new IllegalArgumentException("field " + field + " must list values and matchers, not lists");
|
||||
}
|
||||
if (element.has("numeric")) {
|
||||
return matchesNumericFilter(element.get("numeric"), actualValue);
|
||||
if (alternative.isObject() && alternative.has("exists")) {
|
||||
if (alternative.get("exists").asBoolean() == (value != null)) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
if (value.isArray()) {
|
||||
for (JsonNode element : value) {
|
||||
if (matchesOne(alternative, element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (matchesOne(alternative, value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean matchesNumericFilter(JsonNode numericArray, JsonNode actualValue) {
|
||||
if (!actualValue.isNumber() || !numericArray.isArray()) {
|
||||
private static boolean matchesOne(JsonNode alternative, JsonNode value) {
|
||||
if (!alternative.isObject()) {
|
||||
return equalsExactly(alternative, value);
|
||||
}
|
||||
if (alternative.has("prefix")) {
|
||||
return matchesAffix(alternative.get("prefix"), value, true);
|
||||
}
|
||||
if (alternative.has("suffix")) {
|
||||
return matchesAffix(alternative.get("suffix"), value, false);
|
||||
}
|
||||
if (alternative.has("equals-ignore-case")) {
|
||||
return value.isTextual() && value.textValue().equalsIgnoreCase(alternative.get("equals-ignore-case").asText());
|
||||
}
|
||||
if (alternative.has("numeric")) {
|
||||
return matchesNumeric(alternative.get("numeric"), value);
|
||||
}
|
||||
if (alternative.has("anything-but")) {
|
||||
return !matchesExcluded(alternative.get("anything-but"), value);
|
||||
}
|
||||
throw new IllegalArgumentException("unsupported matcher " + alternative);
|
||||
}
|
||||
|
||||
private static boolean matchesExcluded(JsonNode excluded, JsonNode value) {
|
||||
if (excluded.isArray()) {
|
||||
for (JsonNode each : excluded) {
|
||||
if (equalsExactly(each, value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
BigDecimal actual = actualValue.decimalValue();
|
||||
for (int i = 0; i + 1 < numericArray.size(); i += 2) {
|
||||
String op = numericArray.get(i).asText();
|
||||
BigDecimal operand = numericArray.get(i + 1).decimalValue();
|
||||
boolean result = switch (op) {
|
||||
case "=" -> actual.compareTo(operand) == 0;
|
||||
case ">" -> actual.compareTo(operand) > 0;
|
||||
case ">=" -> actual.compareTo(operand) >= 0;
|
||||
case "<" -> actual.compareTo(operand) < 0;
|
||||
case "<=" -> actual.compareTo(operand) <= 0;
|
||||
default -> false;
|
||||
if (excluded.isObject()) {
|
||||
if (excluded.has("prefix")) {
|
||||
return matchesAffix(excluded.get("prefix"), value, true);
|
||||
}
|
||||
if (excluded.has("suffix")) {
|
||||
return matchesAffix(excluded.get("suffix"), value, false);
|
||||
}
|
||||
if (excluded.has("equals-ignore-case")) {
|
||||
JsonNode names = excluded.get("equals-ignore-case");
|
||||
for (JsonNode name : names.isArray() ? names : List.of(names)) {
|
||||
if (value.isTextual() && value.textValue().equalsIgnoreCase(name.asText())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
throw new IllegalArgumentException("unsupported anything-but matcher " + excluded);
|
||||
}
|
||||
return equalsExactly(excluded, value);
|
||||
}
|
||||
|
||||
/** A prefix or suffix, given as a string or as {@code {"equals-ignore-case": ...}}. */
|
||||
private static boolean matchesAffix(JsonNode affix, JsonNode value, boolean prefix) {
|
||||
if (!value.isTextual()) {
|
||||
return false;
|
||||
}
|
||||
String text = value.textValue();
|
||||
if (affix.isObject() && affix.has("equals-ignore-case")) {
|
||||
String wanted = affix.get("equals-ignore-case").asText();
|
||||
return text.length() >= wanted.length() && (prefix
|
||||
? text.regionMatches(true, 0, wanted, 0, wanted.length())
|
||||
: text.regionMatches(true, text.length() - wanted.length(), wanted, 0, wanted.length()));
|
||||
}
|
||||
return prefix ? text.startsWith(affix.asText()) : text.endsWith(affix.asText());
|
||||
}
|
||||
|
||||
private static boolean matchesNumeric(JsonNode conditions, JsonNode value) {
|
||||
if (!conditions.isArray() || conditions.isEmpty() || conditions.size() % 2 != 0) {
|
||||
throw new IllegalArgumentException("numeric takes pairs of a comparison and a number");
|
||||
}
|
||||
if (!value.isNumber()) {
|
||||
return false;
|
||||
}
|
||||
BigDecimal actual = value.decimalValue();
|
||||
for (int i = 0; i < conditions.size(); i += 2) {
|
||||
JsonNode operand = conditions.get(i + 1);
|
||||
if (!operand.isNumber()) {
|
||||
throw new IllegalArgumentException("numeric operand " + operand + " is not a number");
|
||||
}
|
||||
int compared = actual.compareTo(operand.decimalValue());
|
||||
boolean holds = switch (conditions.get(i).asText()) {
|
||||
case "=" -> compared == 0;
|
||||
case ">" -> compared > 0;
|
||||
case ">=" -> compared >= 0;
|
||||
case "<" -> compared < 0;
|
||||
case "<=" -> compared <= 0;
|
||||
default -> throw new IllegalArgumentException("unsupported numeric comparison " + conditions.get(i));
|
||||
};
|
||||
if (!result) {
|
||||
if (!holds) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean equalsExactly(JsonNode expected, JsonNode value) {
|
||||
if (expected.isNull()) {
|
||||
return value.isNull();
|
||||
}
|
||||
if (expected.isNumber()) {
|
||||
return value.isNumber() && expected.decimalValue().compareTo(value.decimalValue()) == 0;
|
||||
}
|
||||
if (expected.isTextual()) {
|
||||
return value.isTextual() && expected.textValue().equals(value.textValue());
|
||||
}
|
||||
if (expected.isBoolean()) {
|
||||
return value.isBoolean() && expected.booleanValue() == value.booleanValue();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user