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:
Mario Toffia authored and GitHub committed 2026-10-01 07:59:18 -04:00
1 parent 4716ac9992
commit 0a54d0708e
15 files changed
+1221 -46

No files matched your search

@@ -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
);
@@ -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(
@@ -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));
}
@@ -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());
@@ -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"));
}
}
@@ -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));
}
@@ -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);
}
}