fix(sqs): send JSON responses with content length (#6209)

* fix(sqs): send JSON responses with content length

* fix(sqs): share JSON response serialization with DynamoDB
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-22 10:47:55 -04:00
1 parent 2720f84884
commit d7c139cb69
6 files changed
+165 -12

No files matched your search

@@ -205,6 +205,18 @@ public class AwsJsonController {
}
return DynamoDbResponses.withCrc32(response, objectMapper);
}
if ("sqs".equals(serviceKey) && response.getEntity() != null
&& !(response.getEntity() instanceof byte[])) {
byte[] bodyBytes = JsonResponseBytes.serializeOrNull(response.getEntity(), objectMapper,
LOG, "Failed to serialize SQS JSON response");
if (bodyBytes == null) {
return response;
}
return Response.fromResponse(response)
.entity(bodyBytes)
.type(CONTENT_TYPE_AWS_JSON_1_0)
.build();
}
return response;
}
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.logging.Logger;
public final class JsonResponseBytes {
private JsonResponseBytes() {}
public static byte[] serializeOrNull(Object entity, ObjectMapper objectMapper,
Logger logger, String failureMessage) {
try {
if (entity == null) {
return new byte[0];
}
if (entity instanceof byte[] bytes) {
return bytes;
}
return objectMapper.writeValueAsBytes(entity);
} catch (Exception e) {
logger.warn(failureMessage, e);
return null;
}
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.JsonResponseBytes;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
@@ -59,18 +60,9 @@ public final class DynamoDbResponses {
if (response == null) {
return null;
}
Object entity = response.getEntity();
byte[] bodyBytes;
try {
if (entity == null) {
bodyBytes = new byte[0];
} else if (entity instanceof byte[] b) {
bodyBytes = b;
} else {
bodyBytes = objectMapper.writeValueAsBytes(entity);
}
} catch (Exception e) {
LOG.warn("Failed to serialize DynamoDB response for CRC32 computation", e);
byte[] bodyBytes = JsonResponseBytes.serializeOrNull(response.getEntity(), objectMapper,
LOG, "Failed to serialize DynamoDB response for CRC32 computation");
if (bodyBytes == null) {
return response;
}
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AwsJsonControllerSerializationTest {
@Test
void sqsSerializationFailurePreservesOriginalResponse() throws Exception {
ObjectMapper mapper = new ObjectMapper() {
@Override
public byte[] writeValueAsBytes(Object value) throws JsonProcessingException {
throw new JsonProcessingException("expected serialization failure") {};
}
};
ResolvedServiceCatalog catalog = mock(ResolvedServiceCatalog.class);
ServiceDescriptor descriptor = new ServiceDescriptor("sqs", "sqs", true, true,
"sqs", "memory", 0, null, ServiceProtocol.QUERY, Set.of(ServiceProtocol.JSON),
Set.of("AmazonSQS."), Set.of("sqs"), Set.of(), Set.of(), Set.of());
when(catalog.matchTarget("AmazonSQS.Test"))
.thenReturn(Optional.of(new ServiceCatalog.TargetMatch(descriptor, "AmazonSQS.", "Test")));
RegionResolver regionResolver = mock(RegionResolver.class);
HttpHeaders headers = mock(HttpHeaders.class);
when(regionResolver.resolveRegion(headers)).thenReturn("us-east-1");
SqsJsonHandler sqs = mock(SqsJsonHandler.class);
Object entity = new Object();
Response original = Response.status(202).entity(entity)
.header("x-amzn-query-error", "example;Sender").build();
when(sqs.handle(eq("Test"), any(), eq("us-east-1"))).thenReturn(original);
AwsJsonController controller = new AwsJsonController(mapper, catalog, regionResolver,
null, null, sqs, null, null, null, null, null, null, null, null, null, null);
Response result = controller.handleJsonRequest("AmazonSQS.Test", headers, "{}");
assertSame(original, result);
assertEquals(202, result.getStatus());
assertSame(entity, result.getEntity());
assertEquals("example;Sender", result.getHeaderString("x-amzn-query-error"));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.ws.rs.core.MediaType;
@@ -114,6 +115,21 @@ class DynamoDbResponsesTest {
assertNull(DynamoDbResponses.withCrc32(null, mapper));
}
@Test
void withCrc32_serializationFailurePreservesOriginalResponse() {
ObjectMapper failingMapper = new ObjectMapper() {
@Override
public byte[] writeValueAsBytes(Object value) throws JsonProcessingException {
throw new JsonProcessingException("expected serialization failure") {};
}
};
Response original = Response.status(202).entity(new Object())
.header("x-amzn-requestid", "request-123").build();
assertSame(original, DynamoDbResponses.withCrc32(original, failingMapper));
assertNull(original.getHeaderString("X-Amz-Crc32"));
}
@Test
void legacyErrorsRetainMessageHeadersAndOriginalBackendBody() {
ObjectNode entity = mapper.createObjectNode()
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -14,6 +15,7 @@ import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -955,6 +957,58 @@ class SqsJsonProtocolTest {
}
}
@Test
void largeJsonReceiveMessageUsesContentLength() {
String framingQueueUrl = given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
.body("{\"QueueName\":\"json-response-framing-queue\"}")
.when().post("/")
.then().statusCode(200)
.extract().jsonPath().getString("QueueUrl");
try {
String messageBody = "x".repeat(12_000);
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + framingQueueUrl + "\",\"MessageBody\":\"" + messageBody + "\"}")
.when().post("/")
.then().statusCode(200);
for (String path : List.of("/", "/" + ACCOUNT_ID + "/json-response-framing-queue")) {
Response response = given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
.body("{\"QueueUrl\":\"" + framingQueueUrl
+ "\",\"MaxNumberOfMessages\":1,\"VisibilityTimeout\":0}")
.when().post(path)
.then().statusCode(200)
.body("Messages[0].Body", equalTo(messageBody))
.extract().response();
int bodyLength = response.asByteArray().length;
assertTrue(bodyLength > 8_191);
assertEquals(Integer.toString(bodyLength), response.getHeader("Content-Length"));
assertNull(response.getHeader("Transfer-Encoding"));
}
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
.body("{\"QueueUrl\":\"" + framingQueueUrl + "\",\"WaitTimeSeconds\":21}")
.when().post("/")
.then().statusCode(400)
.header("x-amzn-query-error", equalTo("InvalidParameterValue;Sender"))
.body("__type", equalTo("InvalidParameterValue"));
} finally {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.DeleteQueue")
.body("{\"QueueUrl\":\"" + framingQueueUrl + "\"}")
.when().post("/");
}
}
private static void assertMessageCounts(String url, String visible, String notVisible) {
given()
.contentType(CONTENT_TYPE)