mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(pipes): deliver to a Kinesis stream target with its PartitionKey (#9185)
This commit is contained in:
1 parent
d8809f6f0e
commit
4d96d3e662
8 files changed
+553
-25
No files matched your search
@@ -223,6 +223,15 @@ target input.
|
||||
`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`.
|
||||
- A Kinesis stream target writes one record per event, with the event JSON, or the rendered
|
||||
`InputTemplate`, as its data. `KinesisStreamParameters` `PartitionKey` is a literal or a JSON path read
|
||||
off the event before the `InputTemplate` renders. A number becomes its text. A path that names
|
||||
nothing fails the delivery. An empty key, or one longer than 256 characters, also fails the delivery.
|
||||
- CreatePipe and UpdatePipe refuse a Kinesis target that is not a plain `stream/<name>` ARN or is in another
|
||||
account, one that has no `KinesisStreamParameters`, and a `PartitionKey` that starts with `$.` but is not a
|
||||
valid JSON path. The errors are reported together in `fieldList`. A `PartitionKey` that is missing, not a
|
||||
string, or longer than 256 characters is refused alone with a schema message. An empty `PartitionKey` is
|
||||
accepted.
|
||||
- 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:
|
||||
|
||||
@@ -365,6 +365,8 @@ public class PipesService implements TagHandler, ResourceProvider {
|
||||
private void validateTargetConfiguration(String target, JsonNode targetParameters) {
|
||||
if (AwsArnUtils.isArnFor(target, "sqs")) {
|
||||
validateSqsTarget(target, targetParameters);
|
||||
} else if (AwsArnUtils.isArnFor(target, "kinesis")) {
|
||||
validateKinesisTarget(target, targetParameters);
|
||||
} else if (PipesTargetInvoker.isRedshiftTarget(target)) {
|
||||
validateRedshiftTarget(targetParameters);
|
||||
}
|
||||
@@ -430,6 +432,68 @@ public class PipesService implements TagHandler, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateKinesisTarget(String target, JsonNode targetParameters) {
|
||||
JsonNode kinesisParameters = targetParameters == null
|
||||
? MissingNode.getInstance() : targetParameters.path("KinesisStreamParameters");
|
||||
if (kinesisParameters.isObject()) {
|
||||
validatePartitionKeySchema(kinesisParameters.path("PartitionKey"));
|
||||
}
|
||||
List<ValidationField> errors = new ArrayList<>();
|
||||
String resource = AwsArnUtils.resourceIfArnFor(target, "kinesis").orElse("");
|
||||
boolean plainStream = resource.startsWith("stream/") && resource.length() > "stream/".length()
|
||||
&& resource.indexOf('/', "stream/".length()) < 0;
|
||||
if (!plainStream) {
|
||||
errors.add(new ValidationField("Target", "Invalid pipe target ARN"));
|
||||
} else if (!AwsArnUtils.parse(target).accountId().equals(regionResolver.getAccountId())) {
|
||||
errors.add(new ValidationField("Target", "Creating cross-account pipe is not permitted."));
|
||||
}
|
||||
if (kinesisParameters.isMissingNode() || kinesisParameters.isNull()) {
|
||||
errors.add(new ValidationField(
|
||||
"TargetParameters.KinesisStreamParameters", "Missing required target parameter."));
|
||||
} else {
|
||||
String partitionKey = PipesTargetInvoker.text(kinesisParameters, "PartitionKey");
|
||||
if (partitionKey != null && isInvalidDynamicPath(partitionKey)) {
|
||||
errors.add(new ValidationField("PartitionKey", invalidPathMessage(partitionKey)));
|
||||
}
|
||||
}
|
||||
if (!errors.isEmpty()) {
|
||||
throw validationFields(errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validatePartitionKeySchema(JsonNode partitionKey) {
|
||||
if (partitionKey.isMissingNode()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"[object has missing required properties ([\"PartitionKey\"])]", 400);
|
||||
}
|
||||
if (!partitionKey.isTextual()) {
|
||||
throw new AwsException("ValidationException", "[instance type (" + jsonTypeName(partitionKey)
|
||||
+ ") does not match any allowed primitive type (allowed: [\"string\"])]", 400);
|
||||
}
|
||||
String value = partitionKey.asText();
|
||||
int length = value.codePointCount(0, value.length());
|
||||
if (length > PipesTargetInvoker.MAX_PARTITION_KEY_LENGTH) {
|
||||
throw new AwsException("ValidationException", "[string \"" + value + "\" is too long (length: "
|
||||
+ length + ", maximum allowed: " + PipesTargetInvoker.MAX_PARTITION_KEY_LENGTH + ")]", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static String jsonTypeName(JsonNode node) {
|
||||
if (node.isNull()) {
|
||||
return "null";
|
||||
}
|
||||
if (node.isIntegralNumber()) {
|
||||
return "integer";
|
||||
}
|
||||
if (node.isNumber()) {
|
||||
return "number";
|
||||
}
|
||||
if (node.isBoolean()) {
|
||||
return "boolean";
|
||||
}
|
||||
return node.isObject() ? "object" : "array";
|
||||
}
|
||||
|
||||
private static boolean isInvalidDynamicPath(String value) {
|
||||
return value.startsWith("$.") && !TARGET_PARAMETER_PATH.matcher(value).matches();
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.core.common.ServiceRegistry;
|
||||
import io.floci.aws.services.eventbridge.EventBridgeService;
|
||||
import io.floci.aws.services.kinesis.KinesisService;
|
||||
import io.floci.aws.services.lambda.LambdaService;
|
||||
import io.floci.aws.services.lambda.model.InvocationType;
|
||||
import io.floci.aws.services.lambda.model.InvokeResult;
|
||||
@@ -42,12 +43,14 @@ public class PipesTargetInvoker {
|
||||
Pattern.compile("<(\\$[^>]+|aws\\.pipes\\.event\\.ingestion-time)>");
|
||||
private static final Pattern ARRAY_INDEX = Pattern.compile("^(.*?)\\[(\\d+)]$");
|
||||
private static final String PIPES_PRINCIPAL = ServicePrincipals.of("pipes");
|
||||
static final int MAX_PARTITION_KEY_LENGTH = 256;
|
||||
private static final Pattern DYNAMIC_PARAMETER_PATH =
|
||||
Pattern.compile("\\$(?:\\.[\\w*/-]+|\\[\\d+\\])+");
|
||||
|
||||
private final LambdaService lambdaService;
|
||||
private final SqsService sqsService;
|
||||
private final SnsService snsService;
|
||||
private final KinesisService kinesisService;
|
||||
private final EventBridgeService eventBridgeService;
|
||||
private final StepFunctionsService stepFunctionsService;
|
||||
private final RedshiftDataTargetSubmitter redshiftSubmitter;
|
||||
@@ -60,6 +63,7 @@ public class PipesTargetInvoker {
|
||||
public PipesTargetInvoker(LambdaService lambdaService,
|
||||
SqsService sqsService,
|
||||
SnsService snsService,
|
||||
KinesisService kinesisService,
|
||||
EventBridgeService eventBridgeService,
|
||||
StepFunctionsService stepFunctionsService,
|
||||
RedshiftDataTargetSubmitter redshiftSubmitter,
|
||||
@@ -70,6 +74,7 @@ public class PipesTargetInvoker {
|
||||
this.lambdaService = lambdaService;
|
||||
this.sqsService = sqsService;
|
||||
this.snsService = snsService;
|
||||
this.kinesisService = kinesisService;
|
||||
this.eventBridgeService = eventBridgeService;
|
||||
this.stepFunctionsService = stepFunctionsService;
|
||||
this.redshiftSubmitter = redshiftSubmitter;
|
||||
@@ -107,6 +112,8 @@ public class PipesTargetInvoker {
|
||||
invokeSqs(targetArn, payload, region, tp, event);
|
||||
} else if (targetArn.contains(":sns:")) {
|
||||
invokeSns(targetArn, payload, region);
|
||||
} else if (AwsArnUtils.isArnFor(targetArn, "kinesis")) {
|
||||
invokeKinesis(targetArn, payload, region, tp, event);
|
||||
} else if (targetArn.contains(":events:")) {
|
||||
invokeEventBridge(targetArn, payload, region, tp, event);
|
||||
} else if (targetArn.contains(":states:")) {
|
||||
@@ -215,6 +222,32 @@ public class PipesTargetInvoker {
|
||||
LOG.debugv("Pipe delivered to SNS: {0}", arn);
|
||||
}
|
||||
|
||||
private void invokeKinesis(String arn, String payload, String region, JsonNode tp, String event) {
|
||||
JsonNode kinesisParams = tp == null ? MissingNode.getInstance() : tp.path("KinesisStreamParameters");
|
||||
String partitionKey = resolveDynamicParameter(text(kinesisParams, "PartitionKey"), event,
|
||||
"target parameter PartitionKey");
|
||||
validateKinesisPartitionKey(partitionKey);
|
||||
AwsArnUtils.Arn stream = AwsArnUtils.parse(arn);
|
||||
kinesisService.putRecordForAccount(stream.accountId(), PipesPoller.kinesisStreamName(arn),
|
||||
payload.getBytes(StandardCharsets.UTF_8), partitionKey, extractRegionFromArn(arn, region));
|
||||
LOG.debugv("Pipe delivered to Kinesis: {0}", arn);
|
||||
}
|
||||
|
||||
private static void validateKinesisPartitionKey(String partitionKey) {
|
||||
String key = partitionKey == null ? "" : partitionKey;
|
||||
String constraint;
|
||||
if (key.isEmpty()) {
|
||||
constraint = "greater than or equal to 1";
|
||||
} else if (key.codePointCount(0, key.length()) > MAX_PARTITION_KEY_LENGTH) {
|
||||
constraint = "less than or equal to " + MAX_PARTITION_KEY_LENGTH;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + key
|
||||
+ "' at 'records.1.member.partitionKey' failed to satisfy constraint: Member must have length "
|
||||
+ constraint, 400);
|
||||
}
|
||||
|
||||
private void invokeEventBridge(String arn, String payload, String region, JsonNode tp, String event) {
|
||||
String busName = AwsArnUtils.resourceIfArnFor(arn, "events")
|
||||
.filter(resource -> resource.startsWith("event-bus/"))
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class PipesKinesisTargetIntegrationTest {
|
||||
|
||||
private static final String SQS_CONTENT_TYPE = "application/x-www-form-urlencoded";
|
||||
private static final String KINESIS_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/pipe-role";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamTargetReceivesTheRenderedTemplateUnderThePartitionKeyReadOffTheEvent() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceName = "pipe-kin-src-" + suffix;
|
||||
String streamName = "pipe-kin-stream-" + suffix;
|
||||
String pipeName = "pipe-kin-" + suffix;
|
||||
String sourceUrl = createQueue(sourceName);
|
||||
kinesis("CreateStream", "{\"StreamName\": \"" + streamName + "\", \"ShardCount\": 1}");
|
||||
try {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"Source": "arn:aws:sqs:us-east-1:000000000000:%s",
|
||||
"Target": "arn:aws:kinesis:us-east-1:000000000000:stream/%s",
|
||||
"RoleArn": "%s",
|
||||
"TargetParameters": {
|
||||
"InputTemplate": "{\\"t\\": <$.body.k>}",
|
||||
"KinesisStreamParameters": {
|
||||
"PartitionKey": "$.body.k"
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(sourceName, streamName, ROLE))
|
||||
.when()
|
||||
.post("/v1/pipes/" + pipeName)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.formParam("Action", "SendMessage")
|
||||
.formParam("QueueUrl", sourceUrl)
|
||||
.formParam("MessageBody", "{\"k\":\"key1\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
JsonPath record = readFirstRecord(streamName);
|
||||
assertEquals("key1", record.getString("Records[0].PartitionKey"));
|
||||
assertEquals("{\"t\": \"key1\"}", new String(
|
||||
Base64.getDecoder().decode(record.getString("Records[0].Data")), StandardCharsets.UTF_8));
|
||||
} finally {
|
||||
given().when().delete("/v1/pipes/" + pipeName);
|
||||
deleteQueue(sourceUrl);
|
||||
kinesis("DeleteStream", "{\"StreamName\": \"" + streamName + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPipeForAKinesisTargetWithoutTargetParametersIsRefusedWithTheFieldList() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceName = "pipe-kin-src-" + suffix;
|
||||
String pipeName = "pipe-kin-refused-" + suffix;
|
||||
String sourceUrl = createQueue(sourceName);
|
||||
try {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"Source": "arn:aws:sqs:us-east-1:000000000000:%s",
|
||||
"Target": "arn:aws:kinesis:us-east-1:000000000000:stream/any-stream",
|
||||
"RoleArn": "%s"
|
||||
}
|
||||
""".formatted(sourceName, ROLE))
|
||||
.when()
|
||||
.post("/v1/pipes/" + pipeName)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("{\"ValidationErrorFields\":[{\"Name\":"
|
||||
+ "\"TargetParameters.KinesisStreamParameters\","
|
||||
+ "\"Message\":\"Missing required target parameter.\"}]}"))
|
||||
.body("fieldList.size()", equalTo(1))
|
||||
.body("fieldList[0].name", equalTo("TargetParameters.KinesisStreamParameters"))
|
||||
.body("fieldList[0].message", equalTo("Missing required target parameter."));
|
||||
} finally {
|
||||
given().when().delete("/v1/pipes/" + pipeName);
|
||||
deleteQueue(sourceUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private static Response kinesis(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202." + action)
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static JsonPath readFirstRecord(String streamName) {
|
||||
return PipesTargetWaits.awaitTarget("a record in stream " + streamName, () -> {
|
||||
String iterator = kinesis("GetShardIterator", "{\"StreamName\": \"" + streamName
|
||||
+ "\", \"ShardId\": \"shardId-000000000000\", \"ShardIteratorType\": \"TRIM_HORIZON\"}")
|
||||
.then().statusCode(200).extract().jsonPath().getString("ShardIterator");
|
||||
return kinesis("GetRecords", "{\"ShardIterator\": \"" + iterator + "\"}")
|
||||
.then().statusCode(200).extract().jsonPath();
|
||||
}, result -> !result.getList("Records").isEmpty());
|
||||
}
|
||||
|
||||
private static String createQueue(String name) {
|
||||
return given()
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.formParam("Action", "CreateQueue")
|
||||
.formParam("QueueName", name)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200).extract().xmlPath()
|
||||
.getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
|
||||
}
|
||||
|
||||
private static void deleteQueue(String queueUrl) {
|
||||
given()
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.formParam("Action", "DeleteQueue")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ 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.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
@@ -33,6 +34,7 @@ class PipesServiceTest {
|
||||
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 KINESIS_TARGET = "arn:aws:kinesis:us-east-1:000000000000:stream/target-stream";
|
||||
private static final String PIPE_ROLE = "arn:aws:iam::000000000000:role/role";
|
||||
|
||||
private AccountAwareStorageBackend<Pipe> storage;
|
||||
@@ -172,6 +174,174 @@ class PipesServiceTest {
|
||||
assertFields(ex, "TargetParameters.SqsQueueParameters", "Missing required target parameter.");
|
||||
}
|
||||
|
||||
private static JsonNode kinesisParameters(String partitionKey) {
|
||||
ObjectNode tp = MAPPER.createObjectNode();
|
||||
tp.putObject("KinesisStreamParameters").put("PartitionKey", partitionKey);
|
||||
return tp;
|
||||
}
|
||||
|
||||
private Pipe createKinesisPipe(JsonNode targetParameters) {
|
||||
return pipesService.createPipe("kinesis-pipe", SQS_SOURCE, KINESIS_TARGET, PIPE_ROLE,
|
||||
null, null, null, null, targetParameters, null, null, "us-east-1");
|
||||
}
|
||||
|
||||
private static final String MISSING_BLOCK = "Missing required target parameter.";
|
||||
private static final String CROSS_ACCOUNT = "Creating cross-account pipe is not permitted.";
|
||||
|
||||
private void assertSchemaError(JsonNode targetParameters, String message) {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> createKinesisPipe(targetParameters));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
assertEquals(message, ex.getMessage());
|
||||
assertNull(ex.getExtendedData());
|
||||
}
|
||||
|
||||
private static JsonNode partitionKeyOf(JsonNode value) {
|
||||
ObjectNode tp = MAPPER.createObjectNode();
|
||||
tp.putObject("KinesisStreamParameters").set("PartitionKey", value);
|
||||
return tp;
|
||||
}
|
||||
|
||||
private AwsException createKinesisPipeTo(String target, JsonNode targetParameters) {
|
||||
return assertThrows(AwsException.class, () -> pipesService.createPipe("kinesis-pipe", SQS_SOURCE, target,
|
||||
PIPE_ROLE, null, null, null, null, targetParameters, null, null, "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisTargetWithoutKinesisStreamParametersIsRefused() throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> createKinesisPipe(null));
|
||||
assertFields(ex, "TargetParameters.KinesisStreamParameters", MISSING_BLOCK);
|
||||
|
||||
ex = assertThrows(AwsException.class,
|
||||
() -> createKinesisPipe(MAPPER.createObjectNode().put("InputTemplate", "x")));
|
||||
assertFields(ex, "TargetParameters.KinesisStreamParameters", MISSING_BLOCK);
|
||||
|
||||
ObjectNode nullBlock = MAPPER.createObjectNode();
|
||||
nullBlock.putNull("KinesisStreamParameters");
|
||||
ex = assertThrows(AwsException.class, () -> createKinesisPipe(nullBlock));
|
||||
assertFields(ex, "TargetParameters.KinesisStreamParameters", MISSING_BLOCK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisPartitionKeyAbsentIsASchemaError() {
|
||||
assertSchemaError(MAPPER.createObjectNode().set("KinesisStreamParameters", MAPPER.createObjectNode()),
|
||||
"[object has missing required properties ([\"PartitionKey\"])]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisPartitionKeyOfAnotherJsonTypeIsASchemaError() {
|
||||
JsonNodeFactory f = JsonNodeFactory.instance;
|
||||
Map<String, JsonNode> byType = new LinkedHashMap<>();
|
||||
byType.put("null", f.nullNode());
|
||||
byType.put("integer", f.numberNode(5));
|
||||
byType.put("number", f.numberNode(1.5));
|
||||
byType.put("boolean", f.booleanNode(true));
|
||||
byType.put("object", f.objectNode());
|
||||
byType.put("array", f.arrayNode());
|
||||
for (Map.Entry<String, JsonNode> entry : byType.entrySet()) {
|
||||
assertSchemaError(partitionKeyOf(entry.getValue()), "[instance type (" + entry.getKey()
|
||||
+ ") does not match any allowed primitive type (allowed: [\"string\"])]");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisPartitionKeyIsCountedInCodePoints() {
|
||||
String tooLong = "a".repeat(257);
|
||||
assertSchemaError(kinesisParameters(tooLong),
|
||||
"[string \"" + tooLong + "\" is too long (length: 257, maximum allowed: 256)]");
|
||||
|
||||
assertNotNull(createKinesisPipe(kinesisParameters("a".repeat(256))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisPartitionKeyOf200EmojiIsAccepted() {
|
||||
assertNotNull(createKinesisPipe(kinesisParameters("\uD83D\uDE00".repeat(200))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisTargetThatIsNotAPlainStreamArnIsRefused() throws Exception {
|
||||
for (String target : List.of(
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/s/consumer/c:1700000000",
|
||||
"arn:aws:kinesis:us-east-1:000000000000:s",
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/")) {
|
||||
assertFields(createKinesisPipeTo(target, kinesisParameters("k")),
|
||||
"Target", "Invalid pipe target ARN");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisTargetInAnotherAccountIsRefused() throws Exception {
|
||||
assertFields(createKinesisPipeTo("arn:aws:kinesis:us-east-1:111111111111:stream/s", kinesisParameters("k")),
|
||||
"Target", CROSS_ACCOUNT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisTargetErrorsComeBeforeTheMissingBlockAndThePartitionKeyPath() throws Exception {
|
||||
String otherAccount = "arn:aws:kinesis:us-east-1:111111111111:stream/s";
|
||||
String consumer = "arn:aws:kinesis:us-east-1:000000000000:stream/s/consumer/c:1700000000";
|
||||
|
||||
assertFields(createKinesisPipeTo(otherAccount, null),
|
||||
"Target", CROSS_ACCOUNT, "TargetParameters.KinesisStreamParameters", MISSING_BLOCK);
|
||||
assertFields(createKinesisPipeTo(consumer, null),
|
||||
"Target", "Invalid pipe target ARN", "TargetParameters.KinesisStreamParameters", MISSING_BLOCK);
|
||||
assertFields(createKinesisPipeTo(otherAccount, kinesisParameters("$.a b")),
|
||||
"Target", CROSS_ACCOUNT, "PartitionKey",
|
||||
"Invalid JSON path $.a b provided in the service target parameters.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSchemaErrorIsThrownAloneBeforeTheTargetChecks() {
|
||||
AwsException ex = createKinesisPipeTo(
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/s/consumer/c:1700000000",
|
||||
MAPPER.createObjectNode().set("KinesisStreamParameters", MAPPER.createObjectNode()));
|
||||
|
||||
assertEquals("[object has missing required properties ([\"PartitionKey\"])]", ex.getMessage());
|
||||
assertNull(ex.getExtendedData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisUpdateRunsTheSameChecks() {
|
||||
createKinesisPipe(kinesisParameters("k"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> pipesService.updatePipe("kinesis-pipe", null, null,
|
||||
null, null, null, null, MAPPER.createObjectNode().set("KinesisStreamParameters",
|
||||
MAPPER.createObjectNode()), null, "us-east-1"));
|
||||
assertEquals("[object has missing required properties ([\"PartitionKey\"])]", ex.getMessage());
|
||||
|
||||
AwsException crossAccount = assertThrows(AwsException.class, () -> pipesService.updatePipe("kinesis-pipe",
|
||||
"arn:aws:kinesis:us-east-1:111111111111:stream/s", null, null, null, null, null,
|
||||
kinesisParameters("k"), null, "us-east-1"));
|
||||
assertTrue(crossAccount.getMessage().contains(CROSS_ACCOUNT), crossAccount.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"$.body[", "$.a b", "$.", "$..a", "$.a.*", "$.a[-1]"})
|
||||
void kinesisPartitionKeyThatStartsWithADollarDotButIsNotAPathIsRefused(String value) throws Exception {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> createKinesisPipe(kinesisParameters(value)));
|
||||
assertFields(ex, "PartitionKey",
|
||||
"Invalid JSON path " + value + " provided in the service target parameters.");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"x", "", "$.a[0]", "$.a[*]", "$.a-b", "$.a/b", "$", "$x", "$[0]", "$['a']", "a$.b"})
|
||||
void kinesisPartitionKeyThatIsAPathOrNotPathLikeIsAccepted(String value) {
|
||||
assertNotNull(createKinesisPipe(kinesisParameters(value)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisUpdateWithOnlyTargetParametersIsCheckedAgainstTheStoredTarget() throws Exception {
|
||||
createKinesisPipe(kinesisParameters("k"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> pipesService.updatePipe("kinesis-pipe", null, null,
|
||||
null, null, null, null, kinesisParameters("$.a["), null, "us-east-1"));
|
||||
assertFields(ex, "PartitionKey", "Invalid JSON path $.a[ provided in the service target parameters.");
|
||||
|
||||
AwsException missing = assertThrows(AwsException.class, () -> pipesService.updatePipe("kinesis-pipe", null,
|
||||
null, null, null, null, null, MAPPER.createObjectNode().put("InputTemplate", "x"), null,
|
||||
"us-east-1"));
|
||||
assertFields(missing, "TargetParameters.KinesisStreamParameters", "Missing required target parameter.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPipe() {
|
||||
Pipe pipe = pipesService.createPipe("test-pipe",
|
||||
|
||||
@@ -10,7 +10,6 @@ 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 {
|
||||
@@ -19,7 +18,7 @@ class PipesSqsTargetIntegrationTest {
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/pipe-role";
|
||||
|
||||
@Test
|
||||
void fifoTargetReceivesTheGroupAndDeduplicationIdsReadOffTheEvent() throws Exception {
|
||||
void fifoTargetReceivesTheGroupAndDeduplicationIdsReadOffTheEvent() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceName = "pipe-sqs-src-" + suffix;
|
||||
String targetName = "pipe-sqs-fifo-" + suffix + ".fifo";
|
||||
@@ -59,9 +58,6 @@ class PipesSqsTargetIntegrationTest {
|
||||
.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"));
|
||||
@@ -121,25 +117,19 @@ class PipesSqsTargetIntegrationTest {
|
||||
.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 XmlPath receive(String queueUrl) {
|
||||
return PipesTargetWaits.awaitTarget("a message in " + queueUrl, () -> 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(),
|
||||
result -> !result.getList("ReceiveMessageResponse.ReceiveMessageResult.Message").isEmpty());
|
||||
}
|
||||
|
||||
private static String attribute(XmlPath message, String name) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.ServiceRegistry;
|
||||
import io.floci.aws.services.eventbridge.EventBridgeService;
|
||||
import io.floci.aws.services.kinesis.KinesisService;
|
||||
import io.floci.aws.services.lambda.LambdaService;
|
||||
import io.floci.aws.services.lambda.model.InvocationType;
|
||||
import io.floci.aws.services.lambda.model.InvokeResult;
|
||||
@@ -41,11 +42,13 @@ 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 STREAM_ARN = "arn:aws:kinesis:eu-west-1:111111111111:stream/target-stream";
|
||||
private static final String BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-bus/orders-bus";
|
||||
|
||||
@Mock private LambdaService lambdaService;
|
||||
@Mock private SqsService sqsService;
|
||||
@Mock private SnsService snsService;
|
||||
@Mock private KinesisService kinesisService;
|
||||
@Mock private EventBridgeService eventBridgeService;
|
||||
@Mock private StepFunctionsService stepFunctionsService;
|
||||
@Mock private RedshiftDataTargetSubmitter redshiftSubmitter;
|
||||
@@ -58,7 +61,7 @@ class PipesTargetInvokerTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
invoker = new PipesTargetInvoker(lambdaService, sqsService, snsService,
|
||||
invoker = new PipesTargetInvoker(lambdaService, sqsService, snsService, kinesisService,
|
||||
eventBridgeService, stepFunctionsService, redshiftSubmitter, redshiftAuthorizer, serviceRegistry,
|
||||
MAPPER, config);
|
||||
}
|
||||
@@ -320,6 +323,90 @@ class PipesTargetInvokerTest {
|
||||
verifyNoInteractions(sqsService);
|
||||
}
|
||||
|
||||
private Pipe kinesisPipe(String partitionKey, String inputTemplate) {
|
||||
ObjectNode tp = MAPPER.createObjectNode();
|
||||
if (partitionKey != null) {
|
||||
tp.putObject("KinesisStreamParameters").put("PartitionKey", partitionKey);
|
||||
}
|
||||
if (inputTemplate != null) {
|
||||
tp.put("InputTemplate", inputTemplate);
|
||||
}
|
||||
return createPipe(STREAM_ARN, tp);
|
||||
}
|
||||
|
||||
private void verifyKinesisPut(String data, String partitionKey) {
|
||||
verify(kinesisService).putRecordForAccount(eq("111111111111"), eq("target-stream"),
|
||||
eq(data.getBytes(StandardCharsets.UTF_8)), eq(partitionKey), eq("eu-west-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesis_literalPartitionKeyAndEventDataReachTheStreamTheArnNames() {
|
||||
invoker.invoke(kinesisPipe("pk", null), "{\"a\":1}", "us-east-1");
|
||||
|
||||
verifyKinesisPut("{\"a\":1}", "pk");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesis_pathPartitionKeyReadsTheEventBeforeTheTemplateRenders() {
|
||||
invoker.invoke(kinesisPipe("$.body.k", "{\"t\": <$.body.k>}"), "{\"body\":{\"k\":\"key1\"}}",
|
||||
"us-east-1");
|
||||
|
||||
verifyKinesisPut("{\"t\": \"key1\"}", "key1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesis_aNumberAtThePathBecomesItsText() {
|
||||
invoker.invoke(kinesisPipe("$.body.k", null), "{\"body\":{\"k\":42}}", "us-east-1");
|
||||
|
||||
verifyKinesisPut("{\"body\":{\"k\":42}}", "42");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesis_aPathNamingNothingThrowsAndPutsNothing() {
|
||||
Pipe pipe = kinesisPipe("$.body.missing", null);
|
||||
|
||||
RuntimeException ex = assertThrows(RuntimeException.class,
|
||||
() -> invoker.invoke(pipe, "{\"body\":{\"k\":1}}", "us-east-1"));
|
||||
|
||||
assertTrue(ex.getMessage().contains("$.body.missing"), ex.getMessage());
|
||||
verifyNoInteractions(kinesisService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesis_anEmptyPartitionKeyThrowsAndPutsNothing() {
|
||||
Pipe pipe = kinesisPipe("", null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> invoker.invoke(pipe, "{\"a\":1}", "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("1 validation error detected: Value '' at 'records.1.member.partitionKey' failed to satisfy"
|
||||
+ " constraint: Member must have length greater than or equal to 1", ex.getMessage());
|
||||
verifyNoInteractions(kinesisService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesis_aPathResolvingToMoreThan256CharactersThrowsAndPutsNothing() {
|
||||
String key = "a".repeat(257);
|
||||
Pipe pipe = kinesisPipe("$.body.k", null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> invoker.invoke(pipe, "{\"body\":{\"k\":\"" + key + "\"}}", "us-east-1"));
|
||||
|
||||
assertEquals("1 validation error detected: Value '" + key + "' at 'records.1.member.partitionKey'"
|
||||
+ " failed to satisfy constraint: Member must have length less than or equal to 256",
|
||||
ex.getMessage());
|
||||
verifyNoInteractions(kinesisService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesis_a256CharacterPartitionKeyIsWritten() {
|
||||
String key = "a".repeat(256);
|
||||
|
||||
invoker.invoke(kinesisPipe(key, null), "{\"a\":1}", "us-east-1");
|
||||
|
||||
verifyKinesisPut("{\"a\":1}", key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inputTemplate_missingFieldReplacesWithEmpty() {
|
||||
String region = "us-east-1";
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.floci.aws.services.pipes;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
final class PipesTargetWaits {
|
||||
|
||||
private static final Duration TIMEOUT = Duration.ofSeconds(10);
|
||||
private static final Duration POLL_INTERVAL = Duration.ofMillis(250);
|
||||
|
||||
private PipesTargetWaits() {
|
||||
}
|
||||
|
||||
static <T> T awaitTarget(String alias, Callable<T> read, Predicate<T> arrived) {
|
||||
return await(alias)
|
||||
.atMost(TIMEOUT)
|
||||
.pollInterval(POLL_INTERVAL)
|
||||
.until(read, arrived);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user