feat(pipes): add source polling and target invocation for EventBridge Pipes (#555)

This commit is contained in:
Christine Nguyen authored and GitHub committed 2026-04-22 23:36:48 -05:00
1 parent 2fb5a1f8aa
commit 51bf4f8480
20 files changed
+2517 -8

No files matched your search

@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyMan
import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoller;
import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;
import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller;
import io.github.hectorvent.floci.services.pipes.PipesService;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.quarkus.runtime.Quarkus;
@@ -42,6 +43,7 @@ public class EmulatorLifecycle {
private final SqsEventSourcePoller sqsPoller;
private final KinesisEventSourcePoller kinesisPoller;
private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;
private final PipesService pipesService;
@Inject
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
@@ -53,7 +55,8 @@ public class EmulatorLifecycle {
InitializationHooksRunner initializationHooksRunner,
SqsEventSourcePoller sqsPoller,
KinesisEventSourcePoller kinesisPoller,
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller) {
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,
PipesService pipesService) {
this.storageFactory = storageFactory;
this.serviceRegistry = serviceRegistry;
this.config = config;
@@ -65,6 +68,7 @@ public class EmulatorLifecycle {
this.sqsPoller = sqsPoller;
this.kinesisPoller = kinesisPoller;
this.dynamodbStreamsPoller = dynamodbStreamsPoller;
this.pipesService = pipesService;
}
void onStart(@Observes StartupEvent ignored) {
@@ -78,6 +82,7 @@ public class EmulatorLifecycle {
sqsPoller.startPersistedPollers();
kinesisPoller.startPersistedPollers();
dynamodbStreamsPoller.startPersistedPollers();
pipesService.startPersistedPollers();
if (!initializationHooksRunner.hasHooks(InitializationHook.START)) {
LOG.info("=== AWS Local Emulator Ready ===");
@@ -0,0 +1,321 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.services.dynamodb.DynamoDbStreamService;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.vertx.core.Vertx;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ApplicationScoped
public class PipesPoller {
private static final Logger LOG = Logger.getLogger(PipesPoller.class);
private static final long POLL_INTERVAL_MS = 1000;
private static final int DEFAULT_BATCH_SIZE = 10;
private final Vertx vertx;
private final SqsService sqsService;
private final KinesisService kinesisService;
private final DynamoDbStreamService dynamoDbStreamService;
private final PipesTargetInvoker targetInvoker;
private final ObjectMapper objectMapper;
private final String baseUrl;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, String> kinesisIterators = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, String> dynamoDbIterators = new ConcurrentHashMap<>();
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "pipes-poller");
t.setDaemon(true);
return t;
});
@Inject
public PipesPoller(Vertx vertx,
SqsService sqsService,
KinesisService kinesisService,
DynamoDbStreamService dynamoDbStreamService,
PipesTargetInvoker targetInvoker,
ObjectMapper objectMapper,
EmulatorConfig config) {
this.vertx = vertx;
this.sqsService = sqsService;
this.kinesisService = kinesisService;
this.dynamoDbStreamService = dynamoDbStreamService;
this.targetInvoker = targetInvoker;
this.objectMapper = objectMapper;
this.baseUrl = config.effectiveBaseUrl();
}
@PreDestroy
void shutdown() {
pollExecutor.shutdownNow();
timerIds.values().forEach(vertx::cancelTimer);
timerIds.clear();
LOG.info("PipesPoller shut down");
}
public void startPolling(Pipe pipe) {
String pipeKey = pipeKey(pipe);
if (timerIds.containsKey(pipeKey)) {
return;
}
long timerId = vertx.setPeriodic(POLL_INTERVAL_MS, id -> pollAndInvoke(pipe));
timerIds.put(pipeKey, timerId);
LOG.infov("Pipe {0}: started polling source {1}", pipe.getName(), pipe.getSource());
}
public void stopPolling(Pipe pipe) {
String pipeKey = pipeKey(pipe);
Long timerId = timerIds.remove(pipeKey);
if (timerId != null) {
vertx.cancelTimer(timerId);
kinesisIterators.remove(pipeKey);
dynamoDbIterators.remove(pipeKey);
LOG.infov("Pipe {0}: stopped polling", pipe.getName());
}
}
public boolean isPolling(Pipe pipe) {
return timerIds.containsKey(pipeKey(pipe));
}
private void pollAndInvoke(Pipe pipe) {
String pipeKey = pipeKey(pipe);
if (activePolls.putIfAbsent(pipeKey, Boolean.TRUE) != null) {
return;
}
pollExecutor.submit(() -> {
try {
if (pipe.getDesiredState() != DesiredState.RUNNING) {
return;
}
String sourceArn = pipe.getSource();
String region = extractRegionFromArn(sourceArn);
if (sourceArn.contains(":sqs:")) {
pollSqs(pipe, region);
} else if (sourceArn.contains(":kinesis:")) {
pollKinesis(pipe, region);
} else if (sourceArn.contains(":dynamodb:")) {
pollDynamoDbStreams(pipe, region);
} else {
LOG.warnv("Pipe {0}: unsupported source type: {1}", pipe.getName(), sourceArn);
}
} catch (Exception e) {
LOG.warnv("Pipe {0}: poll error: {1} ({2})",
pipe.getName(), e.getMessage(), e.getClass().getSimpleName());
} finally {
activePolls.remove(pipeKey);
}
});
}
private void pollSqs(Pipe pipe, String region) {
String queueUrl = AwsArnUtils.arnToQueueUrl(pipe.getSource(), baseUrl);
List<Message> messages = sqsService.receiveMessage(queueUrl, DEFAULT_BATCH_SIZE, 30, 0, region);
if (messages.isEmpty()) {
return;
}
LOG.infov("Pipe {0}: received {1} SQS message(s)", pipe.getName(), messages.size());
String eventJson = buildSqsEvent(messages, pipe);
targetInvoker.invoke(pipe, eventJson, region);
for (Message msg : messages) {
try {
sqsService.deleteMessage(queueUrl, msg.getReceiptHandle(), region);
} catch (Exception e) {
LOG.warnv("Pipe {0}: failed to delete SQS message {1}: {2}",
pipe.getName(), msg.getMessageId(), e.getMessage());
}
}
}
private void pollKinesis(Pipe pipe, String region) {
String pipeKey = pipeKey(pipe);
String streamName = extractResourceName(pipe.getSource());
String iterator = kinesisIterators.get(pipeKey);
if (iterator == null) {
iterator = initKinesisIterator(streamName, region);
if (iterator == null) return;
}
try {
@SuppressWarnings("unchecked")
Map<String, Object> result = kinesisService.getRecords(iterator, DEFAULT_BATCH_SIZE, region);
String nextIterator = (String) result.get("NextShardIterator");
if (nextIterator != null) {
kinesisIterators.put(pipeKey, nextIterator);
}
@SuppressWarnings("unchecked")
List<?> records = (List<?>) result.get("Records");
if (records == null || records.isEmpty()) {
return;
}
LOG.infov("Pipe {0}: received {1} Kinesis record(s)", pipe.getName(), records.size());
String eventJson = buildKinesisEvent(records, pipe, region);
targetInvoker.invoke(pipe, eventJson, region);
} catch (AwsException e) {
if ("ExpiredIteratorException".equals(e.getErrorCode())) {
kinesisIterators.remove(pipeKey);
}
throw e;
}
}
private String initKinesisIterator(String streamName, String region) {
try {
return kinesisService.getShardIterator(
streamName, "shardId-000000000000", "TRIM_HORIZON", null, null, region);
} catch (Exception e) {
LOG.warnv("Failed to get Kinesis shard iterator for {0}: {1}", streamName, e.getMessage());
return null;
}
}
private void pollDynamoDbStreams(Pipe pipe, String region) {
String pipeKey = pipeKey(pipe);
String streamArn = pipe.getSource();
String iterator = dynamoDbIterators.get(pipeKey);
if (iterator == null) {
iterator = initDynamoDbIterator(streamArn);
if (iterator == null) return;
}
try {
var result = dynamoDbStreamService.getRecords(iterator, DEFAULT_BATCH_SIZE);
String nextIterator = result.nextShardIterator();
if (nextIterator != null) {
dynamoDbIterators.put(pipeKey, nextIterator);
}
var records = result.records();
if (records == null || records.isEmpty()) {
return;
}
LOG.infov("Pipe {0}: received {1} DynamoDB Stream record(s)", pipe.getName(), records.size());
String eventJson = buildDynamoDbEvent(records, pipe, region);
targetInvoker.invoke(pipe, eventJson, region);
} catch (AwsException e) {
if ("ExpiredIteratorException".equals(e.getErrorCode()) ||
"TrimmedDataAccessException".equals(e.getErrorCode())) {
dynamoDbIterators.remove(pipeKey);
}
throw e;
}
}
private String initDynamoDbIterator(String streamArn) {
try {
return dynamoDbStreamService.getShardIterator(
streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null);
} catch (Exception e) {
LOG.warnv("Failed to get DynamoDB stream iterator for {0}: {1}", streamArn, e.getMessage());
return null;
}
}
// ──────────────────────────── Event Builders ────────────────────────────
private String buildSqsEvent(List<Message> messages, Pipe pipe) {
try {
var records = objectMapper.createArrayNode();
for (Message msg : messages) {
ObjectNode record = objectMapper.createObjectNode();
record.put("messageId", msg.getMessageId());
record.put("receiptHandle", msg.getReceiptHandle());
record.put("body", msg.getBody());
ObjectNode attrs = record.putObject("attributes");
attrs.put("ApproximateReceiveCount", String.valueOf(msg.getReceiveCount()));
attrs.put("SentTimestamp", String.valueOf(System.currentTimeMillis()));
record.putObject("messageAttributes");
record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : "");
record.put("eventSource", "aws:sqs");
record.put("eventSourceARN", pipe.getSource());
record.put("awsRegion", extractRegionFromArn(pipe.getSource()));
records.add(record);
}
ObjectNode root = objectMapper.createObjectNode();
root.set("Records", records);
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
return "{\"Records\":[]}";
}
}
private String buildKinesisEvent(List<?> records, Pipe pipe, String region) {
try {
var recordsArray = objectMapper.createArrayNode();
for (Object record : records) {
ObjectNode node = objectMapper.valueToTree(record);
ObjectNode eventRecord = objectMapper.createObjectNode();
eventRecord.put("eventSource", "aws:kinesis");
eventRecord.put("eventSourceARN", pipe.getSource());
eventRecord.put("awsRegion", region);
eventRecord.put("eventID", pipe.getSource() + ":" +
node.path("SequenceNumber").asText());
ObjectNode kinesis = eventRecord.putObject("kinesis");
kinesis.put("partitionKey", node.path("PartitionKey").asText());
kinesis.put("sequenceNumber", node.path("SequenceNumber").asText());
kinesis.put("approximateArrivalTimestamp",
node.path("ApproximateArrivalTimestamp").asDouble());
String data = node.path("Data").asText();
kinesis.put("data", data);
recordsArray.add(eventRecord);
}
ObjectNode root = objectMapper.createObjectNode();
root.set("Records", recordsArray);
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
return "{\"Records\":[]}";
}
}
private String buildDynamoDbEvent(List<?> records, Pipe pipe, String region) {
try {
var recordsArray = objectMapper.createArrayNode();
for (Object record : records) {
ObjectNode node = objectMapper.valueToTree(record);
node.put("eventSource", "aws:dynamodb");
node.put("eventSourceARN", pipe.getSource());
node.put("awsRegion", region);
recordsArray.add(node);
}
ObjectNode root = objectMapper.createObjectNode();
root.set("Records", recordsArray);
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
return "{\"Records\":[]}";
}
}
// ──────────────────────────── Utilities ────────────────────────────
private static String pipeKey(Pipe pipe) {
return pipe.getArn();
}
private static String extractRegionFromArn(String arn) {
String[] parts = arn.split(":");
return parts.length >= 4 ? parts[3] : "us-east-1";
}
private static String extractResourceName(String arn) {
int slashIdx = arn.lastIndexOf('/');
if (slashIdx >= 0) return arn.substring(slashIdx + 1);
int colonIdx = arn.lastIndexOf(':');
return colonIdx >= 0 ? arn.substring(colonIdx + 1) : arn;
}
}
@@ -27,12 +27,26 @@ public class PipesService implements TagHandler {
private final StorageBackend<String, Pipe> storage;
private final EmulatorConfig config;
private final PipesPoller poller;
@Inject
public PipesService(StorageFactory storageFactory, EmulatorConfig config) {
public PipesService(StorageFactory storageFactory, EmulatorConfig config, PipesPoller poller) {
this.storage = storageFactory.create("pipes", "pipes.json",
new TypeReference<Map<String, Pipe>>() {});
this.config = config;
this.poller = poller;
}
public void startPersistedPollers() {
List<Pipe> runningPipes = storage.scan(key -> true).stream()
.filter(pipe -> pipe.getCurrentState() == PipeState.RUNNING)
.toList();
for (Pipe pipe : runningPipes) {
poller.startPolling(pipe);
}
if (!runningPipes.isEmpty()) {
LOG.infov("Resumed polling for {0} pipe(s)", runningPipes.size());
}
}
public Pipe createPipe(String name, String source, String target, String roleArn,
@@ -83,6 +97,10 @@ public class PipesService implements TagHandler {
storage.put(key, pipe);
LOG.infov("Created pipe: {0}", name);
if (pipe.getCurrentState() == PipeState.RUNNING) {
poller.startPolling(pipe);
}
return pipe;
}
@@ -108,6 +126,11 @@ public class PipesService implements TagHandler {
if (desiredState != null) {
pipe.setDesiredState(desiredState);
pipe.setCurrentState(desiredState == DesiredState.RUNNING ? PipeState.RUNNING : PipeState.STOPPED);
if (desiredState == DesiredState.RUNNING) {
poller.startPolling(pipe);
} else {
poller.stopPolling(pipe);
}
}
if (enrichment != null) pipe.setEnrichment(enrichment);
if (sourceParameters != null) pipe.setSourceParameters(sourceParameters);
@@ -122,10 +145,10 @@ public class PipesService implements TagHandler {
public void deletePipe(String name, String region) {
String key = region + "::" + name;
if (storage.get(key).isEmpty()) {
throw new AwsException("NotFoundException",
"Pipe " + name + " does not exist.", 404);
}
Pipe pipe = storage.get(key)
.orElseThrow(() -> new AwsException("NotFoundException",
"Pipe " + name + " does not exist.", 404));
poller.stopPolling(pipe);
storage.delete(key);
LOG.infov("Deleted pipe: {0}", name);
}
@@ -152,6 +175,7 @@ public class PipesService implements TagHandler {
pipe.setCurrentState(PipeState.RUNNING);
pipe.setLastModifiedTime(Instant.now());
storage.put(key, pipe);
poller.startPolling(pipe);
LOG.infov("Started pipe: {0}", name);
return pipe;
}
@@ -162,6 +186,7 @@ public class PipesService implements TagHandler {
.orElseThrow(() -> new AwsException("NotFoundException",
"Pipe " + name + " does not exist.", 404));
poller.stopPolling(pipe);
pipe.setDesiredState(DesiredState.STOPPED);
pipe.setCurrentState(PipeState.STOPPED);
pipe.setLastModifiedTime(Instant.now());
@@ -0,0 +1,116 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@ApplicationScoped
public class PipesTargetInvoker {
private static final Logger LOG = Logger.getLogger(PipesTargetInvoker.class);
private final LambdaService lambdaService;
private final SqsService sqsService;
private final SnsService snsService;
private final EventBridgeService eventBridgeService;
private final StepFunctionsService stepFunctionsService;
private final ObjectMapper objectMapper;
private final String baseUrl;
@Inject
public PipesTargetInvoker(LambdaService lambdaService,
SqsService sqsService,
SnsService snsService,
EventBridgeService eventBridgeService,
StepFunctionsService stepFunctionsService,
ObjectMapper objectMapper,
EmulatorConfig config) {
this.lambdaService = lambdaService;
this.sqsService = sqsService;
this.snsService = snsService;
this.eventBridgeService = eventBridgeService;
this.stepFunctionsService = stepFunctionsService;
this.objectMapper = objectMapper;
this.baseUrl = config.effectiveBaseUrl();
}
public void invoke(Pipe pipe, String payload, String region) {
String targetArn = pipe.getTarget();
try {
if (targetArn.contains(":lambda:") || targetArn.contains(":function:")) {
invokeLambda(targetArn, payload, region);
} else if (targetArn.contains(":sqs:")) {
invokeSqs(targetArn, payload);
} else if (targetArn.contains(":sns:")) {
invokeSns(targetArn, payload, region);
} else if (targetArn.contains(":events:")) {
invokeEventBridge(targetArn, payload, region);
} else if (targetArn.contains(":states:")) {
invokeStepFunctions(targetArn, payload, region);
} else {
LOG.warnv("Pipe {0}: unsupported target ARN type: {1}", pipe.getName(), targetArn);
}
} catch (Exception e) {
LOG.warnv("Pipe {0}: failed to deliver to target {1}: {2}",
pipe.getName(), targetArn, e.getMessage());
}
}
private void invokeLambda(String arn, String payload, String region) {
String fnName = arn.substring(arn.lastIndexOf(':') + 1);
String fnRegion = extractRegionFromArn(arn, region);
lambdaService.invoke(fnRegion, fnName, payload.getBytes(), InvocationType.RequestResponse);
LOG.debugv("Pipe delivered to Lambda: {0}", arn);
}
private void invokeSqs(String arn, String payload) {
String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl);
sqsService.sendMessage(queueUrl, payload, 0);
LOG.debugv("Pipe delivered to SQS: {0}", arn);
}
private void invokeSns(String arn, String payload, String region) {
String topicRegion = extractRegionFromArn(arn, region);
snsService.publish(arn, null, payload, "Pipes", topicRegion);
LOG.debugv("Pipe delivered to SNS: {0}", arn);
}
private void invokeEventBridge(String arn, String payload, String region) {
String busName = arn.substring(arn.lastIndexOf('/') + 1);
String ebRegion = extractRegionFromArn(arn, region);
Map<String, Object> entry = Map.of(
"EventBusName", busName,
"Source", "aws.pipes",
"DetailType", "PipeForwarded",
"Detail", payload
);
eventBridgeService.putEvents(List.of(entry), ebRegion);
LOG.debugv("Pipe delivered to EventBridge: {0}", arn);
}
private void invokeStepFunctions(String arn, String payload, String region) {
String sfnRegion = extractRegionFromArn(arn, region);
String executionName = "pipes-" + UUID.randomUUID();
stepFunctionsService.startExecution(arn, executionName, payload, sfnRegion);
LOG.debugv("Pipe delivered to Step Functions: {0}", arn);
}
private static String extractRegionFromArn(String arn, String defaultRegion) {
String[] parts = arn.split(":");
return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
}
}