feat(eventbridgev2): deliver subscriber events to Lambda functions (#9720)

AWS invokes a Lambda target with a JSON array of up to MaxBatchSize
events (10 by default), synchronously unless InvocationType is EVENT,
and with LambdaParameters.Qualifier resolved from each event. It checks
a Lambda TargetArn's form, then the Region and account of any target,
then that the parameter block is the target's.

A reset or deleting the subscriber drops the invocations still waiting.
AWS drops a waiting event only once it outlives the subscriber's
MaxEventAgeInSeconds or uses up MaxRetryAttempts, so a burst behind a
slow function is not cut at a fixed count.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-29 09:59:39 -04:00
1 parent c2743ec70f
commit beefbdc155
13 files changed
+1247 -88

No files matched your search

+2 -1
View File
@@ -151,7 +151,8 @@ starts EcsContainerManagerFirelensDockerNightlyIntegrationTest && [ -n "$FLUENT_
# nodejs:20 is the runtime the API Gateway, ELBv2 and Lambda integration tests resolve and every
# shard reaches it; the two Python runtimes each have one Docker-backed class; nodejs:18 was
# pulled by every shard and started by none. A class missed here pulls inline, as before.
grep -qE '/apigateway/|/apigatewayv2/|/lambda/' "$SHARD_FILE" && ecr public.ecr.aws/lambda/nodejs:20
{ grep -qE '/apigateway/|/apigatewayv2/|/lambda/' "$SHARD_FILE" \
|| starts EventBridgeV2LambdaDeliveryDockerNightlyIntegrationTest; } && ecr public.ecr.aws/lambda/nodejs:20
grep -qE '/lambdaweb/' "$SHARD_FILE" && ecr public.ecr.aws/lambda/nodejs:24
starts SwfLambdaIntegrationTest && ecr public.ecr.aws/lambda/python:3.12
starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/python:3.14
+1 -1
View File
@@ -334,7 +334,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| SWF | In-process | Decision and activity tasks, timers, child workflows, timeouts, real Lambda invocation |
| CloudFormation | In-process | Stacks, change sets, resource provisioning, StackSets (cross-account instances) |
| EventBridge | In-process | Custom buses, rules, SQS, SNS and Lambda targets |
| EventBridge V2 | In-process | Event buses, filtered subscribers delivering to SQS, and webhook event sources |
| EventBridge V2 | In-process | Event buses, filtered subscribers delivering to SQS and Lambda, and webhook event sources |
| EventBridge Pipes | In-process | Poller-based integration connecting SQS, Kinesis, DynamoDB, and MSK sources to targets with optional filtering |
| EventBridge Scheduler | In-process | Schedule groups, schedules, flexible time windows, retry policies, DLQs |
| CloudWatch Logs | In-process | Log groups, streams, ingestion, filtering |
+18 -8
View File
@@ -20,7 +20,7 @@ The AWS CLI calls it `aws eventsv2` and the SDKs `EventBridgeV2`.
| `DescribeEventBus` | Return an event bus's name, description, configuration, state and times |
| `DeleteEventBus` | Delete an event bus that has no subscribers or event sources that are not revoked |
| `ListEventBuses` | List the Region's event buses in name order, filtered by name prefix, a page at a time |
| `CreateSubscriber` | Create a subscriber that delivers the events its filters match to an Amazon SQS queue |
| `CreateSubscriber` | Create a subscriber that delivers the events its filters match to an Amazon SQS queue or an AWS Lambda function |
| `DescribeSubscriber` | Return a subscriber's target, filters, transformer, delivery settings, state and times |
| `ListSubscribers` | List the Region's subscribers, or one event bus's, filtered by name prefix, a page at a time |
| `UpdateSubscriber` | Change a subscriber's settings, keeping those the request leaves out |
@@ -58,9 +58,10 @@ Every other EventBridge V2 operation answers `UnsupportedOperation`.
## Subscribers and filters
A subscriber delivers each event to one target. Floci delivers to an **Amazon SQS queue** in your
account. Any other target type is refused with `InvalidInputException`, as is a parameter block other
than `SqsParameters`.
A subscriber delivers each event to one target. Floci delivers to an **Amazon SQS queue** or an
**AWS Lambda function** in your account and Region. The `TargetArn` of a function may carry a qualifier.
Any other target type is refused with `InvalidInputException`, as is a parameter block that does not
belong to the target: `SqsParameters` for a queue and `LambdaParameters` for a function.
`FilterConfiguration.Filters` holds at most one EventBridge pattern for each scope, and an event must
match every filter. A subscriber without a `FilterConfiguration` receives every event on the bus.
@@ -88,10 +89,19 @@ A matcher Floci does not evaluate, such as `cidr` or `anything-but` with `numeri
take a literal, or an expression that is a path into the event, such as
`{% $events.SystemMetadata.EventGroupId %}` or `{% $events.SystemMetadata."aws:EventId" %}`. Other
JSONata is refused when the subscriber is created.
- Delivery is immediate, one message per event, in the bus's sequence order, also across concurrent
`PutEvents` requests. A delivery that fails, for example to a queue that
does not exist, is logged and the event is dropped: `RetryPolicy` and `OnFailureConfiguration` are
stored but not applied, and neither is `BatchConfiguration`.
- A queue gets one message per event at once, in the bus's sequence order, also across concurrent
`PutEvents` requests. A delivery that fails, for example to a queue or a function that does not
exist, is logged and its events are dropped: `RetryPolicy` and `OnFailureConfiguration` are stored
but not applied.
- A function receives a JSON array of events, each in the form `Transformer.Type` gives. The events one
`PutEvents` call, webhook event or AWS service event makes for the subscriber go in one invocation, in
sequence order. `BatchConfiguration.MaxBatchSize`, 10 when not set, caps the events in an invocation.
`MaxBatchWindowInSeconds` is stored but not applied.
- `LambdaParameters.Qualifier` and `DurableExecutionName` take a literal or a path into the event, as
`SqsParameters` do, and are resolved for each event. A batch ends where either changes. Both are passed
to Invoke. `InvocationType` `EVENT` invokes the function asynchronously. `REQUEST_RESPONSE`, the
default, invokes it synchronously. A subscriber's invocations run in order and never hold up `PutEvents`.
`TenantId` and `InvocationTimeoutSeconds` are stored but not applied.
- A `STOPPED` subscriber receives nothing. `StartingPosition` `POINT_IN_TIME` is stored but delivers
from the latest event, since events are not retained.
- The `RoleArn` is checked for shape only; delivery does not assume it.
@@ -1,48 +1,136 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import io.floci.aws.services.lambda.LambdaService;
import io.floci.aws.services.lambda.model.InvocationType;
import io.floci.aws.services.lambda.model.InvokeResult;
import io.floci.aws.services.sqs.SqsService;
import io.floci.aws.services.sqs.model.MessageAttributeValue;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* Delivers an event a subscriber's filters matched to its target, an Amazon SQS queue: one message per event,
* Delivers the events a subscriber's filters matched to its target. An Amazon SQS queue gets 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.
* its data, metadata and system metadata, with the queue parameters {@code SqsParameters} gives. An AWS Lambda
* function gets a JSON array of events in those forms, at most {@code MaxBatchSize} to an invocation, which
* {@code LambdaParameters} shapes.
*/
@ApplicationScoped
public class EventBridgeV2Delivery {
private static final Logger LOG = Logger.getLogger(EventBridgeV2Delivery.class);
private static final int DEFAULT_MAX_BATCH_SIZE = 10;
record LambdaBatch(SubscriberV2 subscriber, String qualifier, String durableExecutionName,
ArrayNode events) {
}
private final SqsService sqsService;
private final LambdaService lambdaService;
private final String baseUrl;
@Inject
public EventBridgeV2Delivery(SqsService sqsService, EmulatorConfig config) {
public EventBridgeV2Delivery(SqsService sqsService, LambdaService lambdaService, EmulatorConfig config) {
this.sqsService = sqsService;
this.lambdaService = lambdaService;
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) {
/**
* Delivers the events one publish matched to the subscriber, in sequence order. A queue is sent each at once.
* A function's batches are returned for the caller to queue and invoke in order, so a slow function holds up
* neither the publisher nor the bus. A delivery that fails is logged and its events dropped.
*/
List<LambdaBatch> deliver(SubscriberV2 subscriber, List<PublishedEvent> events) {
if (AwsArnUtils.isArnFor(subscriber.getInvokeConfiguration().path("TargetArn").asText(), "lambda")) {
return batches(subscriber, events);
}
for (PublishedEvent event : events) {
deliverToQueue(subscriber, event);
}
return List.of();
}
private List<LambdaBatch> batches(SubscriberV2 subscriber, List<PublishedEvent> events) {
JsonNode parameters = subscriber.getInvokeConfiguration().path("LambdaParameters");
int maxBatchSize = subscriber.getBatchConfiguration() == null ? DEFAULT_MAX_BATCH_SIZE
: subscriber.getBatchConfiguration().path("MaxBatchSize").asInt(DEFAULT_MAX_BATCH_SIZE);
boolean withMetadata = withMetadata(subscriber);
List<LambdaBatch> batches = new ArrayList<>();
LambdaBatch current = null;
for (PublishedEvent event : events) {
String qualifier;
String durableExecutionName;
try {
qualifier = parameter(parameters, "LambdaParameters", "Qualifier", event);
durableExecutionName = parameter(parameters, "LambdaParameters", "DurableExecutionName", event);
} catch (IllegalArgumentException e) {
LOG.warnv("EventBridge V2 subscriber {0} failed to deliver an event to {1}: {2}", subscriber.getArn(),
subscriber.getInvokeConfiguration().path("TargetArn").asText(), e.getMessage());
continue;
}
if (current == null || current.events().size() >= maxBatchSize
|| !Objects.equals(current.qualifier(), qualifier)
|| !Objects.equals(current.durableExecutionName(), durableExecutionName)) {
current = new LambdaBatch(subscriber, qualifier, durableExecutionName,
JsonNodeFactory.instance.arrayNode());
batches.add(current);
}
current.events().add(withMetadata ? event.withMetadata() : event.data());
}
return batches;
}
void invoke(LambdaBatch batch) {
SubscriberV2 subscriber = batch.subscriber();
JsonNode configuration = subscriber.getInvokeConfiguration();
String functionArn = configuration.path("TargetArn").asText();
InvocationType type = "EVENT".equals(configuration.path("LambdaParameters").path("InvocationType").asText())
? InvocationType.Event : InvocationType.RequestResponse;
try {
AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn);
byte[] payload = batch.events().toString().getBytes(StandardCharsets.UTF_8);
InvokeResult result = RequestScopes.callAs(arn.accountId(), arn.region(), () -> lambdaService.invoke(
arn.region(), functionArn, batch.qualifier(), payload, type, null, batch.durableExecutionName()));
if (result != null && result.getFunctionError() != null) {
LOG.warnv("EventBridge V2 subscriber {0} invoked {1} and the function failed: {2}",
subscriber.getArn(), functionArn, result.getFunctionError());
} else {
LOG.debugv("EventBridge V2 subscriber {0} invoked {1} with {2} events", subscriber.getArn(),
functionArn, batch.events().size());
}
} catch (RuntimeException e) {
LOG.warnv("EventBridge V2 subscriber {0} failed to invoke {1}: {2}", subscriber.getArn(), functionArn,
e.getMessage());
}
}
private void deliverToQueue(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);
String groupId = parameter(parameters, "SqsParameters", "MessageGroupId", event);
String deduplicationId = parameter(parameters, "SqsParameters", "MessageDeduplicationId", event);
String delay = parameter(parameters, "SqsParameters", "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),
@@ -56,9 +144,7 @@ public class EventBridgeV2Delivery {
}
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)) {
if (withMetadata(subscriber)) {
return event.withMetadata().toString();
}
if (event.rawData() != null) {
@@ -68,12 +154,17 @@ public class EventBridgeV2Delivery {
return data.isTextual() ? data.textValue() : data.toString();
}
private static String parameter(JsonNode parameters, String name, PublishedEvent event) {
private static boolean withMetadata(SubscriberV2 subscriber) {
JsonNode transformer = subscriber.getTransformer();
return transformer != null && "WITH_METADATA".equals(transformer.path("Type").asText("RAW"));
}
private static String parameter(JsonNode parameters, String block, String name, PublishedEvent event) {
JsonNode value = parameters.get(name);
if (value == null || value.isNull()) {
return null;
}
return resolve(value.asText(), name, event);
return resolve(value.asText(), block + "." + name, event);
}
private static Map<String, MessageAttributeValue> messageAttributes(JsonNode attributes, PublishedEvent event) {
@@ -81,13 +172,13 @@ public class EventBridgeV2Delivery {
attributes.properties().forEach(attribute -> {
JsonNode value = attribute.getValue();
String dataType = value.path("DataType").asText("String");
String name = resolve(attribute.getKey(), "MessageAttributes", event);
String name = resolve(attribute.getKey(), "SqsParameters.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));
resolve(value.path("StringValue").asText(""), "SqsParameters.MessageAttributes." + name, event), dataType));
}
});
return resolved;
@@ -96,6 +187,6 @@ public class EventBridgeV2Delivery {
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"));
parameter + " expression " + value + " produced no value"));
}
}
@@ -40,13 +40,10 @@ import java.util.List;
import java.util.Locale;
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.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -75,9 +72,10 @@ public class EventBridgeV2Service implements Resettable {
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",
private static final List<String> PARAMETER_BLOCKS = List.of("LambdaParameters", "SqsParameters", "SnsParameters",
"KinesisParameters", "StepFunctionsParameters", "HttpParameters", "UniversalTargetParameters",
"EventBusV2Parameters");
"EventBusV2Parameters", "MskParameters");
private static final Pattern LAMBDA_FUNCTION_RESOURCE = Pattern.compile("function:[^:]+(:[^:]+)?");
private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
static final int ID_LENGTH = 25;
private static final int MAX_TAGS = 200;
@@ -96,7 +94,10 @@ public class EventBridgeV2Service implements Resettable {
private final Clock clock;
private final boolean enabled;
private final SecureRandom random = new SecureRandom();
private final ConcurrentMap<String, OrderedDeliveries> deliveriesByBus = new ConcurrentHashMap<>();
private final ConcurrentMap<String, OrderedQueue<Map.Entry<SubscriberV2, List<PublishedEvent>>>> deliveriesByBus =
new ConcurrentHashMap<>();
private final ConcurrentMap<String, OrderedQueue<EventBridgeV2Delivery.LambdaBatch>> invocationsBySubscriber =
new ConcurrentHashMap<>();
private final WebhookDeduplication serviceEventDeduplication;
@Inject
@@ -309,7 +310,7 @@ public class EventBridgeV2Service implements Resettable {
subscriber.setStartingPosition(optionalEnum(request, "StartingPosition", Set.of("LATEST", "POINT_IN_TIME"),
"LATEST"));
subscriber.setPointInTimeConfiguration(pointInTimeConfiguration(request, subscriber.getStartingPosition()));
applySettings(subscriber, request, filterConfiguration);
applySettings(subscriber, request, filterConfiguration, region);
requireStoredTagLimit(tags.size());
subscriber.setCreationTime(now);
subscriber.setLastModifiedTime(now);
@@ -370,7 +371,7 @@ public class EventBridgeV2Service implements Resettable {
SubscriberFilters.validate(filterConfiguration);
}
SubscriberV2 changed = copyOf(subscriber);
applySettings(changed, settings, filterConfiguration);
applySettings(changed, settings, filterConfiguration, region);
if (subscriber.isRevoked()) {
throw new AwsException("InvalidStateException", "Subscriber is revoked and cannot be updated", 409);
}
@@ -426,6 +427,10 @@ public class EventBridgeV2Service implements Resettable {
public synchronized void deleteSubscriber(String subscriberArn, String region) {
SubscriberV2 subscriber = requireSubscriber(subscriberArn, region);
subscribers.delete(keyOf(subscriber, region));
OrderedQueue<EventBridgeV2Delivery.LambdaBatch> invocations = invocationsBySubscriber.remove(subscriberArn);
if (invocations != null) {
invocations.clear();
}
}
public Optional<SubscriberV2> findSubscriber(String subscriberArn, String region) {
@@ -703,10 +708,6 @@ public class EventBridgeV2Service implements Resettable {
// ──────────────────────────── 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) {
}
@@ -729,7 +730,7 @@ public class EventBridgeV2Service implements Resettable {
}
List<PutEventsResult> results = new ArrayList<>();
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries = new ArrayList<>();
OrderedDeliveries ordered;
OrderedQueue<Map.Entry<SubscriberV2, List<PublishedEvent>>> ordered;
synchronized (this) {
EventBusV2 bus = requireEventBus(eventBusArn, region);
List<SubscriberV2> running = subscribersOf(bus, region).stream()
@@ -762,7 +763,7 @@ public class EventBridgeV2Service implements Resettable {
PublishedEvent publishWebhookEvent(String eventBusArn, String region, Function<String, PublishedEvent> build) {
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries = new ArrayList<>();
PublishedEvent event;
OrderedDeliveries ordered;
OrderedQueue<Map.Entry<SubscriberV2, List<PublishedEvent>>> ordered;
synchronized (this) {
EventBusV2 bus = requireEventBus(eventBusArn, region);
List<SubscriberV2> running = subscribersOf(bus, region).stream()
@@ -837,36 +838,50 @@ public class EventBridgeV2Service implements Resettable {
return event;
}
private OrderedDeliveries enqueue(EventBusV2 bus, String region,
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries) {
private OrderedQueue<Map.Entry<SubscriberV2, List<PublishedEvent>>> enqueue(EventBusV2 bus, String region,
List<Map.Entry<SubscriberV2, PublishedEvent>> deliveries) {
buses.put(storageKey(region, bus.getName()), bus);
OrderedDeliveries ordered = deliveriesByBus.computeIfAbsent(bus.getArn(),
arn -> new OrderedDeliveries(new ConcurrentLinkedQueue<>(), new ReentrantLock()));
ordered.pending().addAll(deliveries);
OrderedQueue<Map.Entry<SubscriberV2, List<PublishedEvent>>> ordered = deliveriesByBus.computeIfAbsent(
bus.getArn(), arn -> new OrderedQueue<>());
Map<String, Map.Entry<SubscriberV2, List<PublishedEvent>>> perSubscriber = new LinkedHashMap<>();
for (Map.Entry<SubscriberV2, PublishedEvent> delivered : deliveries) {
perSubscriber.computeIfAbsent(delivered.getKey().getArn(),
arn -> Map.entry(delivered.getKey(), new ArrayList<>())).getValue().add(delivered.getValue());
}
ordered.addAll(perSubscriber.values());
return ordered;
}
/**
* 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
* Sends a bus's queued deliveries, each subscriber's events of one publish together, 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());
}
private void send(OrderedQueue<Map.Entry<SubscriberV2, List<PublishedEvent>>> ordered) {
ordered.drain(next -> {
try {
queueInvocations(next.getKey(), delivery.deliver(next.getKey(), next.getValue()));
} catch (RuntimeException e) {
LOG.warnv(e, "EventBridge V2 subscriber {0} failed to deliver {1} events", next.getKey().getArn(),
next.getValue().size());
}
} finally {
ordered.sending().unlock();
});
}
private void queueInvocations(SubscriberV2 subscriber, List<EventBridgeV2Delivery.LambdaBatch> batches) {
if (batches.isEmpty()) {
return;
}
OrderedQueue<EventBridgeV2Delivery.LambdaBatch> invocations = invocationsBySubscriber.computeIfAbsent(
subscriber.getArn(), arn -> new OrderedQueue<>());
invocations.addAll(batches);
invocations.drainInBackground(delivery::invoke, "eventbridgev2-lambda-delivery");
}
OrderedQueue<EventBridgeV2Delivery.LambdaBatch> waitingInvocations(String subscriberArn) {
return invocationsBySubscriber.get(subscriberArn);
}
private PublishedEvent envelope(EventBusV2 bus, JsonNode entry, Instant time, JsonNode detail,
@@ -924,7 +939,10 @@ public class EventBridgeV2Service implements Resettable {
public void clear() {
buses.clear();
subscribers.clear();
deliveriesByBus.values().forEach(OrderedQueue::clear);
deliveriesByBus.clear();
invocationsBySubscriber.values().forEach(OrderedQueue::clear);
invocationsBySubscriber.clear();
serviceEventDeduplication.clear();
}
@@ -948,9 +966,10 @@ public class EventBridgeV2Service implements Resettable {
return settings;
}
private void applySettings(SubscriberV2 subscriber, JsonNode request, JsonNode filterConfiguration) {
private void applySettings(SubscriberV2 subscriber, JsonNode request, JsonNode filterConfiguration,
String region) {
subscriber.setDescription(optionalDescription(request));
subscriber.setInvokeConfiguration(invokeConfiguration(request));
subscriber.setInvokeConfiguration(invokeConfiguration(request, region));
subscriber.setFilterConfiguration(filterConfiguration);
subscriber.setTransformer(transformer(request));
subscriber.setBatchConfiguration(boundedIntegers(request, "BatchConfiguration",
@@ -973,11 +992,11 @@ public class EventBridgeV2Service implements Resettable {
}
/**
* 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.
* The target and its parameters. Floci delivers to an Amazon SQS queue or an AWS Lambda function in the
* caller's account and Region, so a target of another service is refused, and a parameter block must be the one
* of the target's service. A parameter is a literal or a path into the event.
*/
private JsonNode invokeConfiguration(JsonNode request) {
private JsonNode invokeConfiguration(JsonNode request, String region) {
JsonNode configuration = optionalStructure(request, "InvokeConfiguration");
if (configuration == null) {
throw invalidInput("InvokeConfiguration is required.");
@@ -991,20 +1010,69 @@ public class EventBridgeV2Service implements Resettable {
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.");
boolean lambda = "lambda".equals(target.service());
if (!lambda && !"sqs".equals(target.service())) {
throw invalidInput("Floci delivers EventBridge V2 events only to Amazon SQS queues and AWS Lambda "
+ "functions; " + targetArn + " is not one.");
}
if (lambda && !LAMBDA_FUNCTION_RESOURCE.matcher(target.resource()).matches()) {
throw invalidInput("InvokeConfiguration.TargetArn: TargetArn resource must be of the form "
+ "function:{name}[:{qualifier}]");
}
if (!region.equals(target.region())) {
throw invalidInput("InvokeConfiguration.TargetArn: TargetArn must be in region " + region);
}
if (!regionResolver.getAccountId().equals(target.accountId())) {
throw invalidInput("InvokeConfiguration.TargetArn must belong to your account.");
throw invalidInput("Target resource account (" + target.accountId() + ") must match the subscriber "
+ "account (" + regionResolver.getAccountId() + ")");
}
String expectedBlock = lambda ? "LambdaParameters" : "SqsParameters";
for (String block : PARAMETER_BLOCKS) {
if (!"SqsParameters".equals(block) && configuration.hasNonNull(block)) {
throw invalidInput("InvokeConfiguration." + block + " does not match the target type of "
+ targetArn + ".");
if (!expectedBlock.equals(block) && configuration.hasNonNull(block)) {
throw invalidInput(block + " is not supported for target " + targetArn + ". Expected "
+ expectedBlock);
}
}
JsonNode parameters = optionalStructure(configuration, "SqsParameters");
if (lambda) {
requireLambdaParameters(optionalStructure(configuration, "LambdaParameters"));
} else {
requireSqsParameters(optionalStructure(configuration, "SqsParameters"));
}
return configuration;
}
private static void requireLambdaParameters(JsonNode parameters) {
if (parameters == null) {
return;
}
String invocationType = text(parameters, "InvocationType");
if (invocationType != null && !List.of("REQUEST_RESPONSE", "EVENT").contains(invocationType)) {
throw SmithyValidationErrors.exception("InvalidInputException",
SmithyValidationErrors.Violations.WITHOUT_VALUES.notInEnum(invocationType,
"invokeConfiguration.lambdaParameters.invocationType", List.of("REQUEST_RESPONSE", "EVENT")));
}
String timeout = text(parameters, "InvocationTimeoutSeconds");
if (timeout != null && !EventExpressions.isExpression(timeout)) {
requireInvocationTimeout(timeout);
}
for (String name : List.of("InvocationTimeoutSeconds", "Qualifier", "TenantId", "DurableExecutionName")) {
requireSupportedExpression(text(parameters, name), "LambdaParameters." + name);
}
}
private static void requireInvocationTimeout(String timeout) {
int seconds;
try {
seconds = Integer.parseInt(timeout.trim());
} catch (NumberFormatException e) {
throw invalidInput("InvocationTimeoutSeconds must be a valid integer or a JSONata expression");
}
if (seconds < 1 || seconds > 30) {
throw invalidInput("InvocationTimeoutSeconds must be between 1 and 30");
}
}
private static void requireSqsParameters(JsonNode parameters) {
if (parameters != null) {
for (String name : List.of("MessageGroupId", "MessageDeduplicationId", "DelaySeconds")) {
requireSupportedExpression(text(parameters, name), "SqsParameters." + name);
@@ -1021,7 +1089,6 @@ public class EventBridgeV2Service implements Resettable {
}
}
}
return configuration;
}
private static void requireSupportedExpression(String value, String parameter) {
@@ -0,0 +1,60 @@
package io.floci.aws.services.eventbridgev2;
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
/** Items worked off in the order they were added, by one worker at a time. */
final class OrderedQueue<T> {
private final Queue<T> pending = new ConcurrentLinkedQueue<>();
private final ReentrantLock working = new ReentrantLock();
private final AtomicBoolean scheduled = new AtomicBoolean();
void addAll(Collection<? extends T> items) {
pending.addAll(items);
}
/** Works off the queued items on the calling thread, holding the lock, until none is left. */
void drain(Consumer<? super T> worker) {
working.lock();
try {
T next;
while ((next = pending.poll()) != null) {
worker.accept(next);
}
} finally {
working.unlock();
}
}
/** Works off the queued items on a virtual thread, unless one is already scheduled for this queue. */
void drainInBackground(Consumer<? super T> worker, String threadName) {
if (!scheduled.compareAndSet(false, true)) {
return;
}
Thread.ofVirtual().name(threadName).start(() -> {
try {
drain(worker);
} finally {
scheduled.set(false);
// An item added after the last poll but before the flag cleared must not be stranded.
if (!pending.isEmpty()) {
drainInBackground(worker, threadName);
}
}
});
}
/** Drops the waiting items. An item a worker already took still finishes. */
void clear() {
pending.clear();
}
int size() {
return pending.size();
}
}
@@ -602,9 +602,10 @@ class AwsServiceEventSourcesTest {
service.forwardServiceEvent(bus, ruleName, event);
service.forwardServiceEvent(bus, ruleName, event);
ArgumentCaptor<PublishedEvent> delivered = ArgumentCaptor.forClass(PublishedEvent.class);
ArgumentCaptor<List<PublishedEvent>> delivered = ArgumentCaptor.captor();
verify(delivery, times(1)).deliver(any(), delivered.capture());
PublishedEvent published = delivered.getValue();
assertEquals(1, delivered.getValue().size());
PublishedEvent published = delivered.getValue().getFirst();
assertEquals(json(event), published.data());
assertEquals(json("{}"), published.metadata());
assertEquals(List.of("EventGroupId", "DeduplicationId", "ContentType", "aws:IngestionTime", "aws:Source",
@@ -0,0 +1,153 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.FilteredLogEvent;
import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceNotFoundException;
import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client;
import software.amazon.awssdk.services.eventbridgev2.model.FilterConfiguration;
import software.amazon.awssdk.services.eventbridgev2.model.PutEventsRequestEntry;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.Runtime;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Subscribers invoking a real function: it logs what it was invoked as and the array of events it received, and
* the test reads that back from the function's log group.
*/
@QuarkusTest
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
class EventBridgeV2LambdaDeliveryDockerNightlyIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/EventBusDelivery";
private static final Duration DEADLINE = Duration.ofSeconds(90);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String HANDLER = """
exports.handler = async (events, context) => {
console.log('EVENTS ' + JSON.stringify({arn: context.invokedFunctionArn, events}));
return {ok: true};
};
""";
@BeforeEach
void requireDocker() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for the function");
}
@Test
void subscribersInvokeARealFunctionWithTheEventsTheyMatched() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String function = "v2-target-" + suffix;
try (LambdaClient lambda = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_EAST_1);
EventBridgeV2Client events = AwsTestClients.create(EventBridgeV2Client.builder(), ACCOUNT,
Region.US_EAST_1);
CloudWatchLogsClient logs = AwsTestClients.create(CloudWatchLogsClient.builder(), ACCOUNT,
Region.US_EAST_1)) {
String functionArn = lambda.createFunction(request -> request.functionName(function)
.runtime(Runtime.NODEJS20_X).handler("index.handler").role(ROLE).timeout(10)
.code(code -> code.zipFile(SdkBytes.fromByteArray(LambdaCodeFixtures.nodeJsZip(HANDLER)))))
.functionArn();
String version = lambda.publishVersion(request -> request.functionName(function)).version();
lambda.createAlias(request -> request.functionName(function).name("live").functionVersion(version));
String bus = events.createEventBus(request -> request.name("v2-lambda-" + suffix)).eventBusArn();
try {
events.createSubscriber(request -> request.name("raw").eventBusArn(bus)
.invokeConfiguration(invoke -> invoke.targetArn(functionArn).roleArn(ROLE))
.filterConfiguration(filter("raw")));
events.createSubscriber(request -> request.name("meta").eventBusArn(bus)
.invokeConfiguration(invoke -> invoke.targetArn(functionArn).roleArn(ROLE)
.lambdaParameters(parameters -> parameters.qualifier("live").invocationType("EVENT")))
.transformer(transformer -> transformer.type("WITH_METADATA"))
.filterConfiguration(filter("meta")));
List<PutEventsRequestEntry> entries = new ArrayList<>();
for (int i = 0; i < 3; i++) {
entries.add(entry("raw", "{\"n\":" + i + "}"));
}
entries.add(entry("meta", "{\"n\":9}"));
events.putEvents(request -> request.eventBusArn(bus).entries(entries));
List<JsonNode> invocations = await().atMost(DEADLINE).pollInterval(Duration.ofMillis(500))
.until(() -> invocations(logs, function), found -> found.size() >= 2);
JsonNode raw = invocationAs(invocations, functionArn);
assertEquals(3, raw.path("events").size(), raw.toString());
for (int i = 0; i < 3; i++) {
JsonNode event = raw.path("events").get(i);
assertEquals("raw", event.path("detail-type").asText(), event.toString());
assertEquals("floci.test", event.path("source").asText(), event.toString());
assertEquals(i, event.at("/detail/n").asInt(), event.toString());
}
JsonNode meta = invocations.stream().filter(invocation -> invocation.path("arn").asText()
.startsWith(functionArn + ":")).findFirst()
.orElseThrow(() -> new AssertionError("no qualified invocation: " + invocations));
assertEquals(1, meta.path("events").size(), meta.toString());
JsonNode withMetadata = meta.path("events").get(0);
assertEquals("meta", withMetadata.at("/Data/detail-type").asText(), withMetadata.toString());
assertEquals(9, withMetadata.at("/Data/detail/n").asInt(), withMetadata.toString());
assertTrue(withMetadata.path("Metadata").isObject(), withMetadata.toString());
assertEquals("meta", withMetadata.at("/SystemMetadata/aws:DetailType").asText(),
withMetadata.toString());
assertEquals(2, invocations.size(), "one invocation for each subscriber");
} finally {
events.listSubscribers(request -> request.eventBusArn(bus)).subscribers()
.forEach(subscriber -> events.deleteSubscriber(request -> request
.subscriberArn(subscriber.subscriberArn())));
events.deleteEventBus(request -> request.eventBusArn(bus));
lambda.deleteFunction(request -> request.functionName(function));
}
}
}
private static FilterConfiguration filter(String detailType) {
return FilterConfiguration.builder()
.filters(pattern -> pattern.scope("DATA").pattern("{\"detail-type\":[\"" + detailType + "\"]}"))
.build();
}
private static PutEventsRequestEntry entry(String detailType, String detail) {
return PutEventsRequestEntry.builder().source("floci.test").detailType(detailType).detail(detail).build();
}
private static List<JsonNode> invocations(CloudWatchLogsClient logs, String function) throws Exception {
List<FilteredLogEvent> found;
try {
found = logs.filterLogEvents(request -> request.logGroupName("/aws/lambda/" + function)).events();
} catch (ResourceNotFoundException notYet) {
return List.of();
}
List<JsonNode> invocations = new ArrayList<>();
for (FilteredLogEvent event : found) {
int start = event.message().indexOf("EVENTS ");
if (start >= 0) {
invocations.add(MAPPER.readTree(event.message().substring(start + "EVENTS ".length())));
}
}
return invocations;
}
private static JsonNode invocationAs(List<JsonNode> invocations, String invokedArn) {
return invocations.stream().filter(invocation -> invokedArn.equals(invocation.path("arn").asText()))
.findFirst().orElseThrow(() -> new AssertionError("no invocation as " + invokedArn + ": " + invocations));
}
}
@@ -0,0 +1,571 @@
package io.floci.aws.services.eventbridgev2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.TlsCertificateManager;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.eventbridgev2.model.SubscriberV2;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.lambda.LambdaService;
import io.floci.aws.services.lambda.model.InvocationType;
import io.floci.aws.services.lambda.model.InvokeResult;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.sqs.SqsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EventBridgeV2LambdaDeliveryTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String FUNCTION = "arn:aws:lambda:us-east-1:000000000000:function:handler";
private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:orders";
private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery";
private LambdaService lambdaService;
private SqsService sqsService;
private EventBridgeV2Delivery delivery;
private EventBridgeV2Service service;
private String bus;
@BeforeEach
void setUp() {
lambdaService = mock(LambdaService.class);
sqsService = mock(SqsService.class);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.baseUrl()).thenReturn("http://floci.test:4566");
delivery = new EventBridgeV2Delivery(sqsService, lambdaService, config);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
Clock clock = Clock.fixed(Instant.parse("2026-11-29T12:00:00Z"), ZoneOffset.UTC);
EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(
AccountAwareStorageBackend.inMemory(ACCOUNT), mock(SecretsManagerService.class), regionResolver, clock,
"http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class),
mock(KmsService.class));
service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, eventSources, clock, true);
bus = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn();
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new InvokeResult(200, null, new byte[0], null, "request"));
}
@Test
void createSubscriber_lambdaTarget_isStoredAsGiven() {
SubscriberV2 subscriber = service.createSubscriber(json(request("s", invoke(FUNCTION,
",\"LambdaParameters\":{\"InvocationType\":\"EVENT\",\"InvocationTimeoutSeconds\":\"30\"}"))), REGION);
assertEquals(FUNCTION, subscriber.getInvokeConfiguration().path("TargetArn").asText());
assertEquals("EVENT", subscriber.getInvokeConfiguration().path("LambdaParameters").path("InvocationType")
.asText());
assertNull(subscriber.getInvokeConfiguration().get("SqsParameters"));
}
@ParameterizedTest
@CsvSource({
"arn:aws:lambda:us-east-1:000000000000:function:handler:live",
"arn:aws:lambda:us-east-1:000000000000:function:handler:$LATEST",
"arn:aws:lambda:us-east-1:000000000000:function:my.handler",
})
void createSubscriber_qualifiedOrDottedFunction_accepted(String target) {
service.createSubscriber(json(request("s", invoke(target, ""))), REGION);
}
@Test
void createSubscriber_emptyLambdaParametersAndQualifierDifferentFromTheArn_accepted() {
service.createSubscriber(json(request("a", invoke(FUNCTION, ",\"LambdaParameters\":{}"))), REGION);
service.createSubscriber(json(request("b", invoke(FUNCTION + ":live",
",\"LambdaParameters\":{\"Qualifier\":\"other\",\"TenantId\":\"t\",\"DurableExecutionName\":\"d\"}"))),
REGION);
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"arn:aws:lambda:us-east-1:000000000000:function|InvokeConfiguration.TargetArn: TargetArn resource must be "
+ "of the form function:{name}[:{qualifier}]",
"arn:aws:lambda:us-east-1:000000000000:layer:l:1|InvokeConfiguration.TargetArn: TargetArn resource must be "
+ "of the form function:{name}[:{qualifier}]",
"arn:aws:lambda:eu-west-1:000000000000:function:f|InvokeConfiguration.TargetArn: TargetArn must be in "
+ "region us-east-1",
"arn:aws:sqs:eu-west-1:000000000000:q|InvokeConfiguration.TargetArn: TargetArn must be in region us-east-1",
"arn:aws:lambda:us-east-1:123456789012:function:f|Target resource account (123456789012) must match the "
+ "subscriber account (000000000000)",
"arn:aws:sqs:us-east-1:123456789012:q|Target resource account (123456789012) must match the subscriber "
+ "account (000000000000)",
"arn:aws:sns:us-east-1:000000000000:t|Floci delivers EventBridge V2 events only to Amazon SQS queues and "
+ "AWS Lambda functions; arn:aws:sns:us-east-1:000000000000:t is not one.",
})
void createSubscriber_refusedTarget_awsMessage(String target, String message) {
AwsException e = assertThrows(AwsException.class,
() -> service.createSubscriber(json(request("s", invoke(target, ""))), REGION));
assertEquals("InvalidInputException", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
assertEquals(message, e.getMessage());
}
@Test
void createSubscriber_theResourceFormComesBeforeTheRegionAndTheRegionBeforeTheAccount() {
assertMessage("InvokeConfiguration.TargetArn: TargetArn resource must be of the form function:{name}[:{qualifier}]",
"arn:aws:lambda:eu-west-1:123456789012:function", "");
assertMessage("InvokeConfiguration.TargetArn: TargetArn must be in region us-east-1",
"arn:aws:lambda:eu-west-1:123456789012:function:f", "");
}
@Test
void createSubscriber_theAccountComesBeforeTheParameterBlock() {
assertMessage("Target resource account (123456789012) must match the subscriber account (000000000000)",
"arn:aws:lambda:us-east-1:123456789012:function:f", ",\"SqsParameters\":{}");
}
@Test
void createSubscriber_wrongParameterBlock_namesTheExpectedOne() {
assertMessage("SqsParameters is not supported for target " + FUNCTION + ". Expected LambdaParameters", FUNCTION,
",\"SqsParameters\":{}");
assertMessage("LambdaParameters is not supported for target " + QUEUE + ". Expected SqsParameters", QUEUE,
",\"LambdaParameters\":{}");
}
@Test
void createSubscriber_severalWrongBlocks_namesTheFirstInTheModelOrder() {
assertMessage("SqsParameters is not supported for target " + FUNCTION + ". Expected LambdaParameters", FUNCTION,
",\"SnsParameters\":{},\"SqsParameters\":{}");
}
@Test
void createSubscriber_theParameterBlockComesBeforeItsValues() {
assertMessage("SqsParameters is not supported for target " + FUNCTION + ". Expected LambdaParameters", FUNCTION,
",\"SqsParameters\":{},\"LambdaParameters\":{\"InvocationType\":\"x\"}");
}
@Test
void createSubscriber_unknownInvocationType_validationError() {
assertMessage("1 validation error detected: Value at 'invokeConfiguration.lambdaParameters.invocationType' "
+ "failed to satisfy constraint: Member must satisfy enum value set: [REQUEST_RESPONSE, EVENT]",
FUNCTION, ",\"LambdaParameters\":{\"InvocationType\":\"Event\"}");
}
@ParameterizedTest
@CsvSource({"0", "-1", "31", "901"})
void createSubscriber_timeoutOutsideTheRange_refused(String timeout) {
assertMessage("InvocationTimeoutSeconds must be between 1 and 30", FUNCTION,
",\"LambdaParameters\":{\"InvocationTimeoutSeconds\":\"" + timeout + "\"}");
}
@Test
void createSubscriber_timeoutThatIsNeitherAnIntegerNorAnExpression_refused() {
assertMessage("InvocationTimeoutSeconds must be a valid integer or a JSONata expression", FUNCTION,
",\"LambdaParameters\":{\"InvocationTimeoutSeconds\":\"abc\"}");
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {"1", "30", "{% $events.Data.detail.t %}"})
void createSubscriber_timeoutInRangeOrAPath_accepted(String timeout) {
service.createSubscriber(json(request("s", invoke(FUNCTION,
",\"LambdaParameters\":{\"InvocationTimeoutSeconds\":\"" + timeout + "\"}"))), REGION);
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {"Qualifier", "TenantId", "DurableExecutionName", "InvocationTimeoutSeconds"})
void createSubscriber_expressionFloci_doesNotEvaluate_refused(String member) {
AwsException e = assertThrows(AwsException.class, () -> service.createSubscriber(json(request("s",
invoke(FUNCTION, ",\"LambdaParameters\":{\"" + member + "\":\"{% $uppercase($events.Data.source) %}\"}"))),
REGION));
assertEquals("InvalidInputException", e.getErrorCode());
assertTrue(e.getMessage().startsWith("LambdaParameters." + member), e.getMessage());
}
@Test
void updateSubscriber_againstAStoredLambdaTarget_checksTheBlock() {
SubscriberV2 created = service.createSubscriber(json(request("s", invoke(FUNCTION, ""))), REGION);
AwsException e = assertThrows(AwsException.class, () -> service.updateSubscriber(json("{\"SubscriberArn\":\""
+ created.getArn() + "\",\"InvokeConfiguration\":{\"RoleArn\":\"" + ROLE
+ "\",\"SqsParameters\":{\"MessageGroupId\":\"g\"}}}"), REGION));
assertEquals("SqsParameters is not supported for target " + FUNCTION + ". Expected LambdaParameters",
e.getMessage());
SubscriberV2 updated = service.updateSubscriber(json("{\"SubscriberArn\":\"" + created.getArn()
+ "\",\"InvokeConfiguration\":{\"RoleArn\":\"" + ROLE
+ "\",\"LambdaParameters\":{\"InvocationType\":\"EVENT\"}}}"), REGION);
assertEquals(FUNCTION, updated.getInvokeConfiguration().path("TargetArn").asText());
assertEquals("EVENT", updated.getInvokeConfiguration().path("LambdaParameters").path("InvocationType").asText());
}
@Test
void deliver_raw_batchesAnArrayOfTheEventData() {
SubscriberV2 subscriber = lambdaSubscriber("", null);
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber,
List.of(event("1", "{\"detail\":{\"n\":1}}")));
assertEquals(List.of("[{\"detail\":{\"n\":1}}]"), eventsOf(batches));
verify(lambdaService, never()).invoke(any(), any(), any(), any(), any(), any(), any());
}
@Test
void deliver_withMetadata_batchesDataMetadataAndSystemMetadata() {
SubscriberV2 subscriber = lambdaSubscriber("", "WITH_METADATA");
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber,
List.of(event("1", "{\"detail\":{\"n\":1}}")));
assertEquals(List.of("[{\"Data\":{\"detail\":{\"n\":1}},\"Metadata\":{},\"SystemMetadata\":"
+ "{\"aws:SequenceNumber\":\"1\"}}]"), eventsOf(batches));
}
@Test
void deliver_threeEventsOfOnePublish_oneBatchInSequenceOrder() {
SubscriberV2 subscriber = lambdaSubscriber("", null);
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber,
List.of(event("1", "{\"n\":1}"), event("2", "{\"n\":2}"), event("3", "{\"n\":3}")));
assertEquals(List.of("[{\"n\":1},{\"n\":2},{\"n\":3}]"), eventsOf(batches));
}
@Test
void deliver_maxBatchSizeOfTwo_splitsFiveEventsTwoTwoOne() {
SubscriberV2 subscriber = lambdaSubscriber("", null);
subscriber.setBatchConfiguration(json("{\"MaxBatchSize\":2,\"MaxBatchWindowInSeconds\":5}"));
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber,
List.of(event("1", "{\"n\":1}"), event("2", "{\"n\":2}"), event("3", "{\"n\":3}"),
event("4", "{\"n\":4}"), event("5", "{\"n\":5}")));
assertEquals(List.of("[{\"n\":1},{\"n\":2}]", "[{\"n\":3},{\"n\":4}]", "[{\"n\":5}]"), eventsOf(batches));
}
@Test
void deliver_noBatchConfiguration_tenEventsToABatch() {
SubscriberV2 subscriber = lambdaSubscriber("", null);
List<PublishedEvent> events = new ArrayList<>();
for (int i = 1; i <= 11; i++) {
events.add(event(Integer.toString(i), "{\"n\":" + i + "}"));
}
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber, events);
assertEquals(2, batches.size());
assertEquals(10, batches.get(0).events().size());
assertEquals(1, batches.get(1).events().size());
}
@Test
void deliver_qualifierExpression_resolvedPerEventAndTheBatchSplitsWhereItChanges() {
SubscriberV2 subscriber = lambdaSubscriber(
",\"LambdaParameters\":{\"Qualifier\":\"{% $events.Data.q %}\"}", null);
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber,
List.of(event("1", "{\"q\":\"a\"}"), event("2", "{\"q\":\"a\"}"), event("3", "{\"q\":\"b\"}"),
event("4", "{\"q\":\"a\"}")));
assertEquals(List.of("a", "b", "a"), batches.stream().map(EventBridgeV2Delivery.LambdaBatch::qualifier).toList());
assertEquals(List.of(2, 1, 1), batches.stream().map(batch -> batch.events().size()).toList());
}
@Test
void deliver_eventWhoseQualifierExpressionHasNoValue_isDroppedAndTheRestBatched() {
SubscriberV2 subscriber = lambdaSubscriber(
",\"LambdaParameters\":{\"Qualifier\":\"{% $events.Data.q %}\"}", null);
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber,
List.of(event("1", "{\"n\":1}"), event("2", "{\"q\":\"a\",\"n\":2}")));
assertEquals(List.of("[{\"q\":\"a\",\"n\":2}]"), eventsOf(batches));
}
@Test
void invoke_rawBatch_sendsTheArrayAsRequestResponse() {
SubscriberV2 subscriber = lambdaSubscriber("", null);
invokeAll(delivery.deliver(subscriber, List.of(event("1", "{\"detail\":{\"n\":1}}"))));
assertEquals("[{\"detail\":{\"n\":1}}]", payloads(1).getFirst());
verify(lambdaService).invoke(eq(REGION), eq(FUNCTION), any(), any(), eq(InvocationType.RequestResponse),
any(), any());
}
@Test
void invoke_literalQualifier_isPassedToInvoke() {
SubscriberV2 subscriber = lambdaSubscriber(",\"LambdaParameters\":{\"Qualifier\":\"live\"}", null);
invokeAll(delivery.deliver(subscriber, List.of(event("1", "{\"n\":1}"))));
ArgumentCaptor<String> qualifier = ArgumentCaptor.forClass(String.class);
verify(lambdaService).invoke(any(), any(), qualifier.capture(), any(), any(), any(), any());
assertEquals("live", qualifier.getValue());
}
@Test
void invoke_qualifierExpression_passesEachBatchItsQualifier() {
SubscriberV2 subscriber = lambdaSubscriber(
",\"LambdaParameters\":{\"Qualifier\":\"{% $events.Data.q %}\"}", null);
invokeAll(delivery.deliver(subscriber, List.of(event("1", "{\"q\":\"a\"}"), event("2", "{\"q\":\"b\"}"))));
ArgumentCaptor<String> qualifier = ArgumentCaptor.forClass(String.class);
verify(lambdaService, times(2)).invoke(any(), any(), qualifier.capture(), any(), any(), any(), any());
assertEquals(List.of("a", "b"), qualifier.getAllValues());
}
@Test
void invoke_durableExecutionName_isPassedToInvoke() {
SubscriberV2 subscriber = lambdaSubscriber(",\"LambdaParameters\":{\"DurableExecutionName\":\"run-1\"}", null);
invokeAll(delivery.deliver(subscriber, List.of(event("1", "{\"n\":1}"))));
verify(lambdaService).invoke(eq(REGION), eq(FUNCTION), any(), any(), any(), any(), eq("run-1"));
}
@Test
void invoke_invocationType_eventIsAsynchronousAndTheDefaultAndRequestResponseAreSynchronous() {
invokeAll(delivery.deliver(lambdaSubscriber(",\"LambdaParameters\":{\"InvocationType\":\"EVENT\"}", null),
List.of(event("1", "{}"))));
invokeAll(delivery.deliver(
lambdaSubscriber(",\"LambdaParameters\":{\"InvocationType\":\"REQUEST_RESPONSE\"}", null),
List.of(event("1", "{}"))));
invokeAll(delivery.deliver(lambdaSubscriber("", null), List.of(event("1", "{}"))));
verify(lambdaService, times(1)).invoke(any(), any(), any(), any(), eq(InvocationType.Event), any(), any());
verify(lambdaService, times(2)).invoke(any(), any(), any(), any(), eq(InvocationType.RequestResponse), any(),
any());
}
@Test
void invoke_failedInvoke_isLoggedAndTheNextBatchStillSent() {
SubscriberV2 subscriber = lambdaSubscriber("", null);
subscriber.setBatchConfiguration(json("{\"MaxBatchSize\":1}"));
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any()))
.thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404))
.thenReturn(new InvokeResult(200, "Unhandled", new byte[0], null, "request"));
invokeAll(delivery.deliver(subscriber,
List.of(event("1", "{\"n\":1}"), event("2", "{\"n\":2}"), event("3", "{\"n\":3}"))));
assertEquals(List.of("[{\"n\":1}]", "[{\"n\":2}]", "[{\"n\":3}]"), payloads(3));
}
@Test
void deliver_queueTarget_sendsOneMessagePerEventAndReturnsNoBatches() {
SubscriberV2 subscriber = new SubscriberV2();
subscriber.setArn("arn:aws:events:us-east-1:000000000000:subscriber/q/abc");
subscriber.setInvokeConfiguration(json("{\"TargetArn\":\"" + QUEUE + "\",\"RoleArn\":\"" + ROLE + "\"}"));
List<EventBridgeV2Delivery.LambdaBatch> batches = delivery.deliver(subscriber,
List.of(event("1", "{\"n\":1}"), event("2", "{\"n\":2}")));
assertTrue(batches.isEmpty());
verify(sqsService, times(2)).sendMessage(any(), any(), any(), any(), any(), any(), any());
verify(lambdaService, never()).invoke(any(), any(), any(), any(), any(), any(), any());
}
@Test
void putEvents_returnsBeforeASlowSynchronousInvokeFinishes() {
service.createSubscriber(json(request("s", invoke(FUNCTION, ""))), REGION);
CountDownLatch release = new CountDownLatch(1);
CountDownLatch entered = new CountDownLatch(1);
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any())).thenAnswer(call -> {
entered.countDown();
release.await(30, TimeUnit.SECONDS);
return new InvokeResult(200, null, new byte[0], null, "request");
});
List<EventBridgeV2Service.PutEventsResult> results = service.putEvents(json("{\"EventBusArn\":\"" + bus
+ "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"}]}"), REGION);
List<EventBridgeV2Service.PutEventsResult> second = service.putEvents(json("{\"EventBusArn\":\"" + bus
+ "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"}]}"), REGION);
assertEquals(1, results.size());
assertEquals(1, second.size());
await().atMost(5, TimeUnit.SECONDS).until(() -> entered.getCount() == 0);
verify(lambdaService, times(1)).invoke(any(), any(), any(), any(), any(), any(), any());
release.countDown();
await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> verify(lambdaService, times(2)).invoke(any(), any(),
any(), any(), any(), any(), any()));
}
@Test
void putEvents_oneCallWithThreeEvents_oneInvocation() {
service.createSubscriber(json(request("s", invoke(FUNCTION, ""))), REGION);
service.putEvents(json("{\"EventBusArn\":\"" + bus + "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"},"
+ "{\"Source\":\"a\",\"DetailType\":\"t\"},{\"Source\":\"a\",\"DetailType\":\"t\"}]}"), REGION);
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> verify(lambdaService).invoke(any(), any(), any(),
payload.capture(), any(), any(), any()));
assertEquals(3, size(payload.getValue()));
}
@Test
void clear_whileASlowInvocationRuns_dropsTheWaitingInvocations() {
SubscriberV2 subscriber = service.createSubscriber(json(request("s", invoke(FUNCTION, ""))), REGION);
CountDownLatch release = blockInvocations();
putOneEvent();
awaitInvocations(1);
putOneEvent();
putOneEvent();
OrderedQueue<EventBridgeV2Delivery.LambdaBatch> waiting = service.waitingInvocations(subscriber.getArn());
assertEquals(2, waiting.size());
service.clear();
assertEquals(0, waiting.size());
assertNull(service.waitingInvocations(subscriber.getArn()));
release.countDown();
verify(lambdaService, times(1)).invoke(any(), any(), any(), any(), any(), any(), any());
}
@Test
void deleteSubscriber_whileASlowInvocationRuns_dropsTheWaitingInvocations() {
SubscriberV2 subscriber = service.createSubscriber(json(request("s", invoke(FUNCTION, ""))), REGION);
CountDownLatch release = blockInvocations();
putOneEvent();
awaitInvocations(1);
putOneEvent();
putOneEvent();
OrderedQueue<EventBridgeV2Delivery.LambdaBatch> waiting = service.waitingInvocations(subscriber.getArn());
assertEquals(2, waiting.size());
service.deleteSubscriber(subscriber.getArn(), REGION);
assertEquals(0, waiting.size());
assertNull(service.waitingInvocations(subscriber.getArn()));
release.countDown();
verify(lambdaService, times(1)).invoke(any(), any(), any(), any(), any(), any(), any());
}
@Test
void putEvents_manyPublishesBehindASlowFunction_neverRunTwoInvocationsAtOnce() {
service.createSubscriber(json(request("s", invoke(FUNCTION, ""))), REGION);
AtomicInteger running = new AtomicInteger();
AtomicInteger highest = new AtomicInteger();
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any())).thenAnswer(call -> {
highest.accumulateAndGet(running.incrementAndGet(), Math::max);
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(2));
running.decrementAndGet();
return new InvokeResult(200, null, new byte[0], null, "request");
});
for (int i = 0; i < 40; i++) {
putOneEvent();
}
awaitInvocations(40);
assertEquals(1, highest.get());
}
private CountDownLatch blockInvocations() {
CountDownLatch release = new CountDownLatch(1);
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any())).thenAnswer(call -> {
release.await(30, TimeUnit.SECONDS);
return new InvokeResult(200, null, new byte[0], null, "request");
});
return release;
}
private void putOneEvent() {
service.putEvents(json("{\"EventBusArn\":\"" + bus + "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"}]}"),
REGION);
}
private void awaitInvocations(int count) {
await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> verify(lambdaService, atLeast(count)).invoke(any(),
any(), any(), any(), any(), any(), any()));
}
private void invokeAll(List<EventBridgeV2Delivery.LambdaBatch> batches) {
batches.forEach(delivery::invoke);
}
private static List<String> eventsOf(List<EventBridgeV2Delivery.LambdaBatch> batches) {
return batches.stream().map(batch -> batch.events().toString()).toList();
}
private int size(byte[] payload) {
try {
return MAPPER.readTree(payload).size();
} catch (Exception e) {
throw new AssertionError(e);
}
}
private List<String> payloads(int invocations) {
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> verify(lambdaService, times(invocations)).invoke(any(),
any(), any(), payload.capture(), any(), any(), any()));
return payload.getAllValues().stream().map(bytes -> new String(bytes, StandardCharsets.UTF_8)).toList();
}
private void assertMessage(String message, String target, String extra) {
AwsException e = assertThrows(AwsException.class,
() -> service.createSubscriber(json(request("s", invoke(target, extra))), REGION));
assertEquals("InvalidInputException", e.getErrorCode());
assertEquals(message, e.getMessage());
}
private String request(String name, String invokeConfiguration) {
return "{\"Name\":\"" + name + "\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":"
+ invokeConfiguration + "}";
}
private static String invoke(String target, String extra) {
return "{\"TargetArn\":\"" + target + "\",\"RoleArn\":\"" + ROLE + "\"" + extra + "}";
}
private static SubscriberV2 lambdaSubscriber(String extra, String transformerType) {
SubscriberV2 subscriber = new SubscriberV2();
subscriber.setArn("arn:aws:events:us-east-1:000000000000:subscriber/f/" + System.nanoTime());
subscriber.setInvokeConfiguration(json(invoke(FUNCTION, extra)));
if (transformerType != null) {
subscriber.setTransformer(json("{\"Type\":\"" + transformerType + "\"}"));
}
return subscriber;
}
private static PublishedEvent event(String sequenceNumber, String data) {
ObjectNode system = JsonNodeFactory.instance.objectNode();
system.put("aws:SequenceNumber", sequenceNumber);
return new PublishedEvent(json(data), JsonNodeFactory.instance.objectNode(), system);
}
private static JsonNode json(String value) {
try {
return MAPPER.readTree(value);
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
@@ -297,7 +297,7 @@ class EventBridgeV2ServiceTest {
@ParameterizedTest
@ValueSource(strings = {
"{\"TargetArn\":\"arn:aws:lambda:us-east-1:000000000000:function:f\",\"RoleArn\":\"ROLE\"}",
"{\"TargetArn\":\"arn:aws:lambda:eu-west-1:000000000000:function:f\",\"RoleArn\":\"ROLE\"}",
"{\"TargetArn\":\"arn:aws:sqs:us-east-1:111111111111:other\",\"RoleArn\":\"ROLE\"}",
"{\"TargetArn\":\"QUEUE\",\"RoleArn\":\"ROLE\",\"LambdaParameters\":{}}",
"{\"TargetArn\":\"QUEUE\",\"RoleArn\":\"not-a-role\"}",
@@ -628,10 +628,11 @@ class EventBridgeV2ServiceTest {
assertEquals(List.of("1", "2", "3"), results.stream().map(EventBridgeV2Service.PutEventsResult::sequenceNumber)
.toList());
ArgumentCaptor<SubscriberV2> delivered = ArgumentCaptor.forClass(SubscriberV2.class);
ArgumentCaptor<PublishedEvent> event = ArgumentCaptor.forClass(PublishedEvent.class);
verify(delivery, times(1)).deliver(delivered.capture(), event.capture());
ArgumentCaptor<List<PublishedEvent>> events = ArgumentCaptor.captor();
verify(delivery, times(1)).deliver(delivered.capture(), events.capture());
assertEquals(large.getArn(), delivered.getValue().getArn());
JsonNode data = event.getValue().data();
assertEquals(1, events.getValue().size());
JsonNode data = events.getValue().getFirst().data();
assertEquals("0", data.path("version").asText());
assertEquals(results.getFirst().eventId(), data.path("id").asText());
assertEquals("Order Placed", data.path("detail-type").asText());
@@ -640,8 +641,9 @@ class EventBridgeV2ServiceTest {
assertEquals(REGION, data.path("region").asText());
assertEquals("2026-10-28T12:00:00Z", data.path("time").asText());
assertEquals(750, data.path("detail").path("total").asInt());
assertEquals("application/eventbridge+json", event.getValue().systemMetadata().path("ContentType").asText());
assertEquals("1", event.getValue().systemMetadata().path("aws:SequenceNumber").asText());
PublishedEvent published = events.getValue().getFirst();
assertEquals("application/eventbridge+json", published.systemMetadata().path("ContentType").asText());
assertEquals("1", published.systemMetadata().path("aws:SequenceNumber").asText());
}
@Test
@@ -680,8 +682,10 @@ class EventBridgeV2ServiceTest {
service.createSubscriber(json(subscriberRequest("fifo", bus, ",\"Type\":\"FIFO\"")), REGION);
List<Long> delivered = Collections.synchronizedList(new ArrayList<>());
doAnswer(invocation -> {
PublishedEvent event = invocation.getArgument(1);
delivered.add(Long.parseLong(event.systemMetadata().path("aws:SequenceNumber").asText()));
List<PublishedEvent> events = invocation.getArgument(1);
for (PublishedEvent event : events) {
delivered.add(Long.parseLong(event.systemMetadata().path("aws:SequenceNumber").asText()));
}
Thread.yield();
return null;
}).when(delivery).deliver(any(), any());
@@ -13,6 +13,8 @@ import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client;
import software.amazon.awssdk.services.eventbridgev2.model.DescribeSubscriberResponse;
import software.amazon.awssdk.services.eventbridgev2.model.FilterScope;
import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException;
import software.amazon.awssdk.services.eventbridgev2.model.InvocationType;
import software.amazon.awssdk.services.eventbridgev2.model.InvokeConfiguration;
import software.amazon.awssdk.services.eventbridgev2.model.PutEventsResponse;
import software.amazon.awssdk.services.eventbridgev2.model.ResourceInUseException;
import software.amazon.awssdk.services.eventbridgev2.model.ResourceNotFoundException;
@@ -26,6 +28,7 @@ import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import java.net.URI;
import java.util.List;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -208,6 +211,70 @@ class EventBridgeV2SubscriberIntegrationTest {
}
}
@Test
void aLambdaSubscriberIsCreatedAndDescribedAsGiven() {
String suffix = suffix();
String function = "arn:aws:lambda:us-east-1:000000000000:function:v2-handler-" + suffix;
try (EventBridgeV2Client events = events()) {
String bus = events.createEventBus(request -> request.name("v2-lambda-" + suffix)).eventBusArn();
String subscriber = events.createSubscriber(request -> request.name("fn").eventBusArn(bus)
.invokeConfiguration(invoke -> invoke.targetArn(function + ":live").roleArn(ROLE)
.lambdaParameters(lambda -> lambda.invocationType(InvocationType.EVENT)
.qualifier("{% $events.Data.detail.q %}").invocationTimeoutSeconds("30")))
).subscriberArn();
InvokeConfiguration described = events.describeSubscriber(request -> request.subscriberArn(subscriber))
.invokeConfiguration();
assertEquals(function + ":live", described.targetArn());
assertEquals(InvocationType.EVENT, described.lambdaParameters().invocationType());
assertEquals("{% $events.Data.detail.q %}", described.lambdaParameters().qualifier());
assertEquals("30", described.lambdaParameters().invocationTimeoutSeconds());
assertNull(described.sqsParameters());
events.deleteSubscriber(request -> request.subscriberArn(subscriber));
events.deleteEventBus(request -> request.eventBusArn(bus));
}
}
@Test
void aLambdaSubscriberIsRefusedWithTheMeasuredMessages() {
String suffix = suffix();
String function = "arn:aws:lambda:us-east-1:000000000000:function:v2-handler-" + suffix;
try (EventBridgeV2Client events = events()) {
String bus = events.createEventBus(request -> request.name("v2-refused-" + suffix)).eventBusArn();
assertEquals("SqsParameters is not supported for target " + function + ". Expected LambdaParameters",
refused(events, bus, function, invoke -> invoke.sqsParameters(sqs -> sqs.messageGroupId("g"))));
assertEquals("InvokeConfiguration.TargetArn: TargetArn must be in region us-east-1", refused(events, bus,
"arn:aws:lambda:eu-west-1:000000000000:function:f", invoke -> { }));
assertEquals("Target resource account (123456789012) must match the subscriber account (000000000000)",
refused(events, bus, "arn:aws:lambda:us-east-1:123456789012:function:f", invoke -> { }));
assertEquals("InvokeConfiguration.TargetArn: TargetArn resource must be of the form "
+ "function:{name}[:{qualifier}]", refused(events, bus,
"arn:aws:lambda:us-east-1:000000000000:function", invoke -> { }));
assertEquals("InvocationTimeoutSeconds must be between 1 and 30", refused(events, bus, function,
invoke -> invoke.lambdaParameters(lambda -> lambda.invocationTimeoutSeconds("31"))));
assertEquals("InvocationTimeoutSeconds must be a valid integer or a JSONata expression", refused(events, bus,
function, invoke -> invoke.lambdaParameters(lambda -> lambda.invocationTimeoutSeconds("abc"))));
assertEquals("1 validation error detected: Value at 'invokeConfiguration.lambdaParameters.invocationType' "
+ "failed to satisfy constraint: Member must satisfy enum value set: [REQUEST_RESPONSE, EVENT]",
refused(events, bus, function,
invoke -> invoke.lambdaParameters(lambda -> lambda.invocationType("Event"))));
events.deleteEventBus(request -> request.eventBusArn(bus));
}
}
private static String refused(EventBridgeV2Client events, String bus, String target,
Consumer<InvokeConfiguration.Builder> parameters) {
InvalidInputException e = assertThrows(InvalidInputException.class, () -> events.createSubscriber(
request -> request.name("refused").eventBusArn(bus).invokeConfiguration(invoke -> {
invoke.targetArn(target).roleArn(ROLE);
parameters.accept(invoke);
})));
return e.awsErrorDetails().errorMessage();
}
/**
* What is in the queue now. PutEvents answers only once its own deliveries are sent, so a look after
* it sees everything the call delivered, and an empty look means it delivered nothing.
@@ -81,9 +81,11 @@ class EventBridgeV2WebhooksTest {
EventBridgeV2Delivery delivery = mock(EventBridgeV2Delivery.class);
doAnswer(call -> {
SubscriberV2 subscriber = call.getArgument(0);
PublishedEvent event = call.getArgument(1);
delivered.add(event);
deliveredBodies.add(subscriber.getName() + "=" + EventBridgeV2Delivery.body(subscriber, event));
List<PublishedEvent> events = call.getArgument(1);
for (PublishedEvent event : events) {
delivered.add(event);
deliveredBodies.add(subscriber.getName() + "=" + EventBridgeV2Delivery.body(subscriber, event));
}
return null;
}).when(delivery).deliver(any(), any());
clock = new ManualClock(Instant.parse("2026-11-25T06:00:00.123Z"));
@@ -0,0 +1,132 @@
package io.floci.aws.services.eventbridgev2;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class OrderedQueueTest {
@Test
void drain_worksOffItemsInTheOrderAdded() {
OrderedQueue<Integer> queue = new OrderedQueue<>();
queue.addAll(List.of(1, 2, 3));
queue.addAll(List.of(4, 5));
List<Integer> seen = new ArrayList<>();
queue.drain(seen::add);
assertEquals(List.of(1, 2, 3, 4, 5), seen);
assertEquals(0, queue.size());
}
@Test
void drain_fromTwoThreads_neverRunsTwoWorkersAtOnce() throws InterruptedException {
OrderedQueue<Integer> queue = new OrderedQueue<>();
for (int i = 0; i < 200; i++) {
queue.addAll(List.of(i));
}
AtomicInteger running = new AtomicInteger();
AtomicInteger highest = new AtomicInteger();
List<Integer> seen = Collections.synchronizedList(new ArrayList<>());
Thread first = Thread.ofVirtual().start(() -> queue.drain(item -> work(item, running, highest, seen)));
Thread second = Thread.ofVirtual().start(() -> queue.drain(item -> work(item, running, highest, seen)));
first.join(10_000);
second.join(10_000);
assertEquals(1, highest.get());
assertEquals(200, seen.size());
for (int i = 0; i < 200; i++) {
assertEquals(i, seen.get(i));
}
}
@Test
void drainInBackground_runsOneWorkerAtATimeAndLosesNoItem() {
OrderedQueue<int[]> queue = new OrderedQueue<>();
int producers = 4;
int perProducer = 250;
AtomicInteger running = new AtomicInteger();
AtomicInteger highest = new AtomicInteger();
List<int[]> seen = Collections.synchronizedList(new ArrayList<>());
for (int producer = 0; producer < producers; producer++) {
int id = producer;
Thread.ofVirtual().start(() -> {
for (int n = 0; n < perProducer; n++) {
queue.addAll(List.of(new int[] {id, n}));
queue.drainInBackground(item -> {
highest.accumulateAndGet(running.incrementAndGet(), Math::max);
seen.add(item);
running.decrementAndGet();
}, "ordered-queue-test");
}
});
}
await().atMost(20, TimeUnit.SECONDS).until(() -> seen.size() == producers * perProducer);
assertEquals(1, highest.get());
int[] next = new int[producers];
synchronized (seen) {
for (int[] item : seen) {
assertEquals(next[item[0]]++, item[1]);
}
}
}
@Test
void clear_dropsTheWaitingItems() {
OrderedQueue<Integer> queue = new OrderedQueue<>();
queue.addAll(List.of(1, 2, 3));
queue.clear();
List<Integer> seen = new ArrayList<>();
queue.drain(seen::add);
assertEquals(0, queue.size());
assertTrue(seen.isEmpty());
}
@Test
void clear_whileAWorkerIsBusy_letsItFinishAndRunsNothingAfter() {
OrderedQueue<Integer> queue = new OrderedQueue<>();
CountDownLatch release = new CountDownLatch(1);
CountDownLatch entered = new CountDownLatch(1);
List<Integer> seen = Collections.synchronizedList(new ArrayList<>());
queue.addAll(List.of(1, 2, 3));
queue.drainInBackground(item -> {
entered.countDown();
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
seen.add(item);
}, "ordered-queue-test");
await().atMost(5, TimeUnit.SECONDS).until(() -> entered.getCount() == 0);
queue.clear();
assertEquals(0, queue.size());
release.countDown();
await().atMost(5, TimeUnit.SECONDS).until(() -> seen.size() == 1);
assertEquals(List.of(1), seen);
}
private static void work(int item, AtomicInteger running, AtomicInteger highest, List<Integer> seen) {
highest.accumulateAndGet(running.incrementAndGet(), Math::max);
LockSupport.parkNanos(1_000);
seen.add(item);
running.decrementAndGet();
}
}