Light, fluffy, and always free - The AWS Local Emulator alternative
fix(eventbridge): answer PutEvents to a missing event bus as AWS does (#6748)
Priamo Germosen32cbf73adc9e
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EventBridgeTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EventBridgeTest.javaindex 22cc38dd3c..648460ad5a 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EventBridgeTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EventBridgeTest.java@@ -235,6 +235,24 @@ class EventBridgeTest {}}+ @Test+ @Order(26)+ void putEventsToAnEventBusThatDoesNotExistIsAnsweredAsPublished() {+ PutEventsResponse response = eb.putEvents(PutEventsRequest.builder()+ .entries(PutEventsRequestEntry.builder()+ .eventBusName(TestFixtures.uniqueName("eb-missing-bus"))+ .source("com.myapp")+ .detailType("OrderPlaced")+ .detail("{}")+ .build())+ .build());++ assertThat(response.failedEntryCount()).isZero();+ assertThat(response.entries()).hasSize(1);+ assertThat(response.entries().get(0).eventId()).isNotBlank();+ assertThat(response.entries().get(0).errorCode()).isNull();+ }+// ──────────────────────────── InputTransformer ────────────────────────────@Testdiff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.mdindex 4ecdc74635..4a3a76d6e5 100644--- a/docs/services/eventbridge.md+++ b/docs/services/eventbridge.md@@ -243,6 +243,7 @@ aws events put-targets \## Current Behavior- `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 `PutEvents` entry for an event bus that does not exist is answered as AWS answers it: with an event id, not counted in `FailedEntryCount`, and dropped, as no rule matches it. Floci logs the drop at `INFO`. Floci's own deliveries to a bus, for a rule, a pipe or a schedule, are unchanged: an entry for a bus that does not exist fails there.- 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.diff --git a/docs/services/step-functions.md b/docs/services/step-functions.mdindex 9761105b2e..67687d6539 100644--- a/docs/services/step-functions.md+++ b/docs/services/step-functions.md@@ -646,15 +646,15 @@ fails the task with `SNS.NotFoundException` and a missing `Message` withcause is the response serialized as a string, so a `Catch` can read which entry was rejected:```json-{"FailedEntryCount":1,"Entries":[{"EventId":"08cbdc46-…"},{"ErrorCode":"InvalidArgument","ErrorMessage":"EventBus not found: no-such-bus"}]}+{"FailedEntryCount":1,"Entries":[{"EventId":"08cbdc46-…"},{"ErrorCode":"InvalidArgument","ErrorMessage":"Parameter Source is not valid. Reason: Source is a required argument."}]}```The optimized integration accepts `Detail` as a JSON object in JSONPath and JSONata workflows. Itserializes that object once for the EventBridge request, preserving nested values and escaped text.The direct EventBridge API continues to accept its native string-valued `Detail` field.-One deviation, and it belongs to EventBridge rather than to the integration: Floci rejects an entry-addressed to an event bus that does not exist, while AWS accepts it and returns an `EventId`.+An entry addressed to an event bus that does not exist is accepted with an `EventId`, as in AWS, and+dropped, so it does not fail the task.## JSONata expressions are validated when the state machine is createddiff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.javaindex 92e89bde10..25eec17021 100644--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java@@ -393,7 +393,7 @@ public class EventBridgeHandler {entries.add(entry);}}- EventBridgeService.PutEventsResult result = eventBridgeService.putEvents(entries, region);+ EventBridgeService.PutEventsResult result = eventBridgeService.putEventsFromRequest(entries, region);ObjectNode response = objectMapper.createObjectNode();response.put("FailedEntryCount", result.failedCount());ArrayNode resultEntries = response.putArray("Entries");diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.javaindex d2b5be84d7..73228f6291 100644--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java@@ -916,6 +916,25 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns* {@code null} whenever the target is in the caller's own account.*/public PutEventsResult putEvents(List<Map<String, Object>> entries, String region, String accountId) {+ return putEvents(entries, region, accountId, false);+ }++ /**+ * Publishes the entries of a {@code PutEvents} request. As {@link #putEvents(List, String)}, except that+ * an entry for an event bus that does not exist is answered as published, with an event id and not+ * counted as failed, and goes no further, as the EventBridge User Guide gives it: "If you use PutEvents+ * to publish an event to an event bus that does not exist, EventBridge event matching will not find a+ * corresponding rule and will drop the event. Although EventBridge will send a 200 response, it will not+ * fail the request or include the event in the FailedEntryCount value of the request response." Floci's+ * own deliveries to a bus, for a rule, a pipe or a schedule, go through {@link #putEvents} and still fail+ * such an entry: the guide's sentence is about the action, and no document says how AWS answers them.+ */+ public PutEventsResult putEventsFromRequest(List<Map<String, Object>> entries, String region) {+ return putEvents(entries, region, null, true);+ }++ private PutEventsResult putEvents(List<Map<String, Object>> entries, String region, String accountId,+ boolean dropForMissingBus) {int failed = 0;List<Map<String, String>> resultEntries = new ArrayList<>();@@ -969,6 +988,12 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArnsif ("default".equals(effectiveBus)) {getOrCreateDefaultBus(region);} else if (accountGet(busStore, accountId, busStoreKey).isEmpty()) {+ if (dropForMissingBus) {+ LOG.infov("PutEvents dropped an event for event bus {0}, which does not exist in {1}",+ effectiveBus, region);+ resultEntries.add(Map.of("EventId", UUID.randomUUID().toString()));+ continue;+ }failed++;Map<String, String> errorEntry = new HashMap<>();errorEntry.put("ErrorCode", "InvalidArgument");diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeIntegrationTest.javaindex d60bcc654c..030d9701e4 100644--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeIntegrationTest.java@@ -9,6 +9,7 @@ import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.hasSize;import static org.hamcrest.Matchers.matchesPattern;import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;@QuarkusTest@TestMethodOrder(MethodOrderer.OrderAnnotation.class)@@ -293,4 +294,29 @@ class EventBridgeIntegrationTest {.body("__type", equalTo("ResourceNotFoundException"));}}++ @Test+ @Order(10)+ void putEventsToAnEventBusThatDoesNotExistIsAnsweredAsPublished() {+ given()+ .contentType(EVENT_BRIDGE_CONTENT_TYPE)+ .header("X-Amz-Target", "AWSEvents.PutEvents")+ .body("""+ {+ "Entries": [+ {"Source": "com.mycompany.myapp", "DetailType": "t", "Detail": "{}",+ "EventBusName": "eb-integration-missing-bus"},+ {"Source": "com.mycompany.myapp", "DetailType": "t", "Detail": "{",+ "EventBusName": "eb-integration-missing-bus"}+ ]+ }+ """)+ .when().post("/")+ .then().statusCode(200)+ .body("FailedEntryCount", equalTo(1))+ .body("Entries", hasSize(2))+ .body("Entries[0].EventId", notNullValue())+ .body("Entries[0].ErrorCode", nullValue())+ .body("Entries[1].ErrorCode", equalTo("MalformedDetail"));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.javaindex 28a7cf3f96..3b64e68ad0 100644--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java@@ -1027,6 +1027,37 @@ class EventBridgeServiceTest {assertEquals(1, result.failedCount());}+ /**+ * A request's entry for an event bus that does not exist is answered as published and dropped: it gets an+ * event id, is not counted as failed and reaches no rule, the default bus's included. An entry that is not+ * valid still fails, whatever bus it names.+ */+ @Test+ void aRequestsEntryForANonExistentBusIsAnsweredAsPublishedAndDropped() {+ service.putRule("on-my-app", null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED,+ null, null, null, REGION);+ Target target = new Target();+ target.setId("t1");+ target.setArn("arn:aws:sqs:us-east-1:000000000000:queue-1");+ service.putTargets("on-my-app", null, List.of(target), REGION);++ EventBridgeService.PutEventsResult result = service.putEventsFromRequest(List.of(+ Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}", "EventBusName", "non-existent-bus"),+ Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}"),+ Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{", "EventBusName", "non-existent-bus")),+ REGION);++ assertEquals(1, result.failedCount());+ assertEquals(3, result.entries().size());+ assertNotNull(result.entries().get(0).get("EventId"));+ assertNull(result.entries().get(0).get("ErrorCode"));+ assertNotNull(result.entries().get(1).get("EventId"));+ assertEquals("MalformedDetail", result.entries().get(2).get("ErrorCode"));+ verify(dispatcherMock).dispatch(anyString(), any(Target.class),+ contains("\"event-bus-name\":\"default\""), anyString(), any());+ verify(dispatcherMock).dispatch(anyString(), any(Target.class), anyString(), anyString(), any());+ }+@Testvoid putEventsShouldInvokeLambdaTarget() {service.putRule("my-rule", null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED,diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPutEventsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPutEventsIntegrationTest.javaindex cd5e6a2255..7dc7474beb 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPutEventsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPutEventsIntegrationTest.java@@ -203,8 +203,7 @@ class StepFunctionsPutEventsIntegrationTest {"Arguments": {"Entries": [{"Source": "floci.unrouted", "DetailType": "t", "Detail": "{}"},- {"EventBusName": "no-such-bus", "Source": "floci.unrouted",- "DetailType": "t", "Detail": "{}"}+ {"DetailType": "t", "Detail": "{}"}]},"End": true@@ -236,8 +235,7 @@ class StepFunctionsPutEventsIntegrationTest {"Type": "Task","Resource": "RESOURCE_ARN","Arguments": {- "Entries": [{"EventBusName": "no-such-bus", "Source": "floci.unrouted",- "DetailType": "t", "Detail": "{}"}]+ "Entries": [{"DetailType": "t", "Detail": "{}"}]},"Catch": [{"ErrorEquals": ["EventBridge.FailedEntry"], "Next": "Recovered"}],"End": true@@ -254,6 +252,32 @@ class StepFunctionsPutEventsIntegrationTest {assertTrue(mapper.readTree(succeedingOutputOf(smArn)).path("recovered").asBoolean());}+ @Test+ @Order(7)+ void anEntryForAnEventBusThatDoesNotExistIsAcceptedAndDoesNotFailTheTask() throws Exception {+ String smArn = createStateMachine("put-events-missing-bus", """+ {+ "QueryLanguage": "JSONata",+ "StartAt": "Publish",+ "States": {+ "Publish": {+ "Type": "Task",+ "Resource": "RESOURCE_ARN",+ "Arguments": {+ "Entries": [{"EventBusName": "no-such-bus", "Source": "floci.unrouted",+ "DetailType": "t", "Detail": "{}"}]+ },+ "End": true+ }+ }+ }+ """.replace("RESOURCE_ARN", RESOURCE));++ JsonNode result = mapper.readTree(succeedingOutputOf(smArn));+ assertEquals(0, result.path("FailedEntryCount").asInt());+ assertFalse(result.path("Entries").get(0).path("EventId").asText().isBlank());+ }+private static List<String> fieldNames(JsonNode node) {ArrayList<String> names = new ArrayList<>();node.fieldNames().forEachRemaining(names::add);