mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(pipes): send an SQS target's MessageGroupId and MessageDeduplicationId (#9178)
A pipe with an SQS queue target ignored SqsQueueParameters, so a FIFO queue target failed every delivery for want of a group id. MessageGroupId and MessageDeduplicationId now reach SendMessage, each a literal or a JSON path read off the event before the InputTemplate renders, as the event bus target already does for Source and DetailType. A number becomes its text and an object its compact JSON, and a path that names nothing fails the delivery. CreatePipe and UpdatePipe check them as AWS does: a target whose queue name ends in .fifo needs SqsQueueParameters and a MessageGroupId, MessageDeduplicationId is refused on a standard queue, and a value that starts with $. but is not a valid JSON path is refused. The errors are reported together, in AWS's order, as a ValidationException with fieldList; UpdatePipe checks against the stored target when the request leaves it out. Part of #7481.
This commit is contained in:
1 parent
11b66161cd
commit
48b95fc8c7
7 files changed
+453
-19
No files matched your search
@@ -216,6 +216,13 @@ target input.
|
||||
pipe has an enrichment, before the `InputTemplate` renders. A value that is not wholly a JSON path
|
||||
stays as written. A path that names nothing fails the delivery, which is retried or sent to the
|
||||
dead-letter queue like any other failure.
|
||||
- An SQS queue target sends `SqsQueueParameters` `MessageGroupId` and `MessageDeduplicationId`. Each is
|
||||
a literal or a JSON path read off the event before the `InputTemplate` renders. A number becomes its
|
||||
text and an object becomes its compact JSON. A path that names nothing fails the delivery.
|
||||
- CreatePipe and UpdatePipe refuse an SQS target whose queue name ends in `.fifo` when it has no
|
||||
`SqsQueueParameters` or no `MessageGroupId`. They refuse a `MessageDeduplicationId` on a standard
|
||||
queue. They refuse a `MessageGroupId` or `MessageDeduplicationId` that starts with `$.` but is not a
|
||||
valid JSON path. The errors are reported together in `fieldList`.
|
||||
- An `InputTemplate` that is exactly one placeholder, such as `<$.Detail>`, renders a string as its
|
||||
own text with no quotes added, so a serialized object reaches an event bus as that object. A
|
||||
placeholder inside a larger template renders a string with quotes where the template gives none:
|
||||
|
||||
@@ -70,9 +70,7 @@ public class PipesController {
|
||||
|
||||
return Response.ok(buildPipeResponse(pipe)).build();
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.build();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Error creating pipe: {0}", e.getMessage());
|
||||
return Response.status(500)
|
||||
@@ -119,9 +117,7 @@ public class PipesController {
|
||||
|
||||
return Response.ok(buildPipeResponse(pipe)).build();
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.build();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Error updating pipe: {0}", e.getMessage());
|
||||
return Response.status(500)
|
||||
|
||||
@@ -2,7 +2,10 @@ package io.floci.aws.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
@@ -23,11 +26,13 @@ import org.jboss.logging.Logger;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -41,6 +46,9 @@ public class PipesService implements TagHandler, ResourceProvider {
|
||||
private static final int MAX_REDSHIFT_SQLS = 40;
|
||||
private static final int MAX_REDSHIFT_SQL_LENGTH = 100_000;
|
||||
|
||||
// CreatePipe refuses a target parameter that starts with $. and does not match this.
|
||||
private static final Pattern TARGET_PARAMETER_PATH = Pattern.compile("\\$(?:\\.[\\w/-]+|\\[(?:\\d+|\\*)])+");
|
||||
|
||||
private final StorageBackend<String, Pipe> storage;
|
||||
private final RegionResolver regionResolver;
|
||||
private final PipesPoller poller;
|
||||
@@ -354,15 +362,20 @@ public class PipesService implements TagHandler, ResourceProvider {
|
||||
"Resource " + arn + " does not exist.", 404));
|
||||
}
|
||||
|
||||
private void validateTargetConfiguration(String target, JsonNode targetParameters) {
|
||||
if (AwsArnUtils.isArnFor(target, "sqs")) {
|
||||
validateSqsTarget(target, targetParameters);
|
||||
} else if (PipesTargetInvoker.isRedshiftTarget(target)) {
|
||||
validateRedshiftTarget(targetParameters);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Redshift target runs its {@code Sqls} as one BatchExecuteStatement, which the PipeTargetRedshiftDataParameters
|
||||
* reference makes required together with {@code Database}, with 1 to 40 statements of at most 100,000
|
||||
* characters each.
|
||||
*/
|
||||
private void validateTargetConfiguration(String target, JsonNode targetParameters) {
|
||||
if (!PipesTargetInvoker.isRedshiftTarget(target)) {
|
||||
return;
|
||||
}
|
||||
private void validateRedshiftTarget(JsonNode targetParameters) {
|
||||
JsonNode parameters = targetParameters == null
|
||||
? MissingNode.getInstance() : targetParameters.path("RedshiftDataParameters");
|
||||
if (!parameters.path("Database").isTextual() || parameters.path("Database").asText().isBlank()) {
|
||||
@@ -384,6 +397,64 @@ public class PipesService implements TagHandler, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateSqsTarget(String target, JsonNode targetParameters) {
|
||||
boolean fifo = AwsArnUtils.resourceIfArnFor(target, "sqs").orElse("").endsWith(".fifo");
|
||||
JsonNode sqsParameters = targetParameters == null
|
||||
? MissingNode.getInstance() : targetParameters.path("SqsQueueParameters");
|
||||
if (sqsParameters.isMissingNode() || sqsParameters.isNull()) {
|
||||
if (fifo) {
|
||||
throw validationFields(List.of(new ValidationField(
|
||||
"TargetParameters.SqsQueueParameters", "Missing required target parameter.")));
|
||||
}
|
||||
return;
|
||||
}
|
||||
String groupId = PipesTargetInvoker.text(sqsParameters, "MessageGroupId");
|
||||
String dedupId = PipesTargetInvoker.text(sqsParameters, "MessageDeduplicationId");
|
||||
List<ValidationField> errors = new ArrayList<>();
|
||||
if (groupId != null && isInvalidDynamicPath(groupId)) {
|
||||
errors.add(new ValidationField("MessageGroupId", invalidPathMessage(groupId)));
|
||||
}
|
||||
if (dedupId != null && isInvalidDynamicPath(dedupId)) {
|
||||
errors.add(new ValidationField("MessageDeduplicationId", invalidPathMessage(dedupId)));
|
||||
}
|
||||
if (dedupId != null && !fifo) {
|
||||
errors.add(new ValidationField("MessageDeduplicationId",
|
||||
"Parameter only applies to FIFO (first-in-first-out) queues."));
|
||||
}
|
||||
if (fifo && groupId == null) {
|
||||
errors.add(new ValidationField("MessageGroupId",
|
||||
"MessageGroupId is required for FIFO (first-in-first-out) queues."));
|
||||
}
|
||||
if (!errors.isEmpty()) {
|
||||
throw validationFields(errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isInvalidDynamicPath(String value) {
|
||||
return value.startsWith("$.") && !TARGET_PARAMETER_PATH.matcher(value).matches();
|
||||
}
|
||||
|
||||
private static String invalidPathMessage(String value) {
|
||||
return "Invalid JSON path " + value + " provided in the service target parameters.";
|
||||
}
|
||||
|
||||
private static AwsException validationFields(List<ValidationField> errors) {
|
||||
ArrayNode validationErrorFields = JsonNodeFactory.instance.arrayNode();
|
||||
List<Map<String, String>> fieldList = new ArrayList<>();
|
||||
for (ValidationField error : errors) {
|
||||
validationErrorFields.addObject().put("Name", error.name()).put("Message", error.message());
|
||||
Map<String, String> field = new LinkedHashMap<>();
|
||||
field.put("name", error.name());
|
||||
field.put("message", error.message());
|
||||
fieldList.add(field);
|
||||
}
|
||||
ObjectNode message = JsonNodeFactory.instance.objectNode();
|
||||
message.set("ValidationErrorFields", validationErrorFields);
|
||||
return new AwsException("ValidationException", message.toString(), 400, Map.of("fieldList", fieldList));
|
||||
}
|
||||
|
||||
private record ValidationField(String name, String message) {}
|
||||
|
||||
private void validateSourceConfiguration(String source, JsonNode sourceParameters) {
|
||||
if (source == null) {
|
||||
return;
|
||||
|
||||
@@ -104,7 +104,7 @@ public class PipesTargetInvoker {
|
||||
if (targetArn.contains(":lambda:") || targetArn.contains(":function:")) {
|
||||
invokeLambda(targetArn, payload, region);
|
||||
} else if (targetArn.contains(":sqs:")) {
|
||||
invokeSqs(targetArn, payload, region);
|
||||
invokeSqs(targetArn, payload, region, tp, event);
|
||||
} else if (targetArn.contains(":sns:")) {
|
||||
invokeSns(targetArn, payload, region);
|
||||
} else if (targetArn.contains(":events:")) {
|
||||
@@ -198,9 +198,14 @@ public class PipesTargetInvoker {
|
||||
return fi >= 0 ? ref.substring(fi + ":function:".length()) : ref;
|
||||
}
|
||||
|
||||
private void invokeSqs(String arn, String payload, String region) {
|
||||
private void invokeSqs(String arn, String payload, String region, JsonNode tp, String event) {
|
||||
String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl);
|
||||
sqsService.sendMessage(queueUrl, payload, 0, region);
|
||||
JsonNode sqsParams = tp == null ? MissingNode.getInstance() : tp.path("SqsQueueParameters");
|
||||
String groupId = resolveDynamicParameter(text(sqsParams, "MessageGroupId"), event,
|
||||
"target parameter MessageGroupId");
|
||||
String dedupId = resolveDynamicParameter(text(sqsParams, "MessageDeduplicationId"), event,
|
||||
"target parameter MessageDeduplicationId");
|
||||
sqsService.sendMessage(queueUrl, payload, 0, groupId, dedupId, region);
|
||||
LOG.debugv("Pipe delivered to SQS: {0}", arn);
|
||||
}
|
||||
|
||||
@@ -290,7 +295,7 @@ public class PipesTargetInvoker {
|
||||
LOG.debugv("Pipe delivered to Redshift Data API: {0}", targetArn);
|
||||
}
|
||||
|
||||
private static String text(JsonNode parent, String field) {
|
||||
static String text(JsonNode parent, String field) {
|
||||
JsonNode node = parent.path(field);
|
||||
return node.isTextual() ? node.asText() : null;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package io.floci.aws.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
@@ -12,8 +14,12 @@ import io.floci.aws.services.pipes.model.Pipe;
|
||||
import io.floci.aws.services.pipes.model.PipeState;
|
||||
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.Mockito;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -24,6 +30,10 @@ import static org.mockito.Mockito.when;
|
||||
class PipesServiceTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SQS_SOURCE = "arn:aws:sqs:us-east-1:000000000000:source";
|
||||
private static final String STANDARD_TARGET = "arn:aws:sqs:us-east-1:000000000000:target";
|
||||
private static final String FIFO_TARGET = "arn:aws:sqs:us-east-1:000000000000:target.fifo";
|
||||
private static final String PIPE_ROLE = "arn:aws:iam::000000000000:role/role";
|
||||
|
||||
private AccountAwareStorageBackend<Pipe> storage;
|
||||
private PipesService pipesService;
|
||||
@@ -41,6 +51,127 @@ class PipesServiceTest {
|
||||
pipesService = new PipesService(storageFactory, regionResolver, poller);
|
||||
}
|
||||
|
||||
private static JsonNode sqsParameters(String groupId, String dedupId) {
|
||||
ObjectNode tp = MAPPER.createObjectNode();
|
||||
ObjectNode sqs = tp.putObject("SqsQueueParameters");
|
||||
if (groupId != null) {
|
||||
sqs.put("MessageGroupId", groupId);
|
||||
}
|
||||
if (dedupId != null) {
|
||||
sqs.put("MessageDeduplicationId", dedupId);
|
||||
}
|
||||
return tp;
|
||||
}
|
||||
|
||||
private Pipe createSqsPipe(String target, JsonNode targetParameters) {
|
||||
return pipesService.createPipe("sqs-pipe", SQS_SOURCE, target, PIPE_ROLE,
|
||||
null, null, null, null, targetParameters, null, null, "us-east-1");
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void assertFields(AwsException ex, String... namesAndMessages) throws Exception {
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
ArrayNode expectedFields = MAPPER.createArrayNode();
|
||||
List<Map<String, String>> expectedList = new ArrayList<>();
|
||||
for (int i = 0; i < namesAndMessages.length; i += 2) {
|
||||
expectedFields.addObject().put("Name", namesAndMessages[i]).put("Message", namesAndMessages[i + 1]);
|
||||
Map<String, String> field = new LinkedHashMap<>();
|
||||
field.put("name", namesAndMessages[i]);
|
||||
field.put("message", namesAndMessages[i + 1]);
|
||||
expectedList.add(field);
|
||||
}
|
||||
ObjectNode expected = MAPPER.createObjectNode();
|
||||
expected.set("ValidationErrorFields", expectedFields);
|
||||
assertEquals(expected.toString(), ex.getMessage());
|
||||
assertEquals(expectedList, ex.getExtendedData().get("fieldList"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsFifoTargetWithoutSqsQueueParametersIsRefused() throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> createSqsPipe(FIFO_TARGET, null));
|
||||
assertFields(ex, "TargetParameters.SqsQueueParameters", "Missing required target parameter.");
|
||||
|
||||
ex = assertThrows(AwsException.class,
|
||||
() -> createSqsPipe(FIFO_TARGET, MAPPER.createObjectNode().put("InputTemplate", "x")));
|
||||
assertFields(ex, "TargetParameters.SqsQueueParameters", "Missing required target parameter.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsFifoTargetWithoutMessageGroupIdIsRefused() throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> createSqsPipe(FIFO_TARGET, sqsParameters(null, null)));
|
||||
assertFields(ex, "MessageGroupId", "MessageGroupId is required for FIFO (first-in-first-out) queues.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsFifoTargetWithOnlyAnInvalidDeduplicationPathReportsBoth() throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> createSqsPipe(FIFO_TARGET, sqsParameters(null, "$.x[")));
|
||||
assertFields(ex,
|
||||
"MessageDeduplicationId", "Invalid JSON path $.x[ provided in the service target parameters.",
|
||||
"MessageGroupId", "MessageGroupId is required for FIFO (first-in-first-out) queues.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsStandardTargetWithInvalidPathsReportsGroupDeduplicationAndFifoOnly() throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> createSqsPipe(STANDARD_TARGET, sqsParameters("$.g[", "$.x[")));
|
||||
assertFields(ex,
|
||||
"MessageGroupId", "Invalid JSON path $.g[ provided in the service target parameters.",
|
||||
"MessageDeduplicationId", "Invalid JSON path $.x[ provided in the service target parameters.",
|
||||
"MessageDeduplicationId", "Parameter only applies to FIFO (first-in-first-out) queues.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsStandardTargetWithDeduplicationIdIsRefused() throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> createSqsPipe(STANDARD_TARGET, sqsParameters("g", "d")));
|
||||
assertFields(ex, "MessageDeduplicationId", "Parameter only applies to FIFO (first-in-first-out) queues.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsTargetsAreAcceptedWhenTheirParametersFitTheQueueKind() {
|
||||
assertNotNull(createSqsPipe(STANDARD_TARGET, null));
|
||||
pipesService.deletePipe("sqs-pipe", "us-east-1");
|
||||
assertNotNull(createSqsPipe(STANDARD_TARGET, sqsParameters("g", null)));
|
||||
pipesService.deletePipe("sqs-pipe", "us-east-1");
|
||||
assertNotNull(createSqsPipe(FIFO_TARGET, sqsParameters("", null)));
|
||||
pipesService.deletePipe("sqs-pipe", "us-east-1");
|
||||
assertNotNull(createSqsPipe(FIFO_TARGET, sqsParameters("$.g", "$.d")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"$.body[", "$.a b", "$.", "$..a", "$.a.*", "$.a[-1]"})
|
||||
void sqsMessageGroupIdThatStartsWithADollarDotButIsNotAPathIsRefused(String value) throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> createSqsPipe(FIFO_TARGET, sqsParameters(value, null)));
|
||||
assertFields(ex, "MessageGroupId",
|
||||
"Invalid JSON path " + value + " provided in the service target parameters.");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"$.a[0]", "$.a[*]", "$.a-b", "$.a/b", "$", "$x", "$[0]", "$['a']", "a$.b"})
|
||||
void sqsMessageGroupIdThatIsAPathOrNotPathLikeIsAccepted(String value) {
|
||||
assertNotNull(createSqsPipe(FIFO_TARGET, sqsParameters(value, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsUpdateWithOnlyTargetParametersIsCheckedAgainstTheStoredTarget() throws Exception {
|
||||
createSqsPipe(FIFO_TARGET, sqsParameters("g", null));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> pipesService.updatePipe("sqs-pipe", null, null,
|
||||
null, null, null, null, sqsParameters(null, null), null, "us-east-1"));
|
||||
assertFields(ex, "MessageGroupId", "MessageGroupId is required for FIFO (first-in-first-out) queues.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsUpdateWithANewTargetIsCheckedAgainstTheStoredParameters() throws Exception {
|
||||
createSqsPipe(STANDARD_TARGET, null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> pipesService.updatePipe("sqs-pipe", FIFO_TARGET,
|
||||
null, null, null, null, null, null, null, "us-east-1"));
|
||||
assertFields(ex, "TargetParameters.SqsQueueParameters", "Missing required target parameter.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPipe() {
|
||||
Pipe pipe = pipesService.createPipe("test-pipe",
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
@QuarkusTest
|
||||
class PipesSqsTargetIntegrationTest {
|
||||
|
||||
private static final String SQS_CONTENT_TYPE = "application/x-www-form-urlencoded";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/pipe-role";
|
||||
|
||||
@Test
|
||||
void fifoTargetReceivesTheGroupAndDeduplicationIdsReadOffTheEvent() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceName = "pipe-sqs-src-" + suffix;
|
||||
String targetName = "pipe-sqs-fifo-" + suffix + ".fifo";
|
||||
String pipeName = "pipe-sqs-fifo-" + suffix;
|
||||
String sourceUrl = createQueue(sourceName, false);
|
||||
String targetUrl = createQueue(targetName, true);
|
||||
try {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"Source": "arn:aws:sqs:us-east-1:000000000000:%s",
|
||||
"Target": "arn:aws:sqs:us-east-1:000000000000:%s",
|
||||
"RoleArn": "%s",
|
||||
"TargetParameters": {
|
||||
"InputTemplate": "{\\"t\\": <$.body.g>}",
|
||||
"SqsQueueParameters": {
|
||||
"MessageGroupId": "$.body.g",
|
||||
"MessageDeduplicationId": "$.body.d"
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(sourceName, targetName, ROLE))
|
||||
.when()
|
||||
.post("/v1/pipes/" + pipeName)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.formParam("Action", "SendMessage")
|
||||
.formParam("QueueUrl", sourceUrl)
|
||||
.formParam("MessageBody", "{\"g\":\"grp\",\"d\":7}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
XmlPath message = receive(targetUrl);
|
||||
if (message == null) {
|
||||
fail("The FIFO target queue never received the message");
|
||||
}
|
||||
assertEquals("{\"t\": \"grp\"}",
|
||||
message.getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Body"));
|
||||
assertEquals("grp", attribute(message, "MessageGroupId"));
|
||||
assertEquals("7", attribute(message, "MessageDeduplicationId"));
|
||||
} finally {
|
||||
given().when().delete("/v1/pipes/" + pipeName);
|
||||
deleteQueue(sourceUrl);
|
||||
deleteQueue(targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPipeForAFifoTargetWithoutTargetParametersIsRefusedWithTheFieldList() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceName = "pipe-sqs-src-" + suffix;
|
||||
String targetName = "pipe-sqs-fifo-" + suffix + ".fifo";
|
||||
String pipeName = "pipe-sqs-refused-" + suffix;
|
||||
String sourceUrl = createQueue(sourceName, false);
|
||||
String targetUrl = createQueue(targetName, true);
|
||||
try {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"Source": "arn:aws:sqs:us-east-1:000000000000:%s",
|
||||
"Target": "arn:aws:sqs:us-east-1:000000000000:%s",
|
||||
"RoleArn": "%s"
|
||||
}
|
||||
""".formatted(sourceName, targetName, ROLE))
|
||||
.when()
|
||||
.post("/v1/pipes/" + pipeName)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("{\"ValidationErrorFields\":[{\"Name\":"
|
||||
+ "\"TargetParameters.SqsQueueParameters\","
|
||||
+ "\"Message\":\"Missing required target parameter.\"}]}"))
|
||||
.body("fieldList.size()", equalTo(1))
|
||||
.body("fieldList[0].name", equalTo("TargetParameters.SqsQueueParameters"))
|
||||
.body("fieldList[0].message", equalTo("Missing required target parameter."));
|
||||
} finally {
|
||||
given().when().delete("/v1/pipes/" + pipeName);
|
||||
deleteQueue(sourceUrl);
|
||||
deleteQueue(targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private static String createQueue(String name, boolean fifo) {
|
||||
RequestSpecification request = given()
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.formParam("Action", "CreateQueue")
|
||||
.formParam("QueueName", name);
|
||||
if (fifo) {
|
||||
request = request.formParam("Attribute.1.Name", "FifoQueue").formParam("Attribute.1.Value", "true");
|
||||
}
|
||||
return request.when().post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
|
||||
}
|
||||
|
||||
private static XmlPath receive(String queueUrl) throws InterruptedException {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
Thread.sleep(500);
|
||||
XmlPath result = given()
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.formParam("Action", "ReceiveMessage")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.formParam("MaxNumberOfMessages", "1")
|
||||
.formParam("AttributeName.1", "All")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().xmlPath();
|
||||
if (!result.getList("ReceiveMessageResponse.ReceiveMessageResult.Message").isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String attribute(XmlPath message, String name) {
|
||||
return message.getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.find { it.Name == '"
|
||||
+ name + "' }.Value");
|
||||
}
|
||||
|
||||
private static void deleteQueue(String queueUrl) {
|
||||
given()
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.formParam("Action", "DeleteQueue")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ import static org.mockito.Mockito.*;
|
||||
class PipesTargetInvokerTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String FIFO_ARN = "arn:aws:sqs:us-east-1:000000000000:target.fifo";
|
||||
private static final String BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-bus/orders-bus";
|
||||
|
||||
@Mock private LambdaService lambdaService;
|
||||
@@ -249,11 +250,76 @@ class PipesTargetInvokerTest {
|
||||
invoker.invoke(pipe, payload, region);
|
||||
|
||||
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), eq(region));
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), isNull(), isNull(), eq(region));
|
||||
String sent = captor.getValue();
|
||||
assertEquals("{\"id\": \"msg-123\", \"content\": \"hello world\"}", sent);
|
||||
}
|
||||
|
||||
private ObjectNode sqsParameters(String groupId, String dedupId) {
|
||||
ObjectNode tp = MAPPER.createObjectNode();
|
||||
ObjectNode sqs = tp.putObject("SqsQueueParameters");
|
||||
if (groupId != null) {
|
||||
sqs.put("MessageGroupId", groupId);
|
||||
}
|
||||
if (dedupId != null) {
|
||||
sqs.put("MessageDeduplicationId", dedupId);
|
||||
}
|
||||
return tp;
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqs_literalGroupAndDeduplicationIdsReachTheQueue() {
|
||||
Pipe pipe = createPipe(FIFO_ARN, sqsParameters("grp", "dup"));
|
||||
|
||||
invoker.invoke(pipe, "{\"g\":\"other\"}", "us-east-1");
|
||||
|
||||
verify(sqsService).sendMessage(anyString(), eq("{\"g\":\"other\"}"), eq(0), eq("grp"), eq("dup"),
|
||||
eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqs_pathsReadTheEventBeforeTheTemplateRenders() {
|
||||
ObjectNode tp = sqsParameters("$.body.g", "$.body.d");
|
||||
tp.put("InputTemplate", "{\"t\": <$.body.g>}");
|
||||
Pipe pipe = createPipe(FIFO_ARN, tp);
|
||||
|
||||
invoker.invoke(pipe, "{\"body\":{\"g\":\"grp\",\"d\":7}}", "us-east-1");
|
||||
|
||||
verify(sqsService).sendMessage(anyString(), eq("{\"t\": \"grp\"}"), eq(0), eq("grp"), eq("7"),
|
||||
eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqs_anObjectPathBecomesItsCompactJson() {
|
||||
Pipe pipe = createPipe(FIFO_ARN, sqsParameters("$.body.o", null));
|
||||
|
||||
invoker.invoke(pipe, "{\"body\":{\"o\":{\"a\":1,\"b\":\"c\"}}}", "us-east-1");
|
||||
|
||||
verify(sqsService).sendMessage(anyString(), anyString(), eq(0), eq("{\"a\":1,\"b\":\"c\"}"), isNull(),
|
||||
eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqs_aPathNamingNothingThrowsAndSendsNothing() {
|
||||
Pipe pipe = createPipe(FIFO_ARN, sqsParameters("$.body.missing", null));
|
||||
|
||||
RuntimeException ex = assertThrows(RuntimeException.class,
|
||||
() -> invoker.invoke(pipe, "{\"body\":{\"g\":\"grp\"}}", "us-east-1"));
|
||||
|
||||
assertTrue(ex.getMessage().contains("$.body.missing"), ex.getMessage());
|
||||
verifyNoInteractions(sqsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqs_aDeduplicationPathNamingNothingThrowsAndSendsNothing() {
|
||||
Pipe pipe = createPipe(FIFO_ARN, sqsParameters("grp", "$.body.missing"));
|
||||
|
||||
assertThrows(RuntimeException.class,
|
||||
() -> invoker.invoke(pipe, "{\"body\":{\"g\":\"grp\"}}", "us-east-1"));
|
||||
|
||||
verifyNoInteractions(sqsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inputTemplate_missingFieldReplacesWithEmpty() {
|
||||
String region = "us-east-1";
|
||||
@@ -266,7 +332,7 @@ class PipesTargetInvokerTest {
|
||||
invoker.invoke(pipe, payload, region);
|
||||
|
||||
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), eq(region));
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), isNull(), isNull(), eq(region));
|
||||
assertEquals("{\"id\": \"\"}", captor.getValue());
|
||||
}
|
||||
|
||||
@@ -279,7 +345,7 @@ class PipesTargetInvokerTest {
|
||||
|
||||
invoker.invoke(pipe, payload, region);
|
||||
|
||||
verify(sqsService).sendMessage(anyString(), eq(payload), eq(0), eq(region));
|
||||
verify(sqsService).sendMessage(anyString(), eq(payload), eq(0), isNull(), isNull(), eq(region));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -315,7 +381,7 @@ class PipesTargetInvokerTest {
|
||||
invoker.invoke(pipe, payload, region);
|
||||
|
||||
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), eq(region));
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), isNull(), isNull(), eq(region));
|
||||
assertEquals("{\"data\": {\"key\":\"value\"}}", captor.getValue());
|
||||
}
|
||||
|
||||
@@ -593,7 +659,7 @@ class PipesTargetInvokerTest {
|
||||
invoker.invoke(pipe, payload, region);
|
||||
|
||||
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), eq(region));
|
||||
verify(sqsService).sendMessage(anyString(), captor.capture(), eq(0), isNull(), isNull(), eq(region));
|
||||
assertEquals(
|
||||
"{\"message\": \"user registered\", \"messageType\": \"REGISTRATION\"}",
|
||||
captor.getValue());
|
||||
|
||||
Reference in new issue
Block a user