mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(eventbridge): execute target retry and dead-letter policies (#4736)
* feat(eventbridge): execute target retry and dead-letter policies PutTargets now validates, stores and returns a target's RetryPolicy and DeadLetterConfig. Failed deliveries from PutEvents and scheduled rules are retried with backoff within the configured attempts and event age, and exhausted or non-retryable events are sent to the standard SQS dead-letter queue with the AWS failure attributes. * fix(eventbridge): order target retries by due time and honour a lowered retry limit Pending retries are kept in a queue ordered by their next attempt, so each wake-up takes only what is due instead of scanning every pending retry. The clock is read again for each retry, so a slow target cannot let a later retry run past its event age, and a reset mid-tick stops the remaining retries. A retry now checks the target's current MaximumRetryAttempts before invoking it, as it already did for MaximumEventAgeInSeconds. * fix(eventbridge): drop a target retry that outlives a reset An attempt still running when the emulator resets can fail afterwards. Its retry or dead-letter delivery is now dropped, so a rule and target recreated under the same names after the reset do not receive a pre-reset event. A scheduled retry wake-up keeps only its due time, not the event. * fix(eventbridge): wake a target retry at its due time after a slow attempt The retry delay was measured from when the failed attempt started but counted from when it failed, so every retry after a slow attempt woke late by the attempt's duration, and an expired event reached its dead-letter queue late. * fix(eventbridge): drop a removed target's retries and drive retries from one tick RemoveTargets now drops the removed targets' pending retries, so a target re-added under the same Id does not receive an event from before its removal. Pending retries are taken by one periodic tick, as in the scheduler's dispatcher, instead of a timer per retry, so a reset leaves no timers behind. * fix(eventbridge): warn about a blank dead-letter queue ARN PutTargets accepts a whitespace-only DeadLetterConfig Arn, since AWS constrains only its length. Delivery skipped it without a word; it now gets the same WARN as any other dead-letter queue that is not a standard SQS queue in the rule's region.
This commit is contained in:
1 parent
4716ac9992
commit
0a54d0708e
15 files changed
+1221
-46
No files matched your search
@@ -303,6 +303,84 @@ class EventBridgeTest {
|
||||
assertThat(body).doesNotContain("orderId");
|
||||
}
|
||||
|
||||
// ──────────────────────────── Retry and dead-letter ────────────────────────────
|
||||
|
||||
@Test
|
||||
@Order(35)
|
||||
void undeliverableEventIsSentToTheTargetDeadLetterQueue() {
|
||||
String dlqUrl = sqs.createQueue(CreateQueueRequest.builder()
|
||||
.queueName(TestFixtures.uniqueName("eb-dlq")).build()).queueUrl();
|
||||
String dlqArn = sqs.getQueueAttributes(GetQueueAttributesRequest.builder()
|
||||
.queueUrl(dlqUrl).attributeNamesWithStrings("QueueArn").build())
|
||||
.attributesAsStrings().get("QueueArn");
|
||||
String missingQueueArn = dlqArn + "-missing";
|
||||
String source = TestFixtures.uniqueName("com.floci.dlq");
|
||||
String dlqRuleName = TestFixtures.uniqueName("eb-dlq-rule");
|
||||
String ruleArn = eb.putRule(PutRuleRequest.builder()
|
||||
.name(dlqRuleName)
|
||||
.eventPattern("{\"source\":[\"" + source + "\"]}")
|
||||
.state(RuleState.ENABLED)
|
||||
.build()).ruleArn();
|
||||
try {
|
||||
eb.putTargets(PutTargetsRequest.builder()
|
||||
.rule(dlqRuleName)
|
||||
.targets(Target.builder()
|
||||
.id("missing-queue")
|
||||
.arn(missingQueueArn)
|
||||
.retryPolicy(RetryPolicy.builder()
|
||||
.maximumRetryAttempts(2).maximumEventAgeInSeconds(60).build())
|
||||
.deadLetterConfig(DeadLetterConfig.builder().arn(dlqArn).build())
|
||||
.build())
|
||||
.build());
|
||||
|
||||
Target stored = eb.listTargetsByRule(ListTargetsByRuleRequest.builder().rule(dlqRuleName).build())
|
||||
.targets().get(0);
|
||||
assertThat(stored.retryPolicy().maximumRetryAttempts()).isEqualTo(2);
|
||||
assertThat(stored.retryPolicy().maximumEventAgeInSeconds()).isEqualTo(60);
|
||||
assertThat(stored.deadLetterConfig().arn()).isEqualTo(dlqArn);
|
||||
|
||||
eb.putEvents(PutEventsRequest.builder()
|
||||
.entries(PutEventsRequestEntry.builder()
|
||||
.source(source).detailType("Undeliverable").detail("{\"id\":\"1\"}").build())
|
||||
.build());
|
||||
|
||||
List<Message> messages = sqs.receiveMessage(ReceiveMessageRequest.builder()
|
||||
.queueUrl(dlqUrl)
|
||||
.messageAttributeNames("All")
|
||||
.waitTimeSeconds(2)
|
||||
.build()).messages();
|
||||
assertThat(messages).hasSize(1);
|
||||
assertThat(messages.get(0).body()).contains(source).contains("Undeliverable");
|
||||
Map<String, MessageAttributeValue> attributes = messages.get(0).messageAttributes();
|
||||
assertThat(attributes.get("RULE_ARN").stringValue()).isEqualTo(ruleArn);
|
||||
assertThat(attributes.get("TARGET_ARN").stringValue()).isEqualTo(missingQueueArn);
|
||||
assertThat(attributes.get("ERROR_CODE").stringValue()).isEqualTo("NO_RESOURCE");
|
||||
assertThat(attributes.get("RETRY_ATTEMPTS").stringValue()).isEqualTo("0");
|
||||
} finally {
|
||||
eb.removeTargets(RemoveTargetsRequest.builder().rule(dlqRuleName).ids("missing-queue").build());
|
||||
eb.deleteRule(DeleteRuleRequest.builder().name(dlqRuleName).build());
|
||||
sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(dlqUrl).build());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(36)
|
||||
void putTargetsRejectsOutOfRangeRetryPolicy() {
|
||||
assertThatThrownBy(() -> eb.putTargets(PutTargetsRequest.builder()
|
||||
.rule(ruleName)
|
||||
.targets(Target.builder()
|
||||
.id("bad-retry")
|
||||
.arn(sinkQueueArn)
|
||||
.retryPolicy(RetryPolicy.builder().maximumEventAgeInSeconds(0).build())
|
||||
.build())
|
||||
.build()))
|
||||
.isInstanceOfSatisfying(EventBridgeException.class, e -> {
|
||||
assertThat(e.statusCode()).isEqualTo(400);
|
||||
assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationException");
|
||||
assertThat(e.getMessage()).contains("targets.1.member.retryPolicy.maximumEventAgeInSeconds");
|
||||
});
|
||||
}
|
||||
|
||||
// ──────────────────────────── Tags ────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -127,9 +127,34 @@ the state machine from the account and region in its ARN.
|
||||
|
||||
State machine aliases and versions are not supported as EventBridge targets.
|
||||
|
||||
## Target Retry and Dead-Letter Queues
|
||||
|
||||
A target's `RetryPolicy` and `DeadLetterConfig` are validated by `PutTargets`, stored with the target, returned by `ListTargetsByRule`, and applied to delivery from `PutEvents` and scheduled rules.
|
||||
|
||||
```bash
|
||||
aws events put-targets \
|
||||
--rule order-placed-rule \
|
||||
--event-bus-name my-bus \
|
||||
--targets '[{
|
||||
"Id": "orders-queue",
|
||||
"Arn": "arn:aws:sqs:us-east-1:000000000000:orders",
|
||||
"RetryPolicy": {"MaximumRetryAttempts": 4, "MaximumEventAgeInSeconds": 3600},
|
||||
"DeadLetterConfig": {"Arn": "arn:aws:sqs:us-east-1:000000000000:orders-dlq"}
|
||||
}]' \
|
||||
--endpoint-url $AWS_ENDPOINT_URL
|
||||
```
|
||||
|
||||
- The first attempt is immediate. Throttling, server-side errors from the target, and internal errors are retried with exponential backoff (1 second doubling, capped at 5 minutes) until `MaximumRetryAttempts` or `MaximumEventAgeInSeconds` runs out. The AWS defaults, 185 attempts and 86400 seconds, apply when a field is omitted.
|
||||
- A missing target resource, a permission error, or any other client error is not retried.
|
||||
- An exhausted or non-retryable event is sent to the `DeadLetterConfig` queue with the original event as the body and the `RULE_ARN`, `TARGET_ARN`, `ERROR_CODE`, `ERROR_MESSAGE`, `EXHAUSTED_RETRY_CONDITION` and `RETRY_ATTEMPTS` message attributes. `EXHAUSTED_RETRY_CONDITION` is omitted for a non-retryable error, since no retry limit was reached. The `ERROR_CODE` value is Floci's best mapping of the underlying failure.
|
||||
- The dead-letter queue must be a standard SQS queue in the rule's region, as in AWS. It may be in another account. Any other queue, and any failure to send to it, is logged as a `WARN`.
|
||||
- A retry uses the target's current definition, so `PutTargets` changes apply to pending retries, and a target removed with `RemoveTargets` stops being retried.
|
||||
- An accepted asynchronous Lambda invocation counts as delivered. A later function error is handled by Lambda's own retry and destination settings, not by the rule.
|
||||
- Pending retries are kept in memory and are dropped by an emulator reset or restart.
|
||||
|
||||
## Current Behavior
|
||||
|
||||
- `PutEvents` reports success once the source bus accepts an event, so target delivery failures surface only as a `WARN` in the Floci logs.
|
||||
- `PutEvents` reports success once the source bus accepts an event. Target delivery failures are retried and dead-lettered as described above, and otherwise surface only as a `WARN` in the Floci logs.
|
||||
- A `Detail` forwarded to an event bus must be a JSON object, as in AWS; anything else is dropped, including an `InputPath` selecting a scalar such as `$.detail.orderId` or an envelope carrying `"detail": null`.
|
||||
- A bus ARN naming another account is forwarded under that account, so the target bus and its rules resolve there.
|
||||
- Onward delivery from that bus follows each target type: SQS and Step Functions resolve cross-account, while Lambda, SNS, Batch and Firehose resolve in the caller's account.
|
||||
|
||||
@@ -242,6 +242,15 @@ public class EventBridgeHandler {
|
||||
if (!ecsParamsNode.isMissingNode() && ecsParamsNode.isObject()) {
|
||||
target.setEcsParameters(objectMapper.convertValue(ecsParamsNode, EcsParameters.class));
|
||||
}
|
||||
JsonNode retryPolicyNode = t.path("RetryPolicy");
|
||||
if (retryPolicyNode.isObject()) {
|
||||
target.setRetryPolicy(objectMapper.convertValue(retryPolicyNode, Target.RetryPolicy.class));
|
||||
}
|
||||
JsonNode deadLetterConfigNode = t.path("DeadLetterConfig");
|
||||
if (deadLetterConfigNode.isObject()) {
|
||||
target.setDeadLetterConfig(
|
||||
objectMapper.convertValue(deadLetterConfigNode, Target.DeadLetterConfig.class));
|
||||
}
|
||||
targets.add(target);
|
||||
}
|
||||
}
|
||||
@@ -305,6 +314,12 @@ public class EventBridgeHandler {
|
||||
if (t.getEcsParameters() != null) {
|
||||
node.set("EcsParameters", objectMapper.valueToTree(t.getEcsParameters()));
|
||||
}
|
||||
if (t.getRetryPolicy() != null) {
|
||||
node.set("RetryPolicy", objectMapper.valueToTree(t.getRetryPolicy()));
|
||||
}
|
||||
if (t.getDeadLetterConfig() != null) {
|
||||
node.set("DeadLetterConfig", objectMapper.valueToTree(t.getDeadLetterConfig()));
|
||||
}
|
||||
targetsArray.add(node);
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
|
||||
+10
-6
@@ -1,10 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.batch.BatchService;
|
||||
@@ -26,6 +28,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -230,12 +233,13 @@ public class EventBridgeInvoker {
|
||||
: targetAccount;
|
||||
BUS_TO_BUS_DEPTH.set(depth + 1);
|
||||
try {
|
||||
var result = eventBridgeService.putEvents(List.of(entry), targetRegion, forwardAccount);
|
||||
EventBridgeService.PutEventsResult result =
|
||||
eventBridgeService.putEvents(List.of(entry), targetRegion, forwardAccount);
|
||||
if (result.failedCount() > 0) {
|
||||
LOG.warnv("EventBridge event-bus target {0} rejected event: {1}", arn, result.entries());
|
||||
} else {
|
||||
LOG.debugv("EventBridge delivered to EventBus: {0}", arn);
|
||||
Map<String, String> rejection = result.entries().getFirst();
|
||||
throw new AwsException(rejection.get("ErrorCode"), rejection.get("ErrorMessage"), 400);
|
||||
}
|
||||
LOG.debugv("EventBridge delivered to EventBus: {0}", arn);
|
||||
} finally {
|
||||
if (depth == 0) {
|
||||
BUS_TO_BUS_DEPTH.remove();
|
||||
@@ -246,8 +250,8 @@ public class EventBridgeInvoker {
|
||||
} else {
|
||||
LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("EventBridge failed to deliver to target {0}: {1}", arn, e.getMessage());
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+39
-6
@@ -59,7 +59,7 @@ public class EventBridgeService implements ResourceProvider {
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RuleScheduler ruleScheduler;
|
||||
private final EventBridgeInvoker invoker;
|
||||
private final TargetDispatcher dispatcher;
|
||||
private final ResourceGroupsTaggingService resourceGroupsTaggingService;
|
||||
private final ReplayDispatcher replayDispatcher;
|
||||
|
||||
@@ -69,7 +69,7 @@ public class EventBridgeService implements ResourceProvider {
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
RuleScheduler ruleScheduler,
|
||||
EventBridgeInvoker invoker,
|
||||
TargetDispatcher dispatcher,
|
||||
ReplayDispatcher replayDispatcher,
|
||||
ResourceGroupsTaggingService resourceGroupsTaggingService) {
|
||||
this(
|
||||
@@ -87,7 +87,7 @@ public class EventBridgeService implements ResourceProvider {
|
||||
new TypeReference<Map<String, Replay>>() {}),
|
||||
storageFactory.create("eventbridge", "eventbridge-connections.json",
|
||||
new TypeReference<Map<String, Connection>>() {}),
|
||||
regionResolver, objectMapper, ruleScheduler, invoker, replayDispatcher,
|
||||
regionResolver, objectMapper, ruleScheduler, dispatcher, replayDispatcher,
|
||||
resourceGroupsTaggingService
|
||||
);
|
||||
}
|
||||
@@ -102,7 +102,7 @@ public class EventBridgeService implements ResourceProvider {
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
RuleScheduler ruleScheduler,
|
||||
EventBridgeInvoker invoker,
|
||||
TargetDispatcher dispatcher,
|
||||
ReplayDispatcher replayDispatcher,
|
||||
ResourceGroupsTaggingService resourceGroupsTaggingService) {
|
||||
this.busStore = busStore;
|
||||
@@ -115,7 +115,7 @@ public class EventBridgeService implements ResourceProvider {
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.ruleScheduler = ruleScheduler;
|
||||
this.invoker = invoker;
|
||||
this.dispatcher = dispatcher;
|
||||
this.replayDispatcher = replayDispatcher;
|
||||
this.resourceGroupsTaggingService = resourceGroupsTaggingService;
|
||||
}
|
||||
@@ -406,6 +406,7 @@ public class EventBridgeService implements ResourceProvider {
|
||||
// ──────────────────────────── Targets ────────────────────────────
|
||||
|
||||
public int putTargets(String ruleName, String busName, List<Target> newTargets, String region) {
|
||||
validateRetrySettings(newTargets);
|
||||
String effectiveBus = resolvedBusName(busName);
|
||||
String key = ruleKey(region, effectiveBus, ruleName);
|
||||
ruleStore.get(key)
|
||||
@@ -421,6 +422,36 @@ public class EventBridgeService implements ResourceProvider {
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void validateRetrySettings(List<Target> targets) {
|
||||
for (int i = 0; i < targets.size(); i++) {
|
||||
Target target = targets.get(i);
|
||||
Integer attempts = target.getRetryPolicy() != null ? target.getRetryPolicy().maximumRetryAttempts() : null;
|
||||
Integer age = target.getRetryPolicy() != null ? target.getRetryPolicy().maximumEventAgeInSeconds() : null;
|
||||
String arn = target.getDeadLetterConfig() != null ? target.getDeadLetterConfig().arn() : null;
|
||||
String field = null;
|
||||
Object value = null;
|
||||
String constraint = null;
|
||||
if (attempts != null && (attempts < 0 || attempts > 185)) {
|
||||
field = "retryPolicy.maximumRetryAttempts";
|
||||
value = attempts;
|
||||
constraint = attempts < 0 ? "value greater than or equal to 0" : "value less than or equal to 185";
|
||||
} else if (age != null && (age < 60 || age > 86400)) {
|
||||
field = "retryPolicy.maximumEventAgeInSeconds";
|
||||
value = age;
|
||||
constraint = age < 60 ? "value greater than or equal to 60" : "value less than or equal to 86400";
|
||||
} else if (arn != null && (arn.isEmpty() || arn.length() > 1600)) {
|
||||
field = "deadLetterConfig.arn";
|
||||
value = arn;
|
||||
constraint = arn.isEmpty() ? "length greater than or equal to 1" : "length less than or equal to 1600";
|
||||
}
|
||||
if (field != null) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + value
|
||||
+ "' at 'targets." + (i + 1) + ".member." + field
|
||||
+ "' failed to satisfy constraint: Member must have " + constraint, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record RemoveTargetsResult(int successfulCount, int failedCount) {}
|
||||
|
||||
public RemoveTargetsResult removeTargets(String ruleName, String busName,
|
||||
@@ -435,6 +466,7 @@ public class EventBridgeService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
targetStore.put(key, existing);
|
||||
ruleStore.get(key).ifPresent(rule -> dispatcher.dropPendingRetries(rule.getArn(), ids));
|
||||
return new RemoveTargetsResult(removed, ids.size() - removed);
|
||||
}
|
||||
|
||||
@@ -753,7 +785,8 @@ public class EventBridgeService implements ResourceProvider {
|
||||
List<Target> targets = accountGet(targetStore, accountId, ruleKey).orElse(List.of());
|
||||
String eventJson = buildEventEnvelope(entry, effectiveBus, eventId, region, accountId);
|
||||
for (Target target : targets) {
|
||||
invoker.invokeTarget(target, eventJson, region);
|
||||
dispatcher.dispatch(rule.getArn(), target, eventJson, region,
|
||||
() -> accountGet(targetStore, accountId, ruleKey).orElse(List.of()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ public class RuleScheduler implements Resettable {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final String defaultAccountId;
|
||||
private final String defaultRegion;
|
||||
private final EventBridgeInvoker invoker;
|
||||
private final TargetDispatcher dispatcher;
|
||||
private final Clock clock;
|
||||
private final ConcurrentHashMap<String, ScheduleContext> scheduleContexts = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -38,8 +38,8 @@ public class RuleScheduler implements Resettable {
|
||||
public RuleScheduler(Vertx vertx,
|
||||
EmulatorConfig config,
|
||||
ObjectMapper objectMapper,
|
||||
EventBridgeInvoker invoker) {
|
||||
this(vertx, config, objectMapper, invoker, Clock.systemUTC());
|
||||
TargetDispatcher dispatcher) {
|
||||
this(vertx, config, objectMapper, dispatcher, Clock.systemUTC());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,13 +50,13 @@ public class RuleScheduler implements Resettable {
|
||||
RuleScheduler(Vertx vertx,
|
||||
EmulatorConfig config,
|
||||
ObjectMapper objectMapper,
|
||||
EventBridgeInvoker invoker,
|
||||
TargetDispatcher dispatcher,
|
||||
Clock clock) {
|
||||
this.vertx = vertx;
|
||||
this.objectMapper = objectMapper;
|
||||
this.defaultAccountId = config.defaultAccountId();
|
||||
this.defaultRegion = config.defaultRegion();
|
||||
this.invoker = invoker;
|
||||
this.dispatcher = dispatcher;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -174,15 +174,15 @@ public class RuleScheduler implements Resettable {
|
||||
LOG.debugv("Rule {0} firing scheduled event", data.rule.getName());
|
||||
|
||||
for (Target target : data.targets) {
|
||||
try {
|
||||
invoker.invokeTarget(target, eventJson, region);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to invoke target {0} for rule {1}: {2}",
|
||||
target.getId(), data.rule.getName(), e.getMessage());
|
||||
}
|
||||
dispatcher.dispatch(data.rule.getArn(), target, eventJson, region, () -> currentTargets(dataSupplier));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Target> currentTargets(Supplier<ScheduleData> dataSupplier) {
|
||||
ScheduleData current = dataSupplier.get();
|
||||
return current == null || current.rule() == null ? List.of() : current.targets();
|
||||
}
|
||||
|
||||
private String buildScheduledEvent(Rule rule, String region) {
|
||||
try {
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.PriorityBlockingQueue;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Delivers a matched event to one rule target, applying the target's {@code RetryPolicy} and
|
||||
* {@code DeadLetterConfig}. The first attempt runs on the caller's thread; retryable failures are
|
||||
* retried with exponential backoff (1s doubling, capped at 300s) against the target's current
|
||||
* definition until {@code MaximumRetryAttempts} or {@code MaximumEventAgeInSeconds} (AWS defaults
|
||||
* 185 and 86400) is exhausted. Exhausted or non-retryable events go to the standard SQS queue in
|
||||
* the rule's region named by {@code DeadLetterConfig}, with the AWS dead-letter message attributes.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class TargetDispatcher implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(TargetDispatcher.class);
|
||||
|
||||
private static final int DEFAULT_MAXIMUM_RETRY_ATTEMPTS = 185;
|
||||
private static final int DEFAULT_MAXIMUM_EVENT_AGE_SECONDS = 86400;
|
||||
private static final long MAXIMUM_BACKOFF_SECONDS = 300;
|
||||
private static final String EXHAUSTED_BY_ATTEMPTS = "MaximumRetryAttempts";
|
||||
private static final String EXHAUSTED_BY_AGE = "MaximumEventAgeInSeconds";
|
||||
private static final Set<String> RETRYABLE_ERROR_CODES = Set.of("THROTTLING", "ERROR_FROM_TARGET", "INTERNAL_ERROR");
|
||||
|
||||
private final EventBridgeInvoker invoker;
|
||||
private final SqsService sqsService;
|
||||
private final String baseUrl;
|
||||
private final Clock clock;
|
||||
private final ScheduledExecutorService executor;
|
||||
private final PriorityBlockingQueue<Delivery> pending =
|
||||
new PriorityBlockingQueue<>(11, Comparator.comparing(Delivery::nextAttemptAt));
|
||||
private final AtomicLong generation = new AtomicLong();
|
||||
|
||||
@Inject
|
||||
public TargetDispatcher(EventBridgeInvoker invoker, SqsService sqsService, EmulatorConfig config, Clock clock) {
|
||||
this(invoker, sqsService, config.baseUrl(), clock, Executors.newSingleThreadScheduledExecutor(runnable -> {
|
||||
Thread thread = new Thread(runnable, "eventbridge-target-retry");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}));
|
||||
}
|
||||
|
||||
TargetDispatcher(EventBridgeInvoker invoker, SqsService sqsService, String baseUrl, Clock clock,
|
||||
ScheduledExecutorService executor) {
|
||||
this.invoker = invoker;
|
||||
this.sqsService = sqsService;
|
||||
this.baseUrl = baseUrl;
|
||||
this.clock = clock;
|
||||
this.executor = executor;
|
||||
if (executor != null) {
|
||||
executor.scheduleWithFixedDelay(this::tick, 1, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
if (executor != null) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
generation.incrementAndGet();
|
||||
pending.clear();
|
||||
}
|
||||
|
||||
public void dispatch(String ruleArn, Target target, String eventJson, String region,
|
||||
Supplier<List<Target>> currentTargets) {
|
||||
Instant now = clock.instant();
|
||||
try {
|
||||
attempt(new Delivery(ruleArn, target.getId(), eventJson, region, currentTargets, generation.get(), now, 0,
|
||||
null, null, now), target, now);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EventBridge rule {0} could not dispatch to target {1}: {2}",
|
||||
ruleArn, target.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void dropPendingRetries(String ruleArn, List<String> targetIds) {
|
||||
pending.removeIf(delivery -> delivery.ruleArn().equals(ruleArn) && targetIds.contains(delivery.targetId()));
|
||||
}
|
||||
|
||||
void tick() {
|
||||
while (true) {
|
||||
Delivery delivery = pending.peek();
|
||||
Instant now = clock.instant();
|
||||
if (delivery == null || now.isBefore(delivery.nextAttemptAt()) || !pending.remove(delivery)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
RequestScopes.runAs(AwsArnUtils.parse(delivery.ruleArn()).accountId(), () -> retry(delivery, now));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EventBridge retry for rule {0} target {1} failed: {2}",
|
||||
delivery.ruleArn(), delivery.targetId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void retry(Delivery delivery, Instant now) {
|
||||
if (delivery.generation() != generation.get()) {
|
||||
return;
|
||||
}
|
||||
Target target = delivery.currentTargets().get().stream()
|
||||
.filter(candidate -> delivery.targetId().equals(candidate.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (target == null) {
|
||||
LOG.debugv("Dropped pending retry for rule {0} target {1}: target or rule removed",
|
||||
delivery.ruleArn(), delivery.targetId());
|
||||
return;
|
||||
}
|
||||
if (!now.isBefore(expiresAt(delivery, target))) {
|
||||
deadLetter(delivery, target, EXHAUSTED_BY_AGE);
|
||||
return;
|
||||
}
|
||||
if (delivery.retryAttempts() >= maximumRetryAttempts(target)) {
|
||||
deadLetter(delivery, target, EXHAUSTED_BY_ATTEMPTS);
|
||||
return;
|
||||
}
|
||||
attempt(delivery.nextRetry(), target, now);
|
||||
}
|
||||
|
||||
private void attempt(Delivery delivery, Target target, Instant now) {
|
||||
try {
|
||||
invoker.invokeTarget(target, delivery.eventJson(), delivery.region());
|
||||
} catch (Exception e) {
|
||||
if (delivery.generation() != generation.get()) {
|
||||
return;
|
||||
}
|
||||
String errorCode = classify(e);
|
||||
String message = e.getMessage() != null && !e.getMessage().isBlank()
|
||||
? e.getMessage()
|
||||
: e.getClass().getSimpleName();
|
||||
LOG.warnv("EventBridge rule {0} target {1} delivery failed with {2}: {3}",
|
||||
delivery.ruleArn(), target.getId(), errorCode, message);
|
||||
long backoffSeconds = Math.min(MAXIMUM_BACKOFF_SECONDS, 1L << Math.min(delivery.retryAttempts(), 9));
|
||||
Instant backoff = now.plusSeconds(backoffSeconds);
|
||||
Instant expiresAt = expiresAt(delivery, target);
|
||||
Delivery failed = delivery.failed(errorCode, message, backoff.isBefore(expiresAt) ? backoff : expiresAt);
|
||||
if (!RETRYABLE_ERROR_CODES.contains(errorCode)) {
|
||||
deadLetter(failed, target, null);
|
||||
} else if (failed.retryAttempts() >= maximumRetryAttempts(target)) {
|
||||
deadLetter(failed, target, EXHAUSTED_BY_ATTEMPTS);
|
||||
} else {
|
||||
pending.add(failed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A heuristic mapping onto the AWS dead-letter ERROR_CODE values; AWS does not document it.
|
||||
private static String classify(Exception e) {
|
||||
if (!(e instanceof AwsException aws)) {
|
||||
return "INTERNAL_ERROR";
|
||||
}
|
||||
String code = aws.getErrorCode() != null ? aws.getErrorCode() : "";
|
||||
if (aws.getHttpStatus() == 429 || code.contains("Throttl") || code.contains("TooManyRequests")) {
|
||||
return "THROTTLING";
|
||||
}
|
||||
if (aws.getHttpStatus() >= 500) {
|
||||
return "ERROR_FROM_TARGET";
|
||||
}
|
||||
if (aws.getHttpStatus() == 403 || code.startsWith("AccessDenied")) {
|
||||
return "NO_PERMISSIONS";
|
||||
}
|
||||
if (code.contains("NotFound") || code.contains("NonExistent") || code.contains("DoesNotExist")) {
|
||||
return "NO_RESOURCE";
|
||||
}
|
||||
return "INVALID_PARAMETER";
|
||||
}
|
||||
|
||||
private void deadLetter(Delivery delivery, Target target, String condition) {
|
||||
LOG.warnv("EventBridge rule {0} did not deliver an event to target {1}: error {2}, condition {3}, retries {4}",
|
||||
delivery.ruleArn(), target.getId(), delivery.errorCode(), condition, delivery.retryAttempts());
|
||||
String queueArn = target.getDeadLetterConfig() != null ? target.getDeadLetterConfig().arn() : null;
|
||||
if (queueArn == null) {
|
||||
return;
|
||||
}
|
||||
if (!isStandardSqsQueueArn(queueArn) || !AwsArnUtils.parse(queueArn).region().equals(delivery.region())) {
|
||||
LOG.warnv("Skipping dead-letter delivery for rule {0}: {1} is not a standard SQS queue in {2}",
|
||||
delivery.ruleArn(), queueArn, delivery.region());
|
||||
return;
|
||||
}
|
||||
Map<String, MessageAttributeValue> attributes = new LinkedHashMap<>();
|
||||
attributes.put("RULE_ARN", stringAttribute(delivery.ruleArn()));
|
||||
attributes.put("TARGET_ARN", stringAttribute(target.getArn()));
|
||||
attributes.put("ERROR_CODE", stringAttribute(delivery.errorCode()));
|
||||
attributes.put("ERROR_MESSAGE", stringAttribute(delivery.errorMessage()));
|
||||
if (condition != null) {
|
||||
attributes.put("EXHAUSTED_RETRY_CONDITION", stringAttribute(condition));
|
||||
}
|
||||
attributes.put("RETRY_ATTEMPTS", stringAttribute(String.valueOf(delivery.retryAttempts())));
|
||||
try {
|
||||
sqsService.sendMessage(AwsArnUtils.arnToQueueUrl(queueArn, baseUrl), delivery.eventJson(), 0, null, null,
|
||||
attributes, delivery.region());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EventBridge rule {0} target {1} dead-letter delivery to {2} failed: {3}",
|
||||
delivery.ruleArn(), target.getId(), queueArn, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static Instant expiresAt(Delivery delivery, Target target) {
|
||||
Target.RetryPolicy retryPolicy = target.getRetryPolicy();
|
||||
int maximumAge = retryPolicy != null && retryPolicy.maximumEventAgeInSeconds() != null
|
||||
? retryPolicy.maximumEventAgeInSeconds()
|
||||
: DEFAULT_MAXIMUM_EVENT_AGE_SECONDS;
|
||||
return delivery.firstAttemptAt().plusSeconds(maximumAge);
|
||||
}
|
||||
|
||||
private static int maximumRetryAttempts(Target target) {
|
||||
Target.RetryPolicy retryPolicy = target.getRetryPolicy();
|
||||
return retryPolicy != null && retryPolicy.maximumRetryAttempts() != null
|
||||
? retryPolicy.maximumRetryAttempts()
|
||||
: DEFAULT_MAXIMUM_RETRY_ATTEMPTS;
|
||||
}
|
||||
|
||||
private static boolean isStandardSqsQueueArn(String arn) {
|
||||
try {
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
return "sqs".equals(parsed.service())
|
||||
&& !parsed.resource().isBlank()
|
||||
&& !parsed.resource().endsWith(".fifo");
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static MessageAttributeValue stringAttribute(String value) {
|
||||
return new MessageAttributeValue(value, "String");
|
||||
}
|
||||
|
||||
private record Delivery(String ruleArn, String targetId, String eventJson, String region,
|
||||
Supplier<List<Target>> currentTargets, long generation, Instant firstAttemptAt,
|
||||
int retryAttempts, String errorCode, String errorMessage, Instant nextAttemptAt) {
|
||||
|
||||
Delivery failed(String code, String message, Instant retryAt) {
|
||||
return new Delivery(ruleArn, targetId, eventJson, region, currentTargets, generation, firstAttemptAt,
|
||||
retryAttempts, code, message, retryAt);
|
||||
}
|
||||
|
||||
Delivery nextRetry() {
|
||||
return new Delivery(ruleArn, targetId, eventJson, region, currentTargets, generation, firstAttemptAt,
|
||||
retryAttempts + 1, errorCode, errorMessage, nextAttemptAt);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@@ -15,6 +17,8 @@ public class Target {
|
||||
private SqsParameters sqsParameters;
|
||||
private BatchParameters batchParameters;
|
||||
private EcsParameters ecsParameters;
|
||||
private RetryPolicy retryPolicy;
|
||||
private DeadLetterConfig deadLetterConfig;
|
||||
|
||||
public Target() {}
|
||||
|
||||
@@ -48,4 +52,21 @@ public class Target {
|
||||
|
||||
public EcsParameters getEcsParameters() { return ecsParameters; }
|
||||
public void setEcsParameters(EcsParameters ecsParameters) { this.ecsParameters = ecsParameters; }
|
||||
|
||||
public RetryPolicy getRetryPolicy() { return retryPolicy; }
|
||||
public void setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; }
|
||||
|
||||
public DeadLetterConfig getDeadLetterConfig() { return deadLetterConfig; }
|
||||
public void setDeadLetterConfig(DeadLetterConfig deadLetterConfig) { this.deadLetterConfig = deadLetterConfig; }
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record RetryPolicy(@JsonProperty("MaximumRetryAttempts") Integer maximumRetryAttempts,
|
||||
@JsonProperty("MaximumEventAgeInSeconds") Integer maximumEventAgeInSeconds) {}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record DeadLetterConfig(@JsonProperty("Arn") String arn) {}
|
||||
}
|
||||
+6
-6
@@ -13,8 +13,8 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
|
||||
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeInvoker;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.TargetDispatcher;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -40,19 +40,19 @@ class EcsEventBridgeIntegrationTest {
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private EventBridgeService eventBridgeService;
|
||||
private EventBridgeInvoker invoker;
|
||||
private TargetDispatcher dispatcher;
|
||||
private EcsService ecsService;
|
||||
private List<String> deliveredEvents;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
deliveredEvents = new CopyOnWriteArrayList<>();
|
||||
invoker = mock(EventBridgeInvoker.class);
|
||||
dispatcher = mock(TargetDispatcher.class);
|
||||
doAnswer(invocation -> {
|
||||
String eventJson = invocation.getArgument(1);
|
||||
String eventJson = invocation.getArgument(2);
|
||||
deliveredEvents.add(eventJson);
|
||||
return null;
|
||||
}).when(invoker).invokeTarget(any(), anyString(), anyString());
|
||||
}).when(dispatcher).dispatch(anyString(), any(), anyString(), anyString(), any());
|
||||
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory();
|
||||
@@ -66,7 +66,7 @@ class EcsEventBridgeIntegrationTest {
|
||||
regionResolver,
|
||||
objectMapper,
|
||||
null,
|
||||
invoker,
|
||||
dispatcher,
|
||||
null,
|
||||
null
|
||||
);
|
||||
|
||||
+22
-2
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eventbridge;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.batch.BatchService;
|
||||
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
|
||||
@@ -117,14 +118,15 @@ class EventBridgeInvokerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_stateMachineStartFailureDoesNotEscapeDelivery() {
|
||||
void invokeTarget_stateMachineStartFailurePropagates() {
|
||||
String arn = "arn:aws:states:us-east-1:000000000000:stateMachine:missing";
|
||||
when(stepFunctionsService.startExecution(arn, null, "{}", "us-east-1"))
|
||||
.thenThrow(new IllegalStateException("missing state machine"));
|
||||
|
||||
assertDoesNotThrow(() -> invoker.invokeTarget(
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class, () -> invoker.invokeTarget(
|
||||
new Target("id1", arn, "{}", null), "{\"ignored\":true}", "us-east-1"));
|
||||
|
||||
assertEquals("missing state machine", error.getMessage());
|
||||
verify(stepFunctionsService).startExecution(arn, null, "{}", "us-east-1");
|
||||
}
|
||||
|
||||
@@ -610,6 +612,24 @@ class EventBridgeInvokerTest {
|
||||
verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetRejectionThrows() {
|
||||
when(eventBridgeService.putEvents(anyList(), anyString(), any()))
|
||||
.thenReturn(new EventBridgeService.PutEventsResult(1, List.of(Map.of(
|
||||
"ErrorCode", "InvalidArgument",
|
||||
"ErrorMessage", "EventBus not found: my-target-bus"))));
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> invoker.invokeTarget(target, "{\"source\":\"s\",\"detail\":{}}", "eu-west-1"));
|
||||
|
||||
assertEquals("InvalidArgument", error.getErrorCode());
|
||||
assertEquals("EventBus not found: my-target-bus", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithoutEventBridgeService_skipsWithoutThrowing() {
|
||||
EventBridgeInvoker bare = new EventBridgeInvoker(
|
||||
|
||||
+4
-2
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -42,7 +43,8 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
StorageBackend<String, List<Target>> targetStore = new InMemoryStorage<>();
|
||||
|
||||
EventBridgeInvoker invoker = new EventBridgeInvoker(null, null, null, new ObjectMapper(), createConfig());
|
||||
scheduler = new RuleScheduler(vertx, createConfig(), new ObjectMapper(), invoker);
|
||||
TargetDispatcher dispatcher = new TargetDispatcher(invoker, null, "http://localhost:4566", Clock.systemUTC(), null);
|
||||
scheduler = new RuleScheduler(vertx, createConfig(), new ObjectMapper(), dispatcher);
|
||||
|
||||
ReplayDispatcher replayDispatcher = new ReplayDispatcher(vertx);
|
||||
eventBridgeService = new EventBridgeService(
|
||||
@@ -50,7 +52,7 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT),
|
||||
new ObjectMapper(), scheduler, invoker, replayDispatcher,
|
||||
new ObjectMapper(), scheduler, dispatcher, replayDispatcher,
|
||||
new ResourceGroupsTaggingService(null));
|
||||
}
|
||||
|
||||
|
||||
+100
-11
@@ -23,6 +23,7 @@ import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
@@ -36,13 +37,13 @@ class EventBridgeServiceTest {
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
private EventBridgeService service;
|
||||
private EventBridgeInvoker invokerMock;
|
||||
private TargetDispatcher dispatcherMock;
|
||||
private StorageBackend<String, Replay> replayStore;
|
||||
private ReplayDispatcher replayDispatcherMock;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
invokerMock = mock(EventBridgeInvoker.class);
|
||||
dispatcherMock = mock(TargetDispatcher.class);
|
||||
replayStore = new InMemoryStorage<>();
|
||||
replayDispatcherMock = mock(ReplayDispatcher.class);
|
||||
service = new EventBridgeService(
|
||||
@@ -56,7 +57,7 @@ class EventBridgeServiceTest {
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
new ObjectMapper(),
|
||||
null,
|
||||
invokerMock,
|
||||
dispatcherMock,
|
||||
replayDispatcherMock,
|
||||
new ResourceGroupsTaggingService(null)
|
||||
);
|
||||
@@ -362,6 +363,94 @@ class EventBridgeServiceTest {
|
||||
assertEquals(1, result.successfulCount());
|
||||
assertEquals(0, result.failedCount());
|
||||
assertEquals(1, service.listTargetsByRule("my-rule", null, REGION).size());
|
||||
verify(dispatcherMock).dropPendingRetries(
|
||||
service.describeRule("my-rule", null, REGION).getArn(), List.of("t1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putTargetsStoresRetryPolicyAndDeadLetterConfig() {
|
||||
service.putRule("my-rule", null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED,
|
||||
null, null, null, REGION);
|
||||
Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue", null, null);
|
||||
target.setRetryPolicy(new Target.RetryPolicy(4, 120));
|
||||
target.setDeadLetterConfig(new Target.DeadLetterConfig("arn:aws:sqs:us-east-1:000000000000:dlq"));
|
||||
|
||||
service.putTargets("my-rule", null, List.of(target), REGION);
|
||||
|
||||
Target stored = service.listTargetsByRule("my-rule", null, REGION).getFirst();
|
||||
assertEquals(new Target.RetryPolicy(4, 120), stored.getRetryPolicy());
|
||||
assertEquals(new Target.DeadLetterConfig("arn:aws:sqs:us-east-1:000000000000:dlq"),
|
||||
stored.getDeadLetterConfig());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putTargetsRejectsRetryAttemptsAboveMaximumBeforeLookingUpTheRule() {
|
||||
Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue", null, null);
|
||||
target.setRetryPolicy(new Target.RetryPolicy(186, null));
|
||||
|
||||
assertPutTargetsValidation("1 validation error detected: Value '186' at "
|
||||
+ "'targets.1.member.retryPolicy.maximumRetryAttempts' failed to satisfy constraint: "
|
||||
+ "Member must have value less than or equal to 185", target);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putTargetsRejectsEventAgeBelowMinimumOnTheSecondTarget() {
|
||||
Target valid = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue", null, null);
|
||||
valid.setRetryPolicy(new Target.RetryPolicy(0, 60));
|
||||
Target invalid = new Target("t2", "arn:aws:sqs:us-east-1:000000000000:queue", null, null);
|
||||
invalid.setRetryPolicy(new Target.RetryPolicy(null, 59));
|
||||
|
||||
assertPutTargetsValidation("1 validation error detected: Value '59' at "
|
||||
+ "'targets.2.member.retryPolicy.maximumEventAgeInSeconds' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to 60", valid, invalid);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putTargetsRejectsEmptyDeadLetterArn() {
|
||||
Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue", null, null);
|
||||
target.setDeadLetterConfig(new Target.DeadLetterConfig(""));
|
||||
|
||||
assertPutTargetsValidation("1 validation error detected: Value '' at "
|
||||
+ "'targets.1.member.deadLetterConfig.arn' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 1", target);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putTargetsRejectsDeadLetterArnAboveMaximumLength() {
|
||||
String arn = "a".repeat(1601);
|
||||
Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue", null, null);
|
||||
target.setDeadLetterConfig(new Target.DeadLetterConfig(arn));
|
||||
|
||||
assertPutTargetsValidation("1 validation error detected: Value '" + arn + "' at "
|
||||
+ "'targets.1.member.deadLetterConfig.arn' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 1600", target);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void putEventsHandsTheDispatcherTheRuleArnAndItsCurrentTargets() {
|
||||
Rule rule = service.putRule("my-rule", null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED,
|
||||
null, null, null, REGION);
|
||||
Target first = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null);
|
||||
service.putTargets("my-rule", null, List.of(first), REGION);
|
||||
|
||||
service.putEvents(List.of(Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")), REGION);
|
||||
|
||||
ArgumentCaptor<Supplier<List<Target>>> currentTargets = ArgumentCaptor.forClass(Supplier.class);
|
||||
verify(dispatcherMock).dispatch(eq(rule.getArn()), eq(first), anyString(), eq(REGION),
|
||||
currentTargets.capture());
|
||||
Target second = new Target("t2", "arn:aws:sqs:us-east-1:000000000000:queue-2", null, null);
|
||||
service.putTargets("my-rule", null, List.of(second), REGION);
|
||||
assertEquals(List.of("t1", "t2"),
|
||||
currentTargets.getValue().get().stream().map(Target::getId).toList());
|
||||
}
|
||||
|
||||
private void assertPutTargetsValidation(String expectedMessage, Target... targets) {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.putTargets("missing-rule", null, List.of(targets), REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertEquals(expectedMessage, error.getMessage());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Pattern Matching ────────────────────────────
|
||||
@@ -467,7 +556,7 @@ class EventBridgeServiceTest {
|
||||
assertEquals(0, result.failedCount());
|
||||
assertEquals(1, result.entries().size());
|
||||
assertNotNull(result.entries().getFirst().get("EventId"));
|
||||
verify(invokerMock).invokeTarget(eq(target), any(String.class), eq(REGION));
|
||||
verify(dispatcherMock).dispatch(anyString(), eq(target), any(String.class), eq(REGION), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -488,7 +577,7 @@ class EventBridgeServiceTest {
|
||||
assertEquals(0, result.failedCount());
|
||||
assertEquals(1, result.entries().size());
|
||||
assertNotNull(result.entries().getFirst().get("EventId"));
|
||||
verify(invokerMock).invokeTarget(eq(target), any(String.class), eq(REGION));
|
||||
verify(dispatcherMock).dispatch(anyString(), eq(target), any(String.class), eq(REGION), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -509,7 +598,7 @@ class EventBridgeServiceTest {
|
||||
assertEquals(0, result.failedCount());
|
||||
assertEquals(1, result.entries().size());
|
||||
assertNotNull(result.entries().getFirst().get("EventId"));
|
||||
verify(invokerMock).invokeTarget(eq(target), any(String.class), eq(REGION));
|
||||
verify(dispatcherMock).dispatch(anyString(), eq(target), any(String.class), eq(REGION), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -745,7 +834,7 @@ class EventBridgeServiceTest {
|
||||
assertEquals(0, result.failedCount());
|
||||
|
||||
ArgumentCaptor<String> json = ArgumentCaptor.forClass(String.class);
|
||||
verify(invokerMock).invokeTarget(eq(target), json.capture(), eq("eu-west-1"));
|
||||
verify(dispatcherMock).dispatch(anyString(), eq(target), json.capture(), eq("eu-west-1"), any());
|
||||
JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue());
|
||||
assertEquals("eu-west-1", envelope.path("region").asText(),
|
||||
"envelope.region should reflect the PutEvents call's region, not the resolver default");
|
||||
@@ -773,7 +862,7 @@ class EventBridgeServiceTest {
|
||||
service.putEvents(List.of(entry), "us-west-2");
|
||||
|
||||
ArgumentCaptor<String> json = ArgumentCaptor.forClass(String.class);
|
||||
verify(invokerMock).invokeTarget(eq(target), json.capture(), eq("us-west-2"));
|
||||
verify(dispatcherMock).dispatch(anyString(), eq(target), json.capture(), eq("us-west-2"), any());
|
||||
JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue());
|
||||
assertEquals("ap-northeast-1", envelope.path("region").asText(),
|
||||
"entry.Region should win over the PutEvents call region");
|
||||
@@ -800,7 +889,7 @@ class EventBridgeServiceTest {
|
||||
Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")), "eu-west-1");
|
||||
|
||||
ArgumentCaptor<String> json = ArgumentCaptor.forClass(String.class);
|
||||
verify(invokerMock).invokeTarget(eq(target), json.capture(), eq("eu-west-1"));
|
||||
verify(dispatcherMock).dispatch(anyString(), eq(target), json.capture(), eq("eu-west-1"), any());
|
||||
JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue());
|
||||
assertEquals("eu-west-1", envelope.path("region").asText(),
|
||||
"envelope and pattern matching must agree on the entry's effective region");
|
||||
@@ -824,7 +913,7 @@ class EventBridgeServiceTest {
|
||||
service.putEvents(List.of(
|
||||
Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")), "eu-west-1");
|
||||
|
||||
verify(invokerMock, Mockito.never()).invokeTarget(eq(target), any(), any());
|
||||
verify(dispatcherMock, Mockito.never()).dispatch(any(), eq(target), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -843,7 +932,7 @@ class EventBridgeServiceTest {
|
||||
Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")), REGION);
|
||||
|
||||
ArgumentCaptor<String> json = ArgumentCaptor.forClass(String.class);
|
||||
verify(invokerMock).invokeTarget(eq(target), json.capture(), eq(REGION));
|
||||
verify(dispatcherMock).dispatch(anyString(), eq(target), json.capture(), eq(REGION), any());
|
||||
JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue());
|
||||
assertEquals(REGION, envelope.path("region").asText());
|
||||
assertEquals("000000000000", envelope.path("account").asText());
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class EventBridgeTargetRetryIntegrationTest {
|
||||
|
||||
private static final String EB_CT = "application/x-amz-json-1.1";
|
||||
private static final String SQS_CT = "application/x-amz-json-1.0";
|
||||
private static final String RULE = "eb-retry-dlq-rule";
|
||||
|
||||
private static String dlqUrl;
|
||||
private static String dlqArn;
|
||||
private static String ruleArn;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createDeadLetterQueueAndRule() {
|
||||
dlqUrl = given()
|
||||
.contentType(SQS_CT)
|
||||
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
|
||||
.body("{\"QueueName\":\"eb-retry-dlq\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("QueueUrl");
|
||||
|
||||
dlqArn = given()
|
||||
.contentType(SQS_CT)
|
||||
.header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
|
||||
.body("{\"QueueUrl\":\"" + dlqUrl + "\",\"AttributeNames\":[\"QueueArn\"]}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("Attributes.QueueArn");
|
||||
|
||||
ruleArn = given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body("""
|
||||
{
|
||||
"Name": "%s",
|
||||
"EventBusName": "default",
|
||||
"EventPattern": "{\\"source\\":[\\"test.retry\\"]}"
|
||||
}
|
||||
""".formatted(RULE))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("RuleArn");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void listTargetsByRuleEchoesRetryPolicyAndDeadLetterConfig() {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body("""
|
||||
{
|
||||
"Rule": "%s",
|
||||
"Targets": [
|
||||
{
|
||||
"Id": "WithPolicies",
|
||||
"Arn": "%s",
|
||||
"RetryPolicy": {"MaximumRetryAttempts": 4, "MaximumEventAgeInSeconds": 120},
|
||||
"DeadLetterConfig": {"Arn": "%s"}
|
||||
},
|
||||
{"Id": "Plain", "Arn": "%s"}
|
||||
]
|
||||
}
|
||||
""".formatted(RULE, dlqArn, dlqArn, dlqArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("FailedEntryCount", equalTo(0));
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.ListTargetsByRule")
|
||||
.body("{\"Rule\":\"" + RULE + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("Targets", hasSize(2))
|
||||
.body("Targets.find { it.Id == 'WithPolicies' }.RetryPolicy.MaximumRetryAttempts", equalTo(4))
|
||||
.body("Targets.find { it.Id == 'WithPolicies' }.RetryPolicy.MaximumEventAgeInSeconds", equalTo(120))
|
||||
.body("Targets.find { it.Id == 'WithPolicies' }.DeadLetterConfig.Arn", equalTo(dlqArn))
|
||||
.body("Targets.find { it.Id == 'Plain' }", not(hasKey("RetryPolicy")))
|
||||
.body("Targets.find { it.Id == 'Plain' }", not(hasKey("DeadLetterConfig")));
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.RemoveTargets")
|
||||
.body("{\"Rule\":\"" + RULE + "\",\"Ids\":[\"WithPolicies\",\"Plain\"]}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void putTargetsRejectsEventAgeBelowMinimum() {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body("""
|
||||
{
|
||||
"Rule": "%s",
|
||||
"Targets": [{
|
||||
"Id": "TooYoung",
|
||||
"Arn": "%s",
|
||||
"RetryPolicy": {"MaximumEventAgeInSeconds": 0}
|
||||
}]
|
||||
}
|
||||
""".formatted(RULE, dlqArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value '0' at "
|
||||
+ "'targets.1.member.retryPolicy.maximumEventAgeInSeconds' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to 60"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void undeliverableEventLandsInTheDeadLetterQueue() {
|
||||
String missingQueueArn = dlqArn.replace("eb-retry-dlq", "eb-retry-missing-queue");
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body("""
|
||||
{
|
||||
"Rule": "%s",
|
||||
"Targets": [{
|
||||
"Id": "MissingQueue",
|
||||
"Arn": "%s",
|
||||
"DeadLetterConfig": {"Arn": "%s"}
|
||||
}]
|
||||
}
|
||||
""".formatted(RULE, missingQueueArn, dlqArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("FailedEntryCount", equalTo(0));
|
||||
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.body("""
|
||||
{
|
||||
"Entries": [{
|
||||
"Source": "test.retry",
|
||||
"DetailType": "RetryTest",
|
||||
"Detail": "{\\"orderId\\":\\"o-7\\"}"
|
||||
}]
|
||||
}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("FailedEntryCount", equalTo(0));
|
||||
|
||||
JsonPath received = given()
|
||||
.contentType(SQS_CT)
|
||||
.header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
|
||||
.body("{\"QueueUrl\":\"" + dlqUrl + "\",\"MaxNumberOfMessages\":10,"
|
||||
+ "\"MessageAttributeNames\":[\"All\"]}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("Messages", hasSize(1))
|
||||
.body("Messages[0].MessageAttributes.RULE_ARN.StringValue", equalTo(ruleArn))
|
||||
.body("Messages[0].MessageAttributes.TARGET_ARN.StringValue", equalTo(missingQueueArn))
|
||||
.body("Messages[0].MessageAttributes.ERROR_CODE.StringValue", equalTo("NO_RESOURCE"))
|
||||
.body("Messages[0].MessageAttributes.ERROR_MESSAGE.StringValue", not(emptyOrNullString()))
|
||||
.body("Messages[0].MessageAttributes.RETRY_ATTEMPTS.StringValue", equalTo("0"))
|
||||
.body("Messages[0].MessageAttributes.RETRY_ATTEMPTS.DataType", equalTo("String"))
|
||||
.body("Messages[0].MessageAttributes", not(hasKey("EXHAUSTED_RETRY_CONDITION")))
|
||||
.extract().jsonPath();
|
||||
|
||||
JsonPath event = new JsonPath(received.getString("Messages[0].Body"));
|
||||
assertEquals("test.retry", event.getString("source"));
|
||||
assertEquals("RetryTest", event.getString("detail-type"));
|
||||
assertEquals("o-7", event.getString("detail.orderId"));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -141,7 +141,8 @@ class RuleSchedulerTest {
|
||||
}
|
||||
|
||||
private static RuleScheduler newScheduler(Vertx vertx, EventBridgeInvoker invoker) {
|
||||
return new RuleScheduler(vertx, testConfig(), new ObjectMapper(), invoker,
|
||||
TargetDispatcher dispatcher = new TargetDispatcher(invoker, null, "http://localhost:4566", Clock.systemUTC(), null);
|
||||
return new RuleScheduler(vertx, testConfig(), new ObjectMapper(), dispatcher,
|
||||
Clock.fixed(JUST_BEFORE_MINUTE_BOUNDARY, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class TargetDispatcherTest {
|
||||
|
||||
private static final Instant T0 = Instant.parse("2026-06-15T12:00:00Z");
|
||||
private static final String BASE_URL = "http://localhost:4566";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String RULE_ARN = "arn:aws:events:us-east-1:000000000000:rule/orders";
|
||||
private static final String TARGET_ARN = "arn:aws:sqs:us-east-1:000000000000:orders";
|
||||
private static final String TARGET_URL = BASE_URL + "/000000000000/orders";
|
||||
private static final String DLQ_ARN = "arn:aws:sqs:us-east-1:000000000000:orders-dlq";
|
||||
private static final String DLQ_URL = BASE_URL + "/000000000000/orders-dlq";
|
||||
private static final String EVENT = "{\"id\":\"e-1\",\"source\":\"orders\",\"detail\":{\"orderId\":\"o-1\"}}";
|
||||
|
||||
private LambdaService lambdaService;
|
||||
private SqsService sqsService;
|
||||
private AtomicReference<Instant> clockNow;
|
||||
private EventBridgeInvoker invoker;
|
||||
private Clock clock;
|
||||
private TargetDispatcher dispatcher;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaService = mock(LambdaService.class);
|
||||
sqsService = mock(SqsService.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.baseUrl()).thenReturn(BASE_URL);
|
||||
invoker = new EventBridgeInvoker(
|
||||
lambdaService, sqsService, mock(SnsService.class), new ObjectMapper(), config);
|
||||
clockNow = new AtomicReference<>(T0);
|
||||
clock = mock(Clock.class);
|
||||
when(clock.instant()).thenAnswer(invocation -> clockNow.get());
|
||||
dispatcher = new TargetDispatcher(invoker, sqsService, BASE_URL, clock, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transientRefusalIsRetriedAfterBackoffUntilAccepted() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
|
||||
.thenThrow(unavailable())
|
||||
.thenReturn(null);
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
|
||||
tickAt(T0.plusMillis(999));
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
|
||||
tickAt(T0.plusSeconds(1));
|
||||
verify(sqsService, times(2)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
|
||||
tickAt(T0.plusSeconds(3600));
|
||||
verify(sqsService, times(2)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedRetryWakesItselfUpOnTheExecutor() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
|
||||
.thenThrow(unavailable())
|
||||
.thenReturn(null);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.baseUrl()).thenReturn(BASE_URL);
|
||||
EventBridgeInvoker invoker = new EventBridgeInvoker(
|
||||
lambdaService, sqsService, mock(SnsService.class), new ObjectMapper(), config);
|
||||
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
||||
TargetDispatcher scheduled = new TargetDispatcher(invoker, sqsService, BASE_URL, Clock.systemUTC(), executor);
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
try {
|
||||
scheduled.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
|
||||
verify(sqsService, timeout(5000).times(2)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
} finally {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void retriesRunFromOnePeriodicTickRatherThanATimerEach() {
|
||||
ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
|
||||
TargetDispatcher scheduled = new TargetDispatcher(invoker, sqsService, BASE_URL, clock, executor);
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
|
||||
scheduled.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
scheduled.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
|
||||
verify(executor).scheduleWithFixedDelay(any(Runnable.class), eq(1L), eq(1L), eq(TimeUnit.SECONDS));
|
||||
verifyNoMoreInteractions(executor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exhaustedRetryAttemptsSendTheOriginalEventToTheDeadLetterQueue() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
Target target = sqsTarget(new Target.RetryPolicy(2, 3600), DLQ_ARN);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
tickAt(T0.plusSeconds(10));
|
||||
tickAt(T0.plusSeconds(20));
|
||||
tickAt(T0.plusSeconds(600));
|
||||
|
||||
verify(sqsService, times(3)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
Map<String, MessageAttributeValue> attributes = deadLetterAttributes();
|
||||
assertAttribute(attributes, "RULE_ARN", RULE_ARN);
|
||||
assertAttribute(attributes, "TARGET_ARN", TARGET_ARN);
|
||||
assertAttribute(attributes, "ERROR_CODE", "ERROR_FROM_TARGET");
|
||||
assertAttribute(attributes, "ERROR_MESSAGE", "Service is unavailable.");
|
||||
assertAttribute(attributes, "EXHAUSTED_RETRY_CONDITION", "MaximumRetryAttempts");
|
||||
assertAttribute(attributes, "RETRY_ATTEMPTS", "2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredEventAgeSendsToTheDeadLetterQueueWithoutAnotherAttempt() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
Target target = sqsTarget(new Target.RetryPolicy(185, 60), DLQ_ARN);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
tickAt(T0.plusSeconds(61));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
Map<String, MessageAttributeValue> attributes = deadLetterAttributes();
|
||||
assertAttribute(attributes, "EXHAUSTED_RETRY_CONDITION", "MaximumEventAgeInSeconds");
|
||||
assertAttribute(attributes, "RETRY_ATTEMPTS", "0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonRetryableRefusalIsDeadLetteredImmediately() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
|
||||
.thenThrow(new AwsException("AWS.SimpleQueueService.NonExistentQueue",
|
||||
"The specified queue does not exist.", 400));
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
|
||||
Map<String, MessageAttributeValue> attributes = deadLetterAttributes();
|
||||
assertAttribute(attributes, "ERROR_CODE", "NO_RESOURCE");
|
||||
assertAttribute(attributes, "ERROR_MESSAGE", "The specified queue does not exist.");
|
||||
assertAttribute(attributes, "RETRY_ATTEMPTS", "0");
|
||||
assertFalse(attributes.containsKey("EXHAUSTED_RETRY_CONDITION"));
|
||||
|
||||
tickAt(T0.plusSeconds(1));
|
||||
tickAt(T0.plusSeconds(3600));
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedDeadLetterDeliveryDoesNotEscapeOrRetry() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
|
||||
.thenThrow(new AwsException("AWS.SimpleQueueService.NonExistentQueue",
|
||||
"The specified queue does not exist.", 400));
|
||||
when(sqsService.sendMessage(eq(DLQ_URL), anyString(), anyInt(), any(), any(), anyMap(), anyString()))
|
||||
.thenThrow(new AwsException("AWS.SimpleQueueService.NonExistentQueue",
|
||||
"The specified queue does not exist.", 400));
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
|
||||
assertDoesNotThrow(() -> dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target)));
|
||||
tickAt(T0.plusSeconds(3600));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verify(sqsService, times(1)).sendMessage(eq(DLQ_URL), anyString(), anyInt(), any(), any(), anyMap(), anyString());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"arn:aws:sqs:us-east-1:000000000000:orders-dlq.fifo",
|
||||
"arn:aws:sns:us-east-1:000000000000:orders-dlq",
|
||||
"arn:aws:sqs:eu-west-1:000000000000:orders-dlq",
|
||||
" "
|
||||
})
|
||||
void unsupportedDeadLetterQueueIsSkipped(String deadLetterArn) {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION))
|
||||
.thenThrow(new AwsException("AWS.SimpleQueueService.NonExistentQueue",
|
||||
"The specified queue does not exist.", 400));
|
||||
Target target = sqsTarget(null, deadLetterArn);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryUsesTheCurrentTargetDefinition() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
Target original = sqsTarget(null, null);
|
||||
Target updated = new Target("orders-target", "arn:aws:sqs:us-east-1:000000000000:orders-v2", null, null);
|
||||
AtomicReference<List<Target>> current = new AtomicReference<>(List.of(original));
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, original, EVENT, REGION, current::get);
|
||||
current.set(List.of(updated));
|
||||
tickAt(T0.plusSeconds(1));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verify(sqsService).sendMessage(BASE_URL + "/000000000000/orders-v2", EVENT, 0, null, null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void loweredRetryLimitDeadLettersAQueuedRetryWithoutAnotherAttempt() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
Target original = sqsTarget(new Target.RetryPolicy(2, 3600), DLQ_ARN);
|
||||
AtomicReference<List<Target>> current = new AtomicReference<>(List.of(original));
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, original, EVENT, REGION, current::get);
|
||||
current.set(List.of(sqsTarget(new Target.RetryPolicy(0, 3600), DLQ_ARN)));
|
||||
tickAt(T0.plusSeconds(1));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
Map<String, MessageAttributeValue> attributes = deadLetterAttributes();
|
||||
assertAttribute(attributes, "EXHAUSTED_RETRY_CONDITION", "MaximumRetryAttempts");
|
||||
assertAttribute(attributes, "RETRY_ATTEMPTS", "0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void slowRetryDoesNotLetALaterDueRetryOutliveItsEventAge() {
|
||||
String slowUrl = BASE_URL + "/000000000000/slow";
|
||||
Target slow = new Target("slow-target", "arn:aws:sqs:us-east-1:000000000000:slow", null, null);
|
||||
Target aged = sqsTarget(new Target.RetryPolicy(185, 60), DLQ_ARN);
|
||||
when(sqsService.sendMessage(slowUrl, EVENT, 0, null, null, REGION))
|
||||
.thenThrow(unavailable())
|
||||
.thenAnswer(invocation -> {
|
||||
clockNow.set(T0.plusSeconds(100));
|
||||
return null;
|
||||
});
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, slow, EVENT, REGION, () -> List.of(slow, aged));
|
||||
clockNow.set(T0.plusMillis(500));
|
||||
dispatcher.dispatch(RULE_ARN, aged, EVENT, REGION, () -> List.of(slow, aged));
|
||||
tickAt(T0.plusSeconds(2));
|
||||
|
||||
verify(sqsService, times(2)).sendMessage(slowUrl, EVENT, 0, null, null, REGION);
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
assertAttribute(deadLetterAttributes(), "EXHAUSTED_RETRY_CONDITION", "MaximumEventAgeInSeconds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearDuringATickStopsTheRemainingRetries() {
|
||||
String firstUrl = BASE_URL + "/000000000000/first";
|
||||
Target first = new Target("first-target", "arn:aws:sqs:us-east-1:000000000000:first", null, null);
|
||||
Target second = sqsTarget(null, DLQ_ARN);
|
||||
when(sqsService.sendMessage(firstUrl, EVENT, 0, null, null, REGION))
|
||||
.thenThrow(unavailable())
|
||||
.thenAnswer(invocation -> {
|
||||
dispatcher.clear();
|
||||
return null;
|
||||
});
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, first, EVENT, REGION, () -> List.of(first, second));
|
||||
clockNow.set(T0.plusMillis(500));
|
||||
dispatcher.dispatch(RULE_ARN, second, EVENT, REGION, () -> List.of(first, second));
|
||||
tickAt(T0.plusSeconds(2));
|
||||
|
||||
verify(sqsService, times(2)).sendMessage(firstUrl, EVENT, 0, null, null, REGION);
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void removedTargetsPendingRetriesAreDroppedEvenIfItsIdReturns() {
|
||||
String otherUrl = BASE_URL + "/000000000000/other";
|
||||
Target removed = sqsTarget(null, DLQ_ARN);
|
||||
Target kept = new Target("other-target", "arn:aws:sqs:us-east-1:000000000000:other", null, null);
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
when(sqsService.sendMessage(otherUrl, EVENT, 0, null, null, REGION)).thenThrow(unavailable()).thenReturn(null);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, removed, EVENT, REGION, () -> List.of(removed, kept));
|
||||
dispatcher.dispatch(RULE_ARN, kept, EVENT, REGION, () -> List.of(removed, kept));
|
||||
dispatcher.dropPendingRetries(RULE_ARN, List.of("orders-target"));
|
||||
tickAt(T0.plusSeconds(1));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verify(sqsService, times(2)).sendMessage(otherUrl, EVENT, 0, null, null, REGION);
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryIsDroppedWhenTheTargetWasRemoved() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
AtomicReference<List<Target>> current = new AtomicReference<>(List.of(target));
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, current::get);
|
||||
current.set(List.of());
|
||||
tickAt(T0.plusSeconds(1));
|
||||
tickAt(T0.plusSeconds(3600));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void retriesStayWithinTheirOwnAccountAndRegion() {
|
||||
String ruleA = "arn:aws:events:us-east-1:111111111111:rule/orders";
|
||||
String ruleB = "arn:aws:events:eu-west-1:222222222222:rule/orders";
|
||||
String urlA = BASE_URL + "/111111111111/orders";
|
||||
String urlB = BASE_URL + "/222222222222/orders";
|
||||
Target targetA = new Target("orders-target", "arn:aws:sqs:us-east-1:111111111111:orders", null, null);
|
||||
Target targetB = new Target("orders-target", "arn:aws:sqs:eu-west-1:222222222222:orders", null, null);
|
||||
when(sqsService.sendMessage(urlA, EVENT, 0, null, null, "us-east-1"))
|
||||
.thenThrow(unavailable())
|
||||
.thenReturn(null);
|
||||
when(sqsService.sendMessage(urlB, EVENT, 0, null, null, "eu-west-1"))
|
||||
.thenThrow(unavailable())
|
||||
.thenReturn(null);
|
||||
|
||||
dispatcher.dispatch(ruleA, targetA, EVENT, "us-east-1", () -> List.of(targetA));
|
||||
dispatcher.dispatch(ruleB, targetB, EVENT, "eu-west-1", () -> List.of(targetB));
|
||||
tickAt(T0.plusSeconds(1));
|
||||
|
||||
verify(sqsService, times(2)).sendMessage(urlA, EVENT, 0, null, null, "us-east-1");
|
||||
verify(sqsService, times(2)).sendMessage(urlB, EVENT, 0, null, null, "eu-west-1");
|
||||
verify(sqsService, never()).sendMessage(urlA, EVENT, 0, null, null, "eu-west-1");
|
||||
verify(sqsService, never()).sendMessage(urlB, EVENT, 0, null, null, "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptedLambdaInvocationIsNotRetried() {
|
||||
String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:f";
|
||||
Target target = new Target("fn-target", functionArn, null, null);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
tickAt(T0.plusSeconds(1));
|
||||
tickAt(T0.plusSeconds(3600));
|
||||
|
||||
verify(lambdaService, times(1)).invokeArn(eq(functionArn), any(), eq(InvocationType.Event));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearDropsPendingRetries() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenThrow(unavailable());
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
dispatcher.clear();
|
||||
tickAt(T0.plusSeconds(3600));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void attemptFailingAfterAResetIsNeitherRetriedNorDeadLettered() {
|
||||
when(sqsService.sendMessage(TARGET_URL, EVENT, 0, null, null, REGION)).thenAnswer(invocation -> {
|
||||
dispatcher.clear();
|
||||
throw unavailable();
|
||||
});
|
||||
Target target = sqsTarget(null, DLQ_ARN);
|
||||
|
||||
dispatcher.dispatch(RULE_ARN, target, EVENT, REGION, () -> List.of(target));
|
||||
tickAt(T0.plusSeconds(3600));
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(TARGET_URL, EVENT, 0, null, null, REGION);
|
||||
verifyNoDeadLetter();
|
||||
}
|
||||
|
||||
private void tickAt(Instant now) {
|
||||
clockNow.set(now);
|
||||
dispatcher.tick();
|
||||
}
|
||||
|
||||
private static Target sqsTarget(Target.RetryPolicy retryPolicy, String deadLetterArn) {
|
||||
Target target = new Target("orders-target", TARGET_ARN, null, null);
|
||||
target.setRetryPolicy(retryPolicy);
|
||||
if (deadLetterArn != null) {
|
||||
target.setDeadLetterConfig(new Target.DeadLetterConfig(deadLetterArn));
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private static AwsException unavailable() {
|
||||
return new AwsException("ServiceUnavailable", "Service is unavailable.", 503);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, MessageAttributeValue> deadLetterAttributes() {
|
||||
ArgumentCaptor<Map<String, MessageAttributeValue>> attributes = ArgumentCaptor.forClass(Map.class);
|
||||
verify(sqsService, times(1)).sendMessage(
|
||||
eq(DLQ_URL), eq(EVENT), eq(0), isNull(), isNull(), attributes.capture(), eq(REGION));
|
||||
return attributes.getValue();
|
||||
}
|
||||
|
||||
private void verifyNoDeadLetter() {
|
||||
verify(sqsService, never()).sendMessage(anyString(), anyString(), anyInt(), any(), any(), anyMap(), anyString());
|
||||
}
|
||||
|
||||
private static void assertAttribute(Map<String, MessageAttributeValue> attributes, String name, String value) {
|
||||
MessageAttributeValue attribute = attributes.get(name);
|
||||
assertNotNull(attribute, name);
|
||||
assertEquals(value, attribute.getStringValue(), name);
|
||||
assertEquals("String", attribute.getDataType(), name);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user