diff --git a/docs/services/sqs.md b/docs/services/sqs.md index 8c949bb5d1..3e667fc439 100644 --- a/docs/services/sqs.md +++ b/docs/services/sqs.md @@ -84,6 +84,11 @@ curl -X DELETE "http://localhost:4566/_aws/sqs/messages?QueueUrl=$QUEUE_URL" `ReceiveMessage` waits up to `WaitTimeSeconds` (0 to 20) for a message to arrive and returns as soon as one is available. Values outside that range are rejected with `InvalidParameterValue`. When the request omits `WaitTimeSeconds`, the queue's `ReceiveMessageWaitTimeSeconds` attribute applies (default `0`, short polling), matching AWS. +`MaxNumberOfMessages` defaults to 1 and must be an integer from 1 to 10. +Out-of-range, malformed, and overflowing values return `InvalidParameterValue` +without receiving a message or changing its receive count or visibility. Both +the JSON and Query protocols enforce this limit. + ```bash # Enable long polling for every consumer of the queue aws sqs set-queue-attributes \ diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java index d71e81a461..09f28f7251 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java @@ -198,7 +198,7 @@ public class SqsEventSourcePoller implements Resettable { int wanted = Math.max(1, esm.getBatchSize() - alreadyBuffered); List received = sqsService.receiveMessage( - esm.getQueueUrl(), wanted, visibilityTimeout, 0, esm.getRegion()); + esm.getQueueUrl(), Math.min(10, wanted), visibilityTimeout, 0, esm.getRegion()); List messages; if (window <= 0) { diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java index 27a9e51088..87928c8681 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java @@ -167,7 +167,7 @@ public class PipesPoller implements Resettable { void pollSqs(Pipe pipe, String region) { String queueUrl = AwsArnUtils.arnToQueueUrl(pipe.getSource(), baseUrl); int batchSize = getBatchSize(pipe, "SqsQueueParameters"); - List messages = sqsService.receiveMessage(queueUrl, batchSize, 30, 0, region); + List messages = sqsService.receiveMessage(queueUrl, Math.min(10, batchSize), 30, 0, region); if (messages.isEmpty()) { return; } diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java index 02d36d7e5f..0617be8676 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java @@ -259,7 +259,8 @@ public class SqsJsonHandler { private Response handleReceiveMessage(JsonNode request, String region) { String queueUrl = request.path("QueueUrl").asText(null); - int maxMessages = request.path("MaxNumberOfMessages").asInt(1); + Integer requestedMax = getOptionalIntField(request, "MaxNumberOfMessages"); + int maxMessages = requestedMax == null ? 1 : requestedMax; int visibilityTimeout = request.path("VisibilityTimeout").asInt(-1); Integer waitTimeSeconds = getOptionalIntField(request, "WaitTimeSeconds"); diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java index 9fea7c15ff..1af13a7f46 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java @@ -274,7 +274,8 @@ public class SqsQueryHandler { private Response handleReceiveMessage(MultivaluedMap params, String region) { String queueUrl = getParam(params, "QueueUrl"); - int maxMessages = getIntParam(params, "MaxNumberOfMessages", 1); + Integer requestedMax = getOptionalIntParam(params, "MaxNumberOfMessages"); + int maxMessages = requestedMax == null ? 1 : requestedMax; int visibilityTimeout = getIntParam(params, "VisibilityTimeout", -1); Integer waitTimeSeconds = getOptionalIntParam(params, "WaitTimeSeconds"); diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java index e0b97d7328..77f8def344 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java @@ -1439,7 +1439,9 @@ public class SqsService implements Resettable, ResourceProvider { "The specified queue does not exist.", 400)); if (maxMessages < 1 || maxMessages > 10) { - maxMessages = 1; + throw new AwsException("InvalidParameterValue", + "Value " + maxMessages + " for parameter MaxNumberOfMessages is invalid. " + + "Reason: Must be between 1 and 10, if provided.", 400); } if (waitTimeSeconds != null && (waitTimeSeconds < 0 || waitTimeSeconds > MAX_RECEIVE_WAIT_TIME_SECONDS)) { throw new AwsException("InvalidParameterValue", diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java index 0affdd850e..5c1d9f1a14 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java @@ -29,6 +29,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static org.junit.jupiter.api.Assertions.*; @@ -495,6 +496,35 @@ class SqsEventSourcePollerTest { return fn; } + @Test + void largeBatchesUseLegalReceiveCountsAndStillDeliverTheWholeBatch() throws Exception { + LambdaFunction fn = stubThrowFn(); + EventSourceMapping esm = esm(); + esm.setBatchSize(25); + esm.setMaximumBatchingWindowInSeconds(300); + poller.setClockForTest(() -> 0L); + List messages = new ArrayList<>(); + for (int i = 0; i < 25; i++) { + messages.add(message("large-" + i)); + } + AtomicInteger position = new AtomicInteger(); + when(sqsService.receiveMessage(eq(esm.getQueueUrl()), anyInt(), anyInt(), anyInt(), eq("us-east-1"))) + .thenAnswer(call -> { + int count = call.getArgument(1); + assertTrue(count >= 1 && count <= 10); + int start = position.getAndAdd(count); + return messages.subList(start, Math.min(start + count, messages.size())); + }); + when(executorService.invoke(eq(fn), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult()); + for (int i = 0; i < 3; i++) { + awaitPoll(poller.pollAndInvoke(esm)); + } + ArgumentCaptor payload = ArgumentCaptor.forClass(byte[].class); + verify(executorService).invoke(eq(fn), payload.capture(), eq(InvocationType.RequestResponse)); + assertEquals(25, OBJECT_MAPPER.readTree(payload.getValue()).path("Records").size()); + } + private void stubReceive(EventSourceMapping esm, List messages) { when(sqsService.receiveMessage(eq(esm.getQueueUrl()), anyInt(), anyInt(), anyInt(), eq("us-east-1"))) .thenReturn(messages); diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java index 2b646fc019..7f788eed46 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java @@ -167,6 +167,18 @@ class PipesPollerTest { assertEquals("not-json", node.get(0).asText()); } + @Test + void sqsPollingKeepsConfiguredLargeBatchesWithinTheReceiveLimit() throws Exception { + Pipe pipe = new Pipe(); + pipe.setName("large-sqs-batch"); + pipe.setSource("arn:aws:sqs:us-east-1:000000000000:src-queue"); + pipe.setSourceParameters(MAPPER.readTree("{\"SqsQueueParameters\":{\"BatchSize\":25}}")); + when(sqsService.receiveMessage(anyString(), anyInt(), anyInt(), anyInt(), eq("us-east-1"))) + .thenReturn(List.of()); + poller.pollSqs(pipe, "us-east-1"); + verify(sqsService).receiveMessage(anyString(), eq(10), anyInt(), anyInt(), eq("us-east-1")); + } + @Test void pollSqs_enrichmentToNonLambdaTargetForwardsRawResponse() throws Exception { // A non-Lambda target (here Step Functions) must receive the raw enrichment response, not a diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsReceiveCountIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsReceiveCountIntegrationTest.java new file mode 100644 index 0000000000..87f7cdb0ae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsReceiveCountIntegrationTest.java @@ -0,0 +1,138 @@ +package io.github.hectorvent.floci.services.sqs; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +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 software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.Message; +import software.amazon.awssdk.services.sqs.model.MessageSystemAttributeName; +import software.amazon.awssdk.services.sqs.model.SqsException; + +import java.net.URI; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +class SqsReceiveCountIntegrationTest { + private static final String ACCOUNT = "741682000001"; + private static final String REGION = "eu-west-2"; + private static final String AUTH = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261028/" + REGION + "/sqs/aws4_request"; + private SqsClient client; + private String queueUrl; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createQueue() { + client = AwsTestClients.create(SqsClient.builder(), ACCOUNT, Region.of(REGION)); + String created = client.createQueue(request -> request.queueName("receive-count-" + UUID.randomUUID())).queueUrl(); + queueUrl = "http://localhost:" + RestAssured.port + URI.create(created).getRawPath(); + } + + @AfterEach + void cleanUp() { + try { + if (queueUrl != null) { + client.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } finally { + client.close(); + } + } + + @ParameterizedTest + @ValueSource(ints = {-1, 0, 11, Integer.MIN_VALUE, Integer.MAX_VALUE}) + void sdkRejectsInvalidCountsWithoutReceivingAMessage(int count) { + send("kept"); + SqsException error = assertThrows(SqsException.class, () -> client.receiveMessage(request -> request + .queueUrl(queueUrl).maxNumberOfMessages(count).waitTimeSeconds(0))); + assertEquals(400, error.statusCode()); + assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode()); + assertTrue(error.awsErrorDetails().errorMessage().contains("MaxNumberOfMessages")); + assertUnreceivedMessageRemains(); + } + + @ParameterizedTest + @ValueSource(ints = {1, 10}) + void sdkAcceptsBothRangeBoundaries(int count) { + for (int i = 0; i < 12; i++) { + send("message-" + i); + } + assertEquals(count, client.receiveMessage(request -> request.queueUrl(queueUrl) + .maxNumberOfMessages(count).waitTimeSeconds(0)).messages().size()); + } + + @Test + void omittedAndNullCountsKeepTheDefaultOfOne() { + send("first"); + send("second"); + assertEquals(1, client.receiveMessage(request -> request.queueUrl(queueUrl) + .visibilityTimeout(0).waitTimeSeconds(0)).messages().size()); + given().contentType("application/x-amz-json-1.0").header("Authorization", AUTH) + .header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":null}") + .post("/").then().statusCode(200).body("Messages.size()", equalTo(1)); + } + + @ParameterizedTest + @ValueSource(strings = {"-1", "0", "11", "2147483648", "4294967297", "1.5", "invalid", ""}) + void queryProtocolRejectsInvalidCountsAtBothEndpoints(String count) { + send("kept"); + for (String path : List.of("/", URI.create(queueUrl).getRawPath())) { + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ReceiveMessage").formParam("QueueUrl", queueUrl) + .formParam("MaxNumberOfMessages", count).formParam("WaitTimeSeconds", 0) + .post(path).then().statusCode(400) + .body(containsString("InvalidParameterValue")); + } + assertUnreceivedMessageRemains(); + } + + @ParameterizedTest + @ValueSource(strings = {"2147483648", "4294967297", "9223372036854775808", "1.5", "\"1\"", "true", "{}", "[]"}) + void jsonProtocolRejectsCoercionAndOverflowAtBothEndpoints(String count) { + send("kept"); + for (String path : List.of("/", URI.create(queueUrl).getRawPath())) { + given().contentType("application/x-amz-json-1.0").header("Authorization", AUTH) + .header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":" + count + "}") + .post(path).then().statusCode(400).body("__type", equalTo("InvalidParameterValue")); + } + assertUnreceivedMessageRemains(); + } + + @Test + void anEmptyQueueStillRejectsAnInvalidCount() { + SqsException error = assertThrows(SqsException.class, () -> client.receiveMessage(request -> request + .queueUrl(queueUrl).maxNumberOfMessages(0).waitTimeSeconds(0))); + assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode()); + } + + private void send(String body) { + client.sendMessage(request -> request.queueUrl(queueUrl).messageBody(body)); + } + + private void assertUnreceivedMessageRemains() { + List messages = client.receiveMessage(request -> request.queueUrl(queueUrl).maxNumberOfMessages(1) + .waitTimeSeconds(0).messageSystemAttributeNames(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT)).messages(); + assertEquals(1, messages.size()); + assertEquals("kept", messages.getFirst().body()); + assertEquals("1", messages.getFirst().attributesAsStrings().get("ApproximateReceiveCount")); + } +}