mirror of
https://github.com/floci-io/floci.git
synced 2026-11-29 00:21:51 -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
@@ -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) {}
|
||||
}
|
||||
Reference in new issue
Block a user