Light, fluffy, and always free - The AWS Local Emulator alternative
fix(eventbridge): page ListRules with Limit and NextToken (#6223)
Mohith007ac9268e01
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 0c926ca2b3..22cc38dd3c 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@@ -7,6 +7,7 @@ import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundExceptiimport software.amazon.awssdk.services.sqs.SqsClient;import software.amazon.awssdk.services.sqs.model.*;+import java.util.ArrayList;import java.util.List;import java.util.Map;@@ -381,6 +382,61 @@ class EventBridgeTest {});}+ @Test+ @Order(37)+ void listRulesPagesWithLimitAndNextToken() {+ String prefix = TestFixtures.uniqueName("eb-page") + "-";+ List<String> names = List.of(prefix + "a", prefix + "b", prefix + "c");+ try {+ for (String name : names) {+ eb.putRule(PutRuleRequest.builder()+ .name(name)+ .eventBusName(busName)+ .eventPattern("{\"source\":[\"paging\"]}")+ .build());+ }++ List<String> seen = new ArrayList<>();+ String token = null;+ do {+ ListRulesResponse page = eb.listRules(ListRulesRequest.builder()+ .eventBusName(busName)+ .namePrefix(prefix)+ .limit(1)+ .nextToken(token)+ .build());+ assertThat(page.rules()).hasSize(1);+ seen.add(page.rules().get(0).name());+ token = page.nextToken();+ } while (token != null);++ assertThat(seen).containsExactlyElementsOf(names);+ } finally {+ for (String name : names) {+ try {+ eb.deleteRule(DeleteRuleRequest.builder().name(name).eventBusName(busName).build());+ } catch (ResourceNotFoundException ignored) {+ // The rule was never created because an earlier putRule failed; nothing to clean up.+ }+ }+ }+ }++ @Test+ @Order(38)+ void listRulesRejectsOutOfRangeLimitAndUnknownToken() {+ assertThatThrownBy(() -> eb.listRules(ListRulesRequest.builder().limit(101).build()))+ .isInstanceOfSatisfying(EventBridgeException.class, e -> {+ assertThat(e.statusCode()).isEqualTo(400);+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationException");+ });+ assertThatThrownBy(() -> eb.listRules(ListRulesRequest.builder().limit(1).nextToken("not-a-token!").build()))+ .isInstanceOfSatisfying(EventBridgeException.class, e -> {+ assertThat(e.statusCode()).isEqualTo(400);+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidToken");+ });+ }+// ──────────────────────────── Tags ────────────────────────────@Testdiff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.mdindex 9ac4e3ec2d..5ccba35503 100644--- a/docs/services/eventbridge.md+++ b/docs/services/eventbridge.md@@ -16,7 +16,7 @@| `PutRule` | Create or update a rule with a schedule or event pattern || `DeleteRule` | Delete a rule || `DescribeRule` | Get rule details |-| `ListRules` | List rules |+| `ListRules` | List rules, paged by `Limit` (1 to 100, default 100) and `NextToken` || `EnableRule` | Enable a disabled rule || `DisableRule` | Disable a rule || `PutTargets` | Add targets to a rule |diff --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 cd051af87e..a9f28cd1c0 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@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsErrorResponse;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsJson11Controller;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination;import io.github.hectorvent.floci.services.eventbridge.model.Archive;import io.github.hectorvent.floci.services.eventbridge.model.ArchiveState;@@ -193,15 +194,39 @@ public class EventBridgeHandler {private Response handleListRules(JsonNode request, String region) {String busName = request.path("EventBusName").asText(null);String namePrefix = request.path("NamePrefix").asText(null);- List<Rule> rules = eventBridgeService.listRules(busName, namePrefix, region);+ Integer limit = readLimit(request.path("Limit"));+ String nextToken = request.path("NextToken").asText(null);+ PaginatedResult<Rule> page = eventBridgeService.listRules(busName, namePrefix, limit, nextToken, region);ObjectNode response = objectMapper.createObjectNode();ArrayNode rulesArray = response.putArray("Rules");- for (Rule rule : rules) {+ for (Rule rule : page.items()) {rulesArray.add(buildRuleNode(rule));}+ if (page.nextToken() != null) {+ response.put("NextToken", page.nextToken());+ }return Response.ok(response).build();}+ /**+ * Reads an integer {@code Limit} without coercion: a string, boolean or fractional value is+ * a SerializationException, and an integral value wider than an int fails the range check+ * instead of being truncated into it.+ */+ private static Integer readLimit(JsonNode limit) {+ if (limit.isMissingNode() || limit.isNull()) {+ return null;+ }+ if (!limit.isIntegralNumber()) {+ throw new AwsException("SerializationException",+ "'" + limit.asText() + "' can not be converted to Integer", 400);+ }+ if (!limit.canConvertToInt()) {+ throw EventBridgeService.limitOutOfRange(limit.asText(), limit.bigIntegerValue().signum() < 0);+ }+ return limit.intValue();+ }+private Response handleEnableRule(JsonNode request, String region) {String name = request.path("Name").asText(null);String busName = request.path("EventBusName").asText(null);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 eb13cb1dab..ea316f1bd5 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@@ -13,6 +13,8 @@ import com.fasterxml.jackson.databind.node.TextNode;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.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pagination;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.SmithyValidationErrors;import io.github.hectorvent.floci.core.resource.ExplorerResource;@@ -58,6 +60,7 @@ import java.util.regex.Pattern;public class EventBridgeService implements ResourceProvider {private static final Logger LOG = Logger.getLogger(EventBridgeService.class);+ private static final int MAX_LIST_LIMIT = 100;private static final List<String> REQUIRED_ENTRY_FIELDS = List.of("Source", "DetailType", "Detail");private final StorageBackend<String, EventBus> busStore;@@ -399,6 +402,29 @@ public class EventBridgeService implements ResourceProvider {});}+ /**+ * One page of a bus's rules in name order. {@code limit} defaults to 100, the documented+ * per-page maximum, and the token is the shared opaque cursor, so a page stays resumable+ * when rules are added or removed between requests.+ */+ public PaginatedResult<Rule> listRules(String busName, String namePrefix, Integer limit,+ String nextToken, String region) {+ if (limit != null && (limit < 1 || limit > MAX_LIST_LIMIT)) {+ throw limitOutOfRange(limit.toString(), limit < 1);+ }+ return Pagination.paginate(listRules(busName, namePrefix, region), Rule::getName,+ limit != null ? limit : MAX_LIST_LIMIT, nextToken, "rule",+ token -> new AwsException("InvalidToken", "Invalid NextToken: " + token, 400));+ }++ static AwsException limitOutOfRange(String value, boolean belowMinimum) {+ String constraint = belowMinimum+ ? "Member must have value greater than or equal to 1"+ : "Member must have value less than or equal to " + MAX_LIST_LIMIT;+ return SmithyValidationErrors.validationException(+ "Value '" + value + "' at 'limit' failed to satisfy constraint: " + constraint);+ }+public void enableRule(String name, String busName, String region) {String effectiveBus = resolvedBusName(busName);String key = ruleKey(region, effectiveBus, name);diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeListRulesPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeListRulesPaginationIntegrationTest.javanew file mode 100644index 0000000000..ddbaf906d3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeListRulesPaginationIntegrationTest.java@@ -0,0 +1,145 @@+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.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import java.util.ArrayList;+import java.util.List;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;+import static org.junit.jupiter.api.Assertions.assertEquals;++@QuarkusTest+class EventBridgeListRulesPaginationIntegrationTest {++ private static final String CT = "application/x-amz-json-1.1";++ @BeforeAll+ static void configure() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ private static void call(String action, String body) {+ given().contentType(CT).header("X-Amz-Target", "AWSEvents." + action)+ .body(body)+ .when().post("/")+ .then().statusCode(200);+ }++ private static void putRule(String name, String bus) {+ String busField = bus == null ? "" : ",\"EventBusName\":\"" + bus + "\"";+ call("PutRule", "{\"Name\":\"" + name + "\",\"EventPattern\":\"{\\\"source\\\":[\\\"paging\\\"]}\""+ + busField + "}");+ }++ private static JsonPath listRules(String body) {+ return given().contentType(CT).header("X-Amz-Target", "AWSEvents.ListRules")+ .body(body)+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath();+ }++ @Test+ void limitOnePagesThroughEveryRuleExactlyOnce() {+ putRule("lr-page-c", null);+ putRule("lr-page-a", null);+ putRule("lr-page-b", null);+ putRule("lr-other", null);++ List<String> seen = new ArrayList<>();+ String token = null;+ do {+ String tokenField = token == null ? "" : ",\"NextToken\":\"" + token + "\"";+ JsonPath page = listRules("{\"NamePrefix\":\"lr-page-\",\"Limit\":1" + tokenField + "}");+ List<String> names = page.getList("Rules.Name");+ assertEquals(1, names.size());+ seen.add(names.get(0));+ token = page.getString("NextToken");+ } while (token != null);++ assertEquals(List.of("lr-page-a", "lr-page-b", "lr-page-c"), seen);+ }++ @Test+ void customBusAndPrefixPageTogether() {+ call("CreateEventBus", "{\"Name\":\"lr-paging-bus\"}");+ putRule("lr-bus-1", "lr-paging-bus");+ putRule("lr-bus-2", "lr-paging-bus");+ putRule("lr-bus-skip", "lr-paging-bus");+ putRule("lr-bus-3", null);++ String token = given().contentType(CT).header("X-Amz-Target", "AWSEvents.ListRules")+ .body("{\"EventBusName\":\"lr-paging-bus\",\"NamePrefix\":\"lr-bus-\",\"Limit\":2}")+ .when().post("/")+ .then().statusCode(200)+ .body("Rules", hasSize(2))+ .body("Rules[0].Name", equalTo("lr-bus-1"))+ .body("Rules[1].Name", equalTo("lr-bus-2"))+ .body("NextToken", notNullValue())+ .extract().jsonPath().getString("NextToken");++ given().contentType(CT).header("X-Amz-Target", "AWSEvents.ListRules")+ .body("{\"EventBusName\":\"lr-paging-bus\",\"NamePrefix\":\"lr-bus-\",\"Limit\":2,"+ + "\"NextToken\":\"" + token + "\"}")+ .when().post("/")+ .then().statusCode(200)+ .body("Rules", hasSize(1))+ .body("Rules[0].Name", equalTo("lr-bus-skip"))+ .body("NextToken", nullValue());+ }++ @ParameterizedTest+ @ValueSource(strings = {"0", "101", "4294967297", "-4294967297"})+ void outOfRangeLimitIsAValidationException(String limit) {+ given().contentType(CT).header("X-Amz-Target", "AWSEvents.ListRules")+ .body("{\"Limit\":" + limit + "}")+ .when().post("/")+ .then().statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", containsString("Value '" + limit + "' at 'limit' failed to satisfy constraint"));+ }++ @ParameterizedTest+ @ValueSource(strings = {"100.9", "true", "\"5\""})+ void nonIntegerLimitIsASerializationException(String limit) {+ given().contentType(CT).header("X-Amz-Target", "AWSEvents.ListRules")+ .body("{\"Limit\":" + limit + "}")+ .when().post("/")+ .then().statusCode(400)+ .body("__type", equalTo("SerializationException"))+ .body("message", containsString("can not be converted to Integer"));+ }++ @ParameterizedTest+ @ValueSource(ints = {1, 100})+ void boundaryLimitsAreAccepted(int limit) {+ putRule("lr-bound-a", null);+ putRule("lr-bound-b", null);++ given().contentType(CT).header("X-Amz-Target", "AWSEvents.ListRules")+ .body("{\"NamePrefix\":\"lr-bound-\",\"Limit\":" + limit + "}")+ .when().post("/")+ .then().statusCode(200)+ .body("Rules", hasSize(Math.min(limit, 2)));+ }++ @Test+ void unknownNextTokenIsInvalidToken() {+ given().contentType(CT).header("X-Amz-Target", "AWSEvents.ListRules")+ .body("{\"Limit\":1,\"NextToken\":\"not-a-token!\"}")+ .when().post("/")+ .then().statusCode(400)+ .body("__type", equalTo("InvalidToken"));+ }+}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 98fdc85d0e..44b5129fd0 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@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.core.storage.StorageBackend;@@ -29,6 +30,7 @@ import org.junit.jupiter.params.provider.ValueSource;import org.mockito.ArgumentCaptor;import org.mockito.Mockito;+import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.function.Supplier;@@ -445,6 +447,79 @@ class EventBridgeServiceTest {assertEquals(2, result.size());}+ @Test+ void listRulesPagesEachRuleExactlyOnceInNameOrder() {+ for (String name : List.of("page-c", "page-a", "page-d", "page-b", "other")) {+ service.putRule(name, null, null, "rate(1 minute)", RuleState.ENABLED,+ null, null, null, REGION);+ }++ List<String> seen = new ArrayList<>();+ String token = null;+ int pages = 0;+ do {+ PaginatedResult<Rule> page = service.listRules(null, "page-", 1, token, REGION);+ assertEquals(1, page.items().size());+ seen.add(page.items().get(0).getName());+ token = page.nextToken();+ pages++;+ } while (token != null);++ assertEquals(List.of("page-a", "page-b", "page-c", "page-d"), seen);+ assertEquals(4, pages);+ }++ @Test+ void listRulesOmitsNextTokenWhenEverythingFits() {+ service.putRule("fit-a", null, null, "rate(1 minute)", RuleState.ENABLED, null, null, null, REGION);+ service.putRule("fit-b", null, null, "rate(1 minute)", RuleState.ENABLED, null, null, null, REGION);++ PaginatedResult<Rule> exact = service.listRules(null, null, 2, null, REGION);+ assertEquals(2, exact.items().size());+ assertNull(exact.nextToken());++ PaginatedResult<Rule> unbounded = service.listRules(null, null, null, null, REGION);+ assertEquals(2, unbounded.items().size());+ assertNull(unbounded.nextToken());+ }++ @Test+ void listRulesPagesOnACustomBusWithoutLeakingDefaultBusRules() {+ service.createEventBus("paging-bus", null, null, REGION);+ service.putRule("custom-1", "paging-bus", null, "rate(1 minute)", RuleState.ENABLED,+ null, null, null, REGION);+ service.putRule("custom-2", "paging-bus", null, "rate(1 minute)", RuleState.ENABLED,+ null, null, null, REGION);+ service.putRule("custom-3", null, null, "rate(1 minute)", RuleState.ENABLED,+ null, null, null, REGION);++ PaginatedResult<Rule> first = service.listRules("paging-bus", "custom-", 1, null, REGION);+ assertEquals("custom-1", first.items().get(0).getName());+ assertNotNull(first.nextToken());++ PaginatedResult<Rule> second = service.listRules("paging-bus", "custom-", 1, first.nextToken(), REGION);+ assertEquals("custom-2", second.items().get(0).getName());+ assertNull(second.nextToken());+ }++ @ParameterizedTest+ @ValueSource(ints = {0, -1, 101})+ void listRulesRejectsOutOfRangeLimit(int limit) {+ AwsException ex = assertThrows(AwsException.class,+ () -> service.listRules(null, null, limit, null, REGION));+ assertEquals("ValidationException", ex.getErrorCode());+ assertTrue(ex.getMessage().contains("'" + limit + "' at 'limit'"), ex.getMessage());+ }++ @ParameterizedTest+ @ValueSource(strings = {"not base64 !", "Zm9vOmJhcg"})+ void listRulesRejectsATokenItDidNotMint(String token) {+ AwsException ex = assertThrows(AwsException.class,+ () -> service.listRules(null, null, 1, token, REGION));+ assertEquals("InvalidToken", ex.getErrorCode());+ assertEquals(400, ex.getHttpStatus());+ }+// ──────────────────────────── Targets ────────────────────────────@Test