Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(lambda): persist, validate and enforce event source mapping FilterCriteria (#3060)

Guilherme Scaranse5512db0e050c
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index a5a1cd3302..9510842dd6 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -765,6 +765,76 @@ use `ParallelizationFactor` instead, which is a separate field.
at a time regardless). Real parallel dispatch capped by
`MaximumConcurrency` is tracked as a follow-up.
+### FilterCriteria
+
+`CreateEventSourceMapping` and `UpdateEventSourceMapping` accept a
+`FilterCriteria` with up to 5 `Filters`, each carrying an event-pattern
+`Pattern`, using the same EventBridge pattern syntax as EventBridge Pipes.
+`GetEventSourceMapping` and `ListEventSourceMappings` echo it back when set and
+omit the field entirely when unset. Filters are **enforced** in the Kinesis,
+DynamoDB Streams, and SQS pollers: only matching records are delivered to the
+function.
+
+```bash
+aws lambda create-event-source-mapping \
+ --function-name my-function \
+ --event-source-arn $QUEUE_ARN \
+ --filter-criteria '{"Filters":[{"Pattern":"{\"body\":{\"type\":[\"order\"]}}"}]}' \
+ --endpoint-url $AWS_ENDPOINT_URL
+```
+
+A pattern addresses each record the way its source presents it, matching AWS:
+
+| Source | Filter key | Notes |
+|--------|-----------|-------|
+| SQS | `body` (+ `messageAttributes`, etc.) | A JSON body is matched structurally; a non-JSON body cannot satisfy an object pattern and is dropped. Other top-level record fields (e.g. `messageId`, `messageAttributes`) are also addressable. |
+| DynamoDB Streams | `dynamodb` (+ `eventName`, etc.) | Matches the AttributeValue-wrapped image directly. Numeric operators do not apply (AttributeValue numbers are JSON strings), matching AWS. |
+| Kinesis | `data` (+ `partitionKey`) | `data` is matched against the **base64-decoded** payload (the delivered event still carries `data` base64-encoded); `partitionKey` is the supported metadata key. |
+
+Non-matching records are consumed, not retried: Kinesis and DynamoDB Streams
+advance the shard iterator past them (a fully filtered batch still advances the
+checkpoint, so a shard never stalls), and SQS deletes filtered-out messages from
+the queue.
+
+Validation mirrors AWS and runs before the mapping is stored: each `Pattern`
+must be a JSON object whose field values are non-empty match arrays or nested
+objects, at most 5 `Filters`, and each `Pattern` at most 4096 characters:
+violations are rejected with `InvalidParameterValueException`. A `FilterCriteria`
+of `{}` or with an empty `Filters` array clears any existing filters.
+
+!!! note "Supported operators"
+ Filtering reuses Floci's shared EventBridge matcher (the same one EventBridge
+ Pipes uses). It supports exact match on a string, number or `null`, plus
+ `prefix`, `suffix`, `equals-ignore-case`, `exists`, `anything-but` (a string,
+ a non-empty array of strings and numbers, or a nested `prefix`), and `numeric`
+ comparison/value pairs using `=`, `>`, `>=`, `<`, `<=`. Patterns using only
+ these behave as on AWS.
+
+ A pattern is validated at `CreateEventSourceMapping` and
+ `UpdateEventSourceMapping` and rejected with `InvalidParameterValueException`
+ when the matcher could not satisfy it: an unknown operator, an operator AWS
+ documents that Floci does not implement (`cidr`, `wildcard`), more than one
+ operator in a single match element, a boolean literal, a wrong operand type,
+ or a malformed `numeric` sequence such as an odd-length array or a
+ non-numeric value. This is stricter than AWS, which accepts several of these.
+ The trade is deliberate: the pollers checkpoint past (Kinesis, DynamoDB) or
+ delete (SQS) any record a pattern fails to match, so a pattern that cannot
+ match destroys records rather than being inert, and create time is the last
+ point at which the caller can still act on it.
+
+ One matcher deviation remains and is not a validation error, because it
+ depends on the record rather than the pattern: event-value array intersection,
+ where AWS matches when the record's own field is itself an array and any
+ element satisfies the pattern, and Floci does not.
+
+!!! warning "Direct Lambda API only"
+ `FilterCriteria` is carried only by the direct Lambda
+ `CreateEventSourceMapping` / `UpdateEventSourceMapping` APIs (SDK, CLI,
+ Terraform). CloudFormation and SAM event-source-mapping resources do not yet
+ forward `FilterCriteria` (as they also do not forward `ScalingConfig` or
+ `DestinationConfig`); forwarding it through those paths is tracked as a
+ follow-up.
+
## Supported Runtimes
Any runtime that has an official AWS Lambda container image works with Floci (e.g. `nodejs22.x`, `python3.13`, `java21`, `go1.x`, `provided.al2023`).
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
index 0f46f82304..2d9ee7732e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
@@ -9,6 +9,8 @@ import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
+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;
@@ -18,6 +20,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
@@ -34,6 +37,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
private final LambdaFunctionStore functionStore;
private final EsmStore esmStore;
private final ObjectMapper objectMapper;
+ private final PipesFilterMatcher filterMatcher;
private final long pollIntervalMs;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
@@ -49,7 +53,8 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
LambdaFunctionStore functionStore,
EsmStore esmStore,
ObjectMapper objectMapper,
- EmulatorConfig config) {
+ EmulatorConfig config,
+ PipesFilterMatcher filterMatcher) {
this.vertx = vertx;
this.streamService = streamService;
this.executorService = executorService;
@@ -57,6 +62,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
this.esmStore = esmStore;
this.objectMapper = objectMapper;
this.pollIntervalMs = config.services().lambda().pollIntervalMs();
+ this.filterMatcher = filterMatcher;
}
public void startPersistedPollers() {
@@ -159,10 +165,31 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
return;
}
- LOG.infov("DynamoDB Streams ESM {0}: received {1} record(s), invoking {2}",
- esm.getUuid(), records.size(), esm.getFunctionName());
+ // Advance to the newest FETCHED record whenever the batch is disposed of, invoked or
+ // fully filtered out, so filtered-out records are consumed, not re-read forever. Leave
+ // the checkpoint unmoved only when an attempted invoke fails (the window retries).
+ String newestFetchedSeq = records.get(records.size() - 1).getSequenceNumber();
- String eventJson = buildDynamoDbEvent(records, esm);
+ List<DynamoDbStreamRecord> matched = records;
+ JsonNode filterParams = EsmFilterCriteriaUtils.matcherSourceParameters(objectMapper, esm.getFilterCriteria());
+ if (filterParams != null) {
+ List<JsonNode> filterNodes = new ArrayList<>(records.size());
+ for (DynamoDbStreamRecord rec : records) {
+ filterNodes.add(buildDynamoDbRecordNode(rec, esm));
+ }
+ matched = EsmFilterCriteriaUtils.selectMatched(
+ records, filterNodes, filterMatcher.applyFilterCriteria(filterNodes, filterParams));
+ }
+
+ if (matched.isEmpty()) {
+ advanceCheckpoint(esm, shardId, newestFetchedSeq);
+ return;
+ }
+
+ LOG.infov("DynamoDB Streams ESM {0}: delivering {1} of {2} record(s) to {3}",
+ esm.getUuid(), matched.size(), records.size(), esm.getFunctionName());
+
+ String eventJson = buildDynamoDbEvent(matched, esm);
InvokeResult invokeResult;
try {
invokeResult = executorService.invoke(fn, eventJson.getBytes(), InvocationType.RequestResponse);
@@ -176,9 +203,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
}
if (invokeResult.getFunctionError() == null) {
- String newestSeq = records.get(records.size() - 1).getSequenceNumber();
- esm.getShardSequenceNumbers().put(shardId, newestSeq);
- esmStore.saveForAccount(esm.getAccountId(), esm);
+ advanceCheckpoint(esm, shardId, newestFetchedSeq);
} else {
LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [{1}], records will be retried",
esm.getUuid(), invokeResult.getFunctionError());
@@ -196,32 +221,48 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
ObjectNode root = objectMapper.createObjectNode();
ArrayNode array = root.putArray("Records");
for (DynamoDbStreamRecord rec : records) {
- ObjectNode item = array.addObject();
- item.put("eventID", rec.getEventId());
- item.put("eventVersion", rec.getEventVersion());
- item.put("awsRegion", rec.getAwsRegion());
- item.put("eventName", rec.getEventName());
- item.put("eventSourceARN", esm.getEventSourceArn());
- item.put("eventSource", rec.getEventSource());
-
- ObjectNode dynamodb = item.putObject("dynamodb");
- dynamodb.put("StreamViewType", rec.getStreamViewType());
- dynamodb.put("SequenceNumber", rec.getSequenceNumber());
- dynamodb.put("SizeBytes", 100);
- dynamodb.put("ApproximateCreationDateTime", (double) rec.getApproximateCreationDateTime());
- if (rec.getKeys() != null) {
- dynamodb.set("Keys", rec.getKeys());
- }
- if (rec.getNewImage() != null) {
- dynamodb.set("NewImage", rec.getNewImage());
- }
- if (rec.getOldImage() != null) {
- dynamodb.set("OldImage", rec.getOldImage());
- }
+ array.add(buildDynamoDbRecordNode(rec, esm));
}
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
throw new RuntimeException("Failed to serialize DynamoDB Streams event", e);
}
}
+
+ /**
+ * Builds the single-record node: top-level {@code eventName}/metadata plus the {@code dynamodb} map
+ * with AttributeValue-wrapped images. This is both the delivery record shape and the exact structure a
+ * DynamoDB filter pattern matches against, so it serves the matcher unchanged. (Numeric operators
+ * naturally never match here because AttributeValue numbers are JSON strings, AWS parity for free.)
+ */
+ private ObjectNode buildDynamoDbRecordNode(DynamoDbStreamRecord rec, EventSourceMapping esm) {
+ ObjectNode item = objectMapper.createObjectNode();
+ item.put("eventID", rec.getEventId());
+ item.put("eventVersion", rec.getEventVersion());
+ item.put("awsRegion", rec.getAwsRegion());
+ item.put("eventName", rec.getEventName());
+ item.put("eventSourceARN", esm.getEventSourceArn());
+ item.put("eventSource", rec.getEventSource());
+
+ ObjectNode dynamodb = item.putObject("dynamodb");
+ dynamodb.put("StreamViewType", rec.getStreamViewType());
+ dynamodb.put("SequenceNumber", rec.getSequenceNumber());
+ dynamodb.put("SizeBytes", 100);
+ dynamodb.put("ApproximateCreationDateTime", (double) rec.getApproximateCreationDateTime());
+ if (rec.getKeys() != null) {
+ dynamodb.set("Keys", rec.getKeys());
+ }
+ if (rec.getNewImage() != null) {
+ dynamodb.set("NewImage", rec.getNewImage());
+ }
+ if (rec.getOldImage() != null) {
+ dynamodb.set("OldImage", rec.getOldImage());
+ }
+ return item;
+ }
+
+ private void advanceCheckpoint(EventSourceMapping esm, String shardId, String newestSeq) {
+ esm.getShardSequenceNumbers().put(shardId, newestSeq);
+ esmStore.saveForAccount(esm.getAccountId(), esm);
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaUtils.java b/src/main/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaUtils.java
new file mode 100644
index 0000000000..ba264015a3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaUtils.java
@@ -0,0 +1,61 @@
+package io.github.hectorvent.floci.services.lambda;
+
+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.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Helpers shared by the three Lambda event-source pollers to apply an event source mapping's
+ * {@link EventSourceMapping.FilterCriteria} through the existing {@code PipesFilterMatcher}.
+ */
+final class EsmFilterCriteriaUtils {
+
+ private EsmFilterCriteriaUtils() {
+ }
+
+ /**
+ * Re-wraps a stored {@link EventSourceMapping.FilterCriteria} as the
+ * {@code {"FilterCriteria":{"Filters":[{"Pattern":...}]}}} node that
+ * {@code PipesFilterMatcher.applyFilterCriteria} path-matches on. Returns {@code null} when no filters
+ * are configured; the matcher passes every record through for a {@code null} argument, so callers treat
+ * {@code null} as "filtering off" and skip building filter nodes entirely.
+ */
+ static JsonNode matcherSourceParameters(ObjectMapper mapper, EventSourceMapping.FilterCriteria criteria) {
+ if (criteria == null || criteria.getFilters() == null || criteria.getFilters().isEmpty()) {
+ return null;
+ }
+ ObjectNode wrapper = mapper.createObjectNode();
+ ArrayNode filters = wrapper.putObject("FilterCriteria").putArray("Filters");
+ for (EventSourceMapping.Filter filter : criteria.getFilters()) {
+ filters.addObject().put("Pattern", filter.getPattern());
+ }
+ return wrapper;
+ }
+
+ /**
+ * Maps the matcher's result back to the source records it corresponds to. {@code PipesFilterMatcher}
+ * preserves input order and returns the same {@link JsonNode} instances it was given, so a
+ * reference-identity two-pointer walk recovers the matched source records without relying on any content
+ * field, robust to duplicate payloads and to filter nodes that deliberately omit a correlating key.
+ *
+ * @param sources the source records, in the same order their filter nodes were built
+ * @param filterNodes the per-record filter nodes passed to the matcher, index-aligned with {@code sources}
+ * @param matchedNodes the matcher's returned subset (same instances, input order)
+ */
+ static <T> List<T> selectMatched(List<T> sources, List<JsonNode> filterNodes, List<JsonNode> matchedNodes) {
+ List<T> matched = new ArrayList<>(matchedNodes.size());
+ int j = 0;
+ for (int i = 0; i < filterNodes.size() && j < matchedNodes.size(); i++) {
+ if (filterNodes.get(i) == matchedNodes.get(j)) {
+ matched.add(sources.get(i));
+ j++;
+ }
+ }
+ return matched;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java
index b9d951ed35..f9e724eafc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.lambda;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -14,12 +16,15 @@ import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
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.nio.charset.StandardCharsets;
+import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
@@ -39,6 +44,7 @@ public class KinesisEventSourcePoller implements Resettable {
private final EsmStore esmStore;
private final long pollIntervalMs;
private final ObjectMapper objectMapper;
+ private final PipesFilterMatcher filterMatcher;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(r -> {
@@ -52,7 +58,8 @@ public class KinesisEventSourcePoller implements Resettable {
LambdaExecutorService executorService,
LambdaFunctionStore functionStore,
EsmStore esmStore, EmulatorConfig config,
- ObjectMapper objectMapper) {
+ ObjectMapper objectMapper,
+ PipesFilterMatcher filterMatcher) {
this.vertx = vertx;
this.kinesisService = kinesisService;
this.executorService = executorService;
@@ -60,6 +67,7 @@ public class KinesisEventSourcePoller implements Resettable {
this.esmStore = esmStore;
this.pollIntervalMs = config.services().lambda().pollIntervalMs();
this.objectMapper = objectMapper;
+ this.filterMatcher = filterMatcher;
}
public void startPersistedPollers() {
@@ -102,7 +110,8 @@ public class KinesisEventSourcePoller implements Resettable {
if (timerId != null) vertx.cancelTimer(timerId);
}
- private void pollAndInvoke(EventSourceMapping esm) {
+ /** Package-private (not private) only so unit tests can drive a single poll directly. */
+ void pollAndInvoke(EventSourceMapping esm) {
if (activePolls.putIfAbsent(esm.getUuid(), Boolean.TRUE) != null) return;
pollExecutor.submit(() -> {
try {
@@ -124,25 +133,48 @@ public class KinesisEventSourcePoller implements Resettable {
Map<String, Object> result = kinesisService.getRecords(iterator, esm.getBatchSize(), esm.getRegion());
List<KinesisRecord> records = (List<KinesisRecord>) result.get("Records");
- if (!records.isEmpty()) {
- String eventJson = buildKinesisEvent(records, esm, shard.getShardId());
- InvokeResult invokeResult;
- try {
- invokeResult = executorService.invoke(fn, eventJson.getBytes(), InvocationType.RequestResponse);
- } catch (AwsException e) {
- if ("TooManyRequestsException".equals(e.getErrorCode())) {
- LOG.infov("Kinesis ESM {0}: function {1} throttled, shard iterator not advanced",
- esm.getUuid(), fn.getFunctionName());
- continue;
- }
- throw e;
+ if (records.isEmpty()) {
+ continue;
+ }
+
+ // The checkpoint must advance to the newest FETCHED record whenever the batch is
+ // disposed of, whether by a successful invoke or because a filter matched nothing,
+ // so filtered-out records are consumed, not re-read forever. Only an invoke that was
+ // attempted and failed leaves the checkpoint unmoved (the whole window retries).
+ String newestFetchedSeq = records.get(records.size() - 1).getSequenceNumber();
+
+ List<KinesisRecord> matched = records;
+ JsonNode filterParams = EsmFilterCriteriaUtils.matcherSourceParameters(objectMapper, esm.getFilterCriteria());
+ if (filterParams != null) {
+ List<JsonNode> filterNodes = new ArrayList<>(records.size());
+ for (KinesisRecord rec : records) {
+ filterNodes.add(buildKinesisFilterNode(rec));
}
+ matched = EsmFilterCriteriaUtils.selectMatched(
+ records, filterNodes, filterMatcher.applyFilterCriteria(filterNodes, filterParams));
+ }
- if (invokeResult.getFunctionError() == null) {
- String newestSeq = records.get(records.size() - 1).getSequenceNumber();
- esm.getShardSequenceNumbers().put(shard.getShardId(), newestSeq);
- esmStore.saveForAccount(esm.getAccountId(), esm);
+ if (matched.isEmpty()) {
+ // Whole batch filtered out: consume it (advance past), do not invoke, do not retry.
+ advanceCheckpoint(esm, shard.getShardId(), newestFetchedSeq);
+ continue;
+ }
+
+ String eventJson = buildKinesisEvent(matched, esm, shard.getShardId());
+ InvokeResult invokeResult;
+ try {
+ invokeResult = executorService.invoke(fn, eventJson.getBytes(), InvocationType.RequestResponse);
+ } catch (AwsException e) {
+ if ("TooManyRequestsException".equals(e.getErrorCode())) {
+ LOG.infov("Kinesis ESM {0}: function {1} throttled, shard iterator not advanced",
+ esm.getUuid(), fn.getFunctionName());
+ continue;
}
+ throw e;
+ }
+
+ if (invokeResult.getFunctionError() == null) {
+ advanceCheckpoint(esm, shard.getShardId(), newestFetchedSeq);
}
}
} catch (Exception e) {
@@ -183,6 +215,35 @@ public class KinesisEventSourcePoller implements Resettable {
}
}
+ /**
+ * The record view a Kinesis filter pattern matches against. AWS decodes the base64 {@code data} and
+ * filters the <em>top-level</em> {@code data} key (plus metadata such as {@code partitionKey}), not the
+ * nested/base64 invocation envelope produced by {@link #buildKinesisEvent}. This is a separate,
+ * filter-only view: {@code data} is the base64-decoded payload, parsed as JSON when it parses, else kept
+ * as the decoded string (an object pattern then won't match it: AWS drops on format mismatch).
+ */
+ private JsonNode buildKinesisFilterNode(KinesisRecord rec) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("partitionKey", rec.getPartitionKey());
+ String decoded = new String(rec.getData(), StandardCharsets.UTF_8);
+ try {
+ JsonNode parsed = objectMapper.readTree(decoded);
+ if (parsed == null || parsed.isMissingNode()) {
+ node.put("data", decoded);
+ } else {
+ node.set("data", parsed);
+ }
+ } catch (JsonProcessingException e) {
+ node.put("data", decoded);
+ }
+ return node;
+ }
+
+ private void advanceCheckpoint(EventSourceMapping esm, String shardId, String newestSeq) {
+ esm.getShardSequenceNumbers().put(shardId, newestSeq);
+ esmStore.saveForAccount(esm.getAccountId(), esm);
+ }
+
private static String streamNameFromArn(String arn) {
return arn.substring(arn.lastIndexOf("/") + 1);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
index 3cbddad8dc..f60d02be7b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
@@ -381,6 +381,15 @@ public class LambdaController {
ObjectNode scaling = node.putObject("ScalingConfig");
scaling.put("MaximumConcurrency", maxConcurrency.intValue());
}
+ // Only emit FilterCriteria when filters are configured: AWS omits the field
+ // entirely (rather than returning null or an empty object) when no filter is set.
+ if (esm.getFilterCriteria() != null && !esm.getFilterCriteria().getFilters().isEmpty()) {
+ ObjectNode filterCriteria = node.putObject("FilterCriteria");
+ ArrayNode filters = filterCriteria.putArray("Filters");
+ for (EventSourceMapping.Filter filter : esm.getFilterCriteria().getFilters()) {
+ filters.addObject().put("Pattern", filter.getPattern());
+ }
+ }
@SuppressWarnings("unchecked")
Map<String, Object> result = objectMapper.convertValue(node, Map.class);
return result;
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
index ff052e8925..40f8a3f848 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.lambda;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+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.core.common.AwsException;
@@ -98,6 +101,7 @@ public class LambdaService implements ResourceProvider {
private final Ec2Service ec2Service;
/** Null in the constructors tests use, exactly as the other optional collaborators above are. */
private final CustomResourceLiveness customResourceLiveness;
+ private final ObjectMapper objectMapper;
private Map<String, Integer> versionCounters = new ConcurrentHashMap<>();
private Map<String, FunctionEventInvokeConfig> eventInvokeConfigs = new ConcurrentHashMap<>();
/**
@@ -169,6 +173,7 @@ public class LambdaService implements ResourceProvider {
this.layerService = null;
this.ec2Service = null;
this.customResourceLiveness = null;
+ this.objectMapper = new ObjectMapper();
}
@Inject
@@ -190,7 +195,8 @@ public class LambdaService implements ResourceProvider {
StorageFactory storageFactory,
LambdaLayerService layerService,
Ec2Service ec2Service,
- CustomResourceLiveness customResourceLiveness) {
+ CustomResourceLiveness customResourceLiveness,
+ ObjectMapper objectMapper) {
this.customResourceLiveness = customResourceLiveness;
this.functionStore = functionStore;
this.executorService = executorService;
@@ -210,6 +216,7 @@ public class LambdaService implements ResourceProvider {
this.storageFactory = storageFactory;
this.layerService = layerService;
this.ec2Service = ec2Service;
+ this.objectMapper = objectMapper;
}
// Real AWS validates a function's Layers eagerly at CreateFunction/UpdateFunctionConfiguration
@@ -1093,6 +1100,8 @@ public class LambdaService implements ResourceProvider {
EventSourceMapping.DestinationConfig destinationConfig = parseDestinationConfig(request);
+ EventSourceMapping.FilterCriteria filterCriteria = parseFilterCriteria(request, objectMapper);
+
StartingPositionSpec startingPosition = parseStartingPosition(request, eventSourceArn);
String queueUrl = eventSourceArn.contains(":sqs:") ? AwsArnUtils.arnToQueueUrl(eventSourceArn, config.effectiveBaseUrl()) : null;
@@ -1112,6 +1121,7 @@ public class LambdaService implements ResourceProvider {
esm.setFunctionResponseTypes(functionResponseTypes);
esm.setBisectBatchOnFunctionError(bisectBatchOnFunctionError);
esm.setDestinationConfig(destinationConfig);
+ esm.setFilterCriteria(filterCriteria);
esm.setStartingPosition(startingPosition.position());
esm.setStartingPositionTimestamp(startingPosition.timestampMillis());
esm.setLastModified(System.currentTimeMillis());
@@ -1149,6 +1159,228 @@ public class LambdaService implements ResourceProvider {
return destinationConfig;
}
+ /**
+ * Parses and validates {@code FilterCriteria} from a create/update request. Mirrors
+ * {@link #parseDestinationConfig} in shape and error behavior; static (with the mapper passed in) so the
+ * validation can be unit-tested without constructing the service.
+ *
+ * <p>AWS rejects invalid filter patterns at create/update time. Because the pollers silently drop, and
+ * checkpoint past (Kinesis/DynamoDB) or delete (SQS), any record a pattern fails to match, an unvalidated
+ * malformed pattern would become silent data loss. Patterns are therefore validated to be well-formed JSON
+ * objects here, before persistence. Returns {@code null} (filtering off) when {@code FilterCriteria} is
+ * absent, an empty object, or has an empty {@code Filters} array: AWS treats an empty object as the
+ * removal operation.
+ */
+ static EventSourceMapping.FilterCriteria parseFilterCriteria(Map<String, Object> request, ObjectMapper objectMapper) {
+ Object raw = request.get("FilterCriteria");
+ if (raw == null) {
+ return null;
+ }
+ if (!(raw instanceof Map<?, ?> criteriaMap)) {
+ throw new AwsException("InvalidParameterValueException",
+ "FilterCriteria must be a JSON object", 400);
+ }
+ Object rawFilters = criteriaMap.get("Filters");
+ if (rawFilters == null) {
+ return null;
+ }
+ if (!(rawFilters instanceof List<?> filterList)) {
+ throw new AwsException("InvalidParameterValueException",
+ "FilterCriteria.Filters must be a JSON array", 400);
+ }
+ if (filterList.isEmpty()) {
+ return null;
+ }
+ if (filterList.size() > 5) {
+ throw new AwsException("InvalidParameterValueException",
+ "FilterCriteria.Filters may contain a maximum of 5 filters", 400);
+ }
+ List<EventSourceMapping.Filter> filters = new ArrayList<>();
+ for (Object rawFilter : filterList) {
+ if (!(rawFilter instanceof Map<?, ?> filterMap)) {
+ throw new AwsException("InvalidParameterValueException",
+ "Each FilterCriteria.Filters entry must be a JSON object", 400);
+ }
+ Object rawPattern = filterMap.get("Pattern");
+ if (!(rawPattern instanceof String pattern) || pattern.isBlank()) {
+ throw new AwsException("InvalidParameterValueException",
+ "Each filter must have a non-empty Pattern string", 400);
+ }
+ if (pattern.length() > 4096) {
+ throw new AwsException("InvalidParameterValueException",
+ "Filter Pattern must not exceed 4096 characters", 400);
+ }
+ JsonNode patternNode;
+ try {
+ patternNode = objectMapper.readTree(pattern);
+ } catch (JsonProcessingException e) {
+ // Only a JSON parse failure is client error (400). An unexpected runtime failure
+ // (e.g. a misconfigured mapper) must surface as a server error, not a misleading 400.
+ throw new AwsException("InvalidParameterValueException",
+ "Filter Pattern is not valid JSON", 400);
+ }
+ if (!patternNode.isObject()) {
+ throw new AwsException("InvalidParameterValueException",
+ "Filter Pattern must be a JSON object", 400);
+ }
+ validatePatternStructure(patternNode);
+ EventSourceMapping.Filter filter = new EventSourceMapping.Filter();
+ filter.setPattern(pattern);
+ filters.add(filter);
+ }
+ EventSourceMapping.FilterCriteria criteria = new EventSourceMapping.FilterCriteria();
+ criteria.setFilters(filters);
+ return criteria;
+ }
+
+ /** Match-array operators {@code PipesFilterMatcher} implements, with the operand shape each accepts. */
+ private static final Set<String> SUPPORTED_FILTER_OPERATORS =
+ Set.of("prefix", "suffix", "equals-ignore-case", "anything-but", "exists", "numeric");
+
+ /** Operators AWS documents that the matcher does not implement, rejected with a clearer message. */
+ private static final Set<String> UNIMPLEMENTED_FILTER_OPERATORS = Set.of("cidr", "wildcard");
+
+ /** Comparisons {@code matchesNumericFilter} understands. Anything else evaluates false for every record. */
+ private static final Set<String> NUMERIC_COMPARISONS = Set.of("=", ">", ">=", "<", "<=");
+
+ /**
+ * Validates the recursive shape of an EventBridge filter pattern: every field value must be either a
+ * non-empty match array (a leaf) or a nested object (recursed into). A scalar or empty-array value is a
+ * pattern the matcher can never satisfy, so, with enforcement active, it would silently drop every
+ * record; reject it at create/update instead.
+ *
+ * <p>Match-array elements are validated against the operator set the matcher implements. This does couple
+ * the validator to {@code PipesFilterMatcher}, which is deliberate: now that the pollers enforce filters,
+ * a pattern the matcher cannot satisfy is destructive rather than inert. A bad operand silently corrupts
+ * delivery instead of erroring, and the failure direction is not even consistent. {@code
+ * {"numeric":[">","abc"]}} coerces its operand to zero and matches every positive value, {@code
+ * {"numeric":[">"]}} matches every record because the comparison loop never runs, and an unknown operator
+ * matches nothing, so every record is checkpointed past or deleted. Failing at create/update is the only
+ * point where the caller can still act on it.
+ */
+ private static void validatePatternStructure(JsonNode node) {
+ for (Map.Entry<String, JsonNode> entry : node.properties()) {
+ JsonNode value = entry.getValue();
+ if (value.isArray()) {
+ if (value.isEmpty()) {
+ throw new AwsException("InvalidParameterValueException",
+ "Filter Pattern field '" + entry.getKey() + "' must have a non-empty match array", 400);
+ }
+ for (JsonNode element : value) {
+ validateMatchElement(entry.getKey(), element);
+ }
+ } else if (value.isObject()) {
+ validatePatternStructure(value);
+ } else {
+ throw new AwsException("InvalidParameterValueException",
+ "Filter Pattern field '" + entry.getKey() + "' must be an array or object", 400);
+ }
+ }
+ }
+
+ /**
+ * A match-array element is either a literal the matcher compares directly (string, number, or null for
+ * "absent") or a single-operator object. Two operators in one object is rejected because the matcher
+ * tests them in a fixed order and silently honours only the first.
+ */
+ private static void validateMatchElement(String field, JsonNode element) {
+ if (element.isTextual() || element.isNumber() || element.isNull()) {
+ return;
+ }
+ if (!element.isObject()) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' has an invalid match value: expected a string, number, null, or an operator object", 400);
+ }
+ List<String> operators = new ArrayList<>();
+ element.fieldNames().forEachRemaining(operators::add);
+ if (operators.size() != 1) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' must carry exactly one operator per match element, found " + operators.size(), 400);
+ }
+ String op = operators.get(0);
+ JsonNode operand = element.get(op);
+ if (UNIMPLEMENTED_FILTER_OPERATORS.contains(op)) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' uses operator '" + op + "', which Floci does not implement", 400);
+ }
+ if (!SUPPORTED_FILTER_OPERATORS.contains(op)) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' uses unknown operator '" + op + "'", 400);
+ }
+ switch (op) {
+ case "prefix", "suffix", "equals-ignore-case" -> requireTextual(field, op, operand);
+ case "exists" -> {
+ if (!operand.isBoolean()) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator 'exists' requires true or false", 400);
+ }
+ }
+ case "anything-but" -> validateAnythingBut(field, operand);
+ case "numeric" -> validateNumeric(field, operand);
+ default -> throw new IllegalStateException("unreachable operator " + op);
+ }
+ }
+
+ private static void requireTextual(String field, String op, JsonNode operand) {
+ if (!operand.isTextual()) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator '" + op + "' requires a string operand", 400);
+ }
+ }
+
+ /** {@code anything-but} accepts a string, a non-empty array of strings/numbers, or a nested prefix. */
+ private static void validateAnythingBut(String field, JsonNode operand) {
+ if (operand.isTextual()) {
+ return;
+ }
+ if (operand.isArray()) {
+ if (operand.isEmpty()) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator 'anything-but' requires a non-empty array", 400);
+ }
+ for (JsonNode v : operand) {
+ if (!v.isTextual() && !v.isNumber()) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator 'anything-but' accepts only strings and numbers", 400);
+ }
+ }
+ return;
+ }
+ if (operand.isObject()) {
+ List<String> inner = new ArrayList<>();
+ operand.fieldNames().forEachRemaining(inner::add);
+ if (inner.size() == 1 && "prefix".equals(inner.get(0))) {
+ requireTextual(field, "anything-but prefix", operand.get("prefix"));
+ return;
+ }
+ }
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator 'anything-but' requires a string, a non-empty array, or {\"prefix\": \"...\"}", 400);
+ }
+
+ /**
+ * {@code numeric} is a flat sequence of comparison/operand pairs. An odd length leaves a trailing
+ * comparison the matcher never evaluates, which makes the whole element match every record.
+ */
+ private static void validateNumeric(String field, JsonNode operand) {
+ if (!operand.isArray() || operand.isEmpty() || operand.size() % 2 != 0) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator 'numeric' requires comparison/value pairs, for example [\">\", 5]", 400);
+ }
+ for (int i = 0; i < operand.size(); i += 2) {
+ JsonNode comparison = operand.get(i);
+ if (!comparison.isTextual() || !NUMERIC_COMPARISONS.contains(comparison.asText())) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator 'numeric' has an invalid comparison at index " + i
+ + ": expected one of =, >, >=, <, <=", 400);
+ }
+ if (!operand.get(i + 1).isNumber()) {
+ throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field
+ + "' operator 'numeric' requires a numeric value at index " + (i + 1), 400);
+ }
+ }
+ }
+
/** A validated {@code StartingPosition} plus, for {@code AT_TIMESTAMP}, its epoch-millis instant. */
private record StartingPositionSpec(String position, Long timestampMillis) {}
@@ -1306,6 +1538,12 @@ public class LambdaService implements ResourceProvider {
esm.setDestinationConfig(parseDestinationConfig(request));
}
+ if (request.containsKey("FilterCriteria")) {
+ // AWS: passing FilterCriteria replaces the whole set; an empty object or an empty
+ // Filters array clears all filters.
+ esm.setFilterCriteria(parseFilterCriteria(request, objectMapper));
+ }
+
esm.setLastModified(System.currentTimeMillis());
esmStore.save(esm);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java
index 894fea7a4b..1af8a5910b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -10,6 +11,7 @@ import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.vertx.core.Vertx;
@@ -18,7 +20,10 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashSet;
+import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -47,6 +52,7 @@ public class SqsEventSourcePoller implements Resettable {
private final long pollIntervalMs;
private final String baseUrl;
private final ObjectMapper objectMapper;
+ private final PipesFilterMatcher filterMatcher;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
// Tracks ESMs with an in-flight poll to prevent concurrent deliveries of the same message
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
@@ -61,7 +67,8 @@ public class SqsEventSourcePoller implements Resettable {
LambdaExecutorService executorService,
LambdaFunctionStore functionStore,
EsmStore esmStore, EmulatorConfig config,
- ObjectMapper objectMapper) {
+ ObjectMapper objectMapper,
+ PipesFilterMatcher filterMatcher) {
this.vertx = vertx;
this.sqsService = sqsService;
this.executorService = executorService;
@@ -70,6 +77,7 @@ public class SqsEventSourcePoller implements Resettable {
this.pollIntervalMs = config.services().lambda().pollIntervalMs();
this.baseUrl = config.effectiveBaseUrl();
this.objectMapper = objectMapper;
+ this.filterMatcher = filterMatcher;
}
public void startPersistedPollers() {
@@ -153,10 +161,39 @@ public class SqsEventSourcePoller implements Resettable {
return;
}
- LOG.infov("ESM {0}: received {1} message(s), invoking {2}",
- esm.getUuid(), messages.size(), esm.getFunctionName());
+ LOG.infov("ESM {0}: received {1} message(s)", esm.getUuid(), messages.size());
- String eventJson = buildSqsEvent(messages, esm);
+ // Apply FilterCriteria. AWS consumes (permanently deletes) filtered-out SQS messages, so
+ // non-matching messages are deleted immediately: leaving them would redeliver every
+ // visibility window forever and never reach the DLQ. A batch that matches nothing
+ // short-circuits without invoking.
+ List<Message> matched = messages;
+ JsonNode filterParams = EsmFilterCriteriaUtils.matcherSourceParameters(objectMapper, esm.getFilterCriteria());
+ if (filterParams != null) {
+ List<JsonNode> recordNodes = new ArrayList<>(messages.size());
+ for (Message m : messages) {
+ recordNodes.add(buildSqsRecordNode(m, esm));
+ }
+ matched = EsmFilterCriteriaUtils.selectMatched(
+ messages, recordNodes, filterMatcher.applyFilterCriteria(recordNodes, filterParams));
+ Set<Message> keep = Collections.newSetFromMap(new IdentityHashMap<>());
+ keep.addAll(matched);
+ for (Message m : messages) {
+ if (!keep.contains(m)) {
+ try {
+ sqsService.deleteMessage(esm.getQueueUrl(), m.getReceiptHandle(), esm.getRegion());
+ } catch (Exception e) {
+ LOG.warnv("ESM {0}: failed to delete filtered-out message {1}: {2}",
+ esm.getUuid(), m.getMessageId(), e.getMessage());
+ }
+ }
+ }
+ if (matched.isEmpty()) {
+ return;
+ }
+ }
+
+ String eventJson = buildSqsEvent(matched, esm);
LOG.infov("ESM {0}: invoking function {1}", esm.getUuid(), fn.getFunctionName());
InvokeResult result;
try {
@@ -172,12 +209,14 @@ public class SqsEventSourcePoller implements Resettable {
}
if (result.getFunctionError() == null) {
+ // Only the delivered (matched) messages are subject to delete/return here; filtered-out
+ // messages were already deleted above, so a batchItemFailure id that names one is inert.
Set<String> failedIds = extractBatchItemFailures(esm, result);
List<Message> toDelete = failedIds.isEmpty()
- ? messages
- : messages.stream().filter(m -> !failedIds.contains(m.getMessageId())).toList();
- LOG.infov("ESM {0}: Lambda succeeded, deleting {1} of {2} message(s) ({3} reported as failed)",
- esm.getUuid(), toDelete.size(), messages.size(), failedIds.size());
+ ? matched
+ : matched.stream().filter(m -> !failedIds.contains(m.getMessageId())).toList();
+ LOG.infov("ESM {0}: Lambda succeeded, deleting {1} of {2} delivered message(s) ({3} reported as failed)",
+ esm.getUuid(), toDelete.size(), matched.size(), failedIds.size());
for (Message msg : toDelete) {
try {
sqsService.deleteMessage(esm.getQueueUrl(),
@@ -191,14 +230,14 @@ public class SqsEventSourcePoller implements Resettable {
// queue immediately so they can be retried/redriven rather than sitting
// in-flight for the full execution-cover visibility window.
if (!failedIds.isEmpty()) {
- List<Message> toReturn = messages.stream()
+ List<Message> toReturn = matched.stream()
.filter(m -> failedIds.contains(m.getMessageId())).toList();
returnMessagesToQueue(esm, toReturn);
}
} else {
- LOG.warnv("ESM {0}: Lambda returned error [{1}], returning {2} message(s) to queue for retry/redrive",
- esm.getUuid(), result.getFunctionError(), messages.size());
- returnMessagesToQueue(esm, messages);
+ LOG.warnv("ESM {0}: Lambda returned error [{1}], returning {2} delivered message(s) to queue for retry/redrive",
+ esm.getUuid(), result.getFunctionError(), matched.size());
+ returnMessagesToQueue(esm, matched);
}
} catch (Exception e) {
LOG.warnv("ESM {0}: poll/invoke error: {1} ({2})",
@@ -283,51 +322,7 @@ public class SqsEventSourcePoller implements Resettable {
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(msg.getSentTimestamp().toEpochMilli()));
- attrs.put("SenderId", AwsArnUtils.accountOrDefault(esm.getEventSourceArn(), "000000000000"));
- attrs.put("ApproximateFirstReceiveTimestamp",
- String.valueOf(msg.getFirstReceiveTimestamp() != null
- ? msg.getFirstReceiveTimestamp().toEpochMilli()
- : System.currentTimeMillis()));
- if (msg.getSequenceNumber() > 0) {
- attrs.put("SequenceNumber", String.valueOf(msg.getSequenceNumber()));
- }
- if (msg.getMessageGroupId() != null) {
- attrs.put("MessageGroupId", msg.getMessageGroupId());
- }
- if (msg.getMessageDeduplicationId() != null) {
- attrs.put("MessageDeduplicationId", msg.getMessageDeduplicationId());
- }
- // Populate messageAttributes from the message model
- ObjectNode msgAttrs = record.putObject("messageAttributes");
- if (msg.getMessageAttributes() != null) {
- msg.getMessageAttributes().forEach((name, val) -> {
- ObjectNode attrNode = msgAttrs.putObject(name);
- attrNode.put("dataType", val.getDataType() != null ? val.getDataType() : "String");
- if (val.getBinaryValue() != null) {
- attrNode.put("binaryValue",
- java.util.Base64.getEncoder().encodeToString(val.getBinaryValue()));
- } else if (val.getStringValue() != null) {
- attrNode.put("stringValue", val.getStringValue());
- }
- attrNode.putArray("stringListValues");
- attrNode.putArray("binaryListValues");
- });
- }
- record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : "");
- if (msg.getMd5OfMessageAttributes() != null) {
- record.put("md5OfMessageAttributes", msg.getMd5OfMessageAttributes());
- }
- record.put("eventSource", "aws:sqs");
- record.put("eventSourceARN", esm.getEventSourceArn());
- record.put("awsRegion", esm.getRegion());
- records.add(record);
+ records.add(buildSqsRecordNode(msg, esm));
}
ObjectNode root = objectMapper.createObjectNode();
root.set("Records", records);
@@ -337,6 +332,59 @@ public class SqsEventSourcePoller implements Resettable {
}
}
+ /**
+ * Builds the single SQS record node: top-level {@code body} plus attributes and metadata. This is both
+ * the delivery record shape and the structure an SQS filter pattern matches against (patterns nest under
+ * {@code body}; the matcher auto-reparses a JSON body).
+ */
+ private ObjectNode buildSqsRecordNode(Message msg, EventSourceMapping esm) {
+ 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(msg.getSentTimestamp().toEpochMilli()));
+ attrs.put("SenderId", AwsArnUtils.accountOrDefault(esm.getEventSourceArn(), "000000000000"));
+ attrs.put("ApproximateFirstReceiveTimestamp",
+ String.valueOf(msg.getFirstReceiveTimestamp() != null
+ ? msg.getFirstReceiveTimestamp().toEpochMilli()
+ : System.currentTimeMillis()));
+ if (msg.getSequenceNumber() > 0) {
+ attrs.put("SequenceNumber", String.valueOf(msg.getSequenceNumber()));
+ }
+ if (msg.getMessageGroupId() != null) {
+ attrs.put("MessageGroupId", msg.getMessageGroupId());
+ }
+ if (msg.getMessageDeduplicationId() != null) {
+ attrs.put("MessageDeduplicationId", msg.getMessageDeduplicationId());
+ }
+ // Populate messageAttributes from the message model
+ ObjectNode msgAttrs = record.putObject("messageAttributes");
+ if (msg.getMessageAttributes() != null) {
+ msg.getMessageAttributes().forEach((name, val) -> {
+ ObjectNode attrNode = msgAttrs.putObject(name);
+ attrNode.put("dataType", val.getDataType() != null ? val.getDataType() : "String");
+ if (val.getBinaryValue() != null) {
+ attrNode.put("binaryValue",
+ java.util.Base64.getEncoder().encodeToString(val.getBinaryValue()));
+ } else if (val.getStringValue() != null) {
+ attrNode.put("stringValue", val.getStringValue());
+ }
+ attrNode.putArray("stringListValues");
+ attrNode.putArray("binaryListValues");
+ });
+ }
+ record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : "");
+ if (msg.getMd5OfMessageAttributes() != null) {
+ record.put("md5OfMessageAttributes", msg.getMd5OfMessageAttributes());
+ }
+ record.put("eventSource", "aws:sqs");
+ record.put("eventSourceARN", esm.getEventSourceArn());
+ record.put("awsRegion", esm.getRegion());
+ return record;
+ }
+
/**
* Derives a queue URL from an SQS ARN.
* arn:aws:sqs:REGION:ACCOUNT:QUEUE_NAME → {baseUrl}/ACCOUNT/QUEUE_NAME
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
index c03419cca2..a2946bf109 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java
@@ -31,6 +31,7 @@ public class EventSourceMapping {
private ScalingConfig scalingConfig;
private Boolean bisectBatchOnFunctionError;
private DestinationConfig destinationConfig;
+ private FilterCriteria filterCriteria;
public EventSourceMapping() {
}
@@ -115,6 +116,14 @@ public class EventSourceMapping {
this.destinationConfig = destinationConfig;
}
+ public FilterCriteria getFilterCriteria() {
+ return filterCriteria;
+ }
+
+ public void setFilterCriteria(FilterCriteria filterCriteria) {
+ this.filterCriteria = filterCriteria;
+ }
+
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class DestinationConfig {
@@ -148,4 +157,38 @@ public class EventSourceMapping {
this.destination = destination;
}
}
+
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class FilterCriteria {
+ private List<Filter> filters = new ArrayList<>();
+
+ public FilterCriteria() {
+ }
+
+ public List<Filter> getFilters() {
+ return filters;
+ }
+
+ public void setFilters(List<Filter> filters) {
+ this.filters = filters != null ? filters : new ArrayList<>();
+ }
+ }
+
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class Filter {
+ private String pattern;
+
+ public Filter() {
+ }
+
+ public String getPattern() {
+ return pattern;
+ }
+
+ public void setPattern(String pattern) {
+ this.pattern = pattern;
+ }
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java
index 1443a1eead..d1ffa6d260 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java
@@ -1,7 +1,10 @@
package io.github.hectorvent.floci.services.lambda;
+import com.fasterxml.jackson.databind.JsonNode;
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.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
@@ -10,17 +13,26 @@ import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
import io.vertx.core.Vertx;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -44,10 +56,12 @@ class DynamoDbStreamsEventSourcePollerTest {
private LambdaExecutorService executorService;
private LambdaFunctionStore functionStore;
private EsmStore esmStore;
+ private EmulatorConfig config;
+ private PipesFilterMatcher filterMatcher;
@BeforeEach
void setUp() {
- EmulatorConfig config = mock(EmulatorConfig.class);
+ config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.LambdaServiceConfig lambdaConfig = mock(EmulatorConfig.LambdaServiceConfig.class);
when(config.services()).thenReturn(services);
@@ -58,12 +72,13 @@ class DynamoDbStreamsEventSourcePollerTest {
executorService = mock(LambdaExecutorService.class);
functionStore = mock(LambdaFunctionStore.class);
esmStore = new EsmStore(new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT_ID));
+ filterMatcher = new PipesFilterMatcher(OBJECT_MAPPER);
// A mocked Vertx makes setPeriodic a no-op, so startPolling registers no live timer and
// the tests drive pollAndInvoke deterministically.
poller = new DynamoDbStreamsEventSourcePoller(
mock(Vertx.class), streamService, executorService, functionStore,
- esmStore, OBJECT_MAPPER, config);
+ esmStore, OBJECT_MAPPER, config, filterMatcher);
}
private EventSourceMapping persistedStreamsEsmWithStaleCheckpoint() {
@@ -131,4 +146,197 @@ class DynamoDbStreamsEventSourcePollerTest {
verify(executorService, timeout(2000))
.invoke(eq(fn), any(byte[].class), eq(InvocationType.RequestResponse));
}
+
+ // ──────────────────────────── FilterCriteria ────────────────────────────
+
+ private DynamoDbStreamsEventSourcePoller pollerWith(EsmStore store) {
+ return new DynamoDbStreamsEventSourcePoller(
+ mock(Vertx.class), streamService, executorService, functionStore,
+ store, OBJECT_MAPPER, config, filterMatcher);
+ }
+
+ /**
+ * Hard happens-after barrier: re-kick until a SECOND fetch is observed. {@code activePolls} serializes
+ * polls per ESM, so fetch #2 cannot begin until poll #1's finally-block ran, so poll #1 is fully complete.
+ */
+ private void awaitPollCompletedViaSecondFetch(DynamoDbStreamsEventSourcePoller p, EventSourceMapping esm) {
+ long deadline = System.currentTimeMillis() + 5000;
+ while (true) {
+ p.pollAndInvoke(esm);
+ try {
+ verify(streamService, atLeast(2)).getRecords("it", 10);
+ return;
+ } catch (AssertionError retry) {
+ if (System.currentTimeMillis() > deadline) {
+ throw retry;
+ }
+ try {
+ Thread.sleep(25);
+ } catch (InterruptedException ie) {
+ Thread.currentThread().interrupt();
+ throw retry;
+ }
+ }
+ }
+ }
+
+ private EventSourceMapping filterEsm(String... patterns) {
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("esm-f");
+ esm.setAccountId(ACCOUNT_ID);
+ esm.setRegion("us-east-1");
+ esm.setFunctionName("fn");
+ esm.setEventSourceArn(STREAM_ARN);
+ esm.setBatchSize(10);
+ esm.setEnabled(true);
+ if (patterns.length > 0) {
+ EventSourceMapping.FilterCriteria fc = new EventSourceMapping.FilterCriteria();
+ List<EventSourceMapping.Filter> filters = new ArrayList<>();
+ for (String p : patterns) {
+ EventSourceMapping.Filter f = new EventSourceMapping.Filter();
+ f.setPattern(p);
+ filters.add(f);
+ }
+ fc.setFilters(filters);
+ esm.setFilterCriteria(fc);
+ }
+ return esm;
+ }
+
+ private DynamoDbStreamRecord ddbRecord(String seq, String eventName, String newImageJson) {
+ DynamoDbStreamRecord rec = new DynamoDbStreamRecord();
+ rec.setSequenceNumber(seq);
+ rec.setEventName(eventName);
+ rec.setEventSource("aws:dynamodb");
+ rec.setAwsRegion("us-east-1");
+ rec.setStreamViewType("NEW_AND_OLD_IMAGES");
+ try {
+ rec.setNewImage(OBJECT_MAPPER.readTree(newImageJson));
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return rec;
+ }
+
+ private void stubTrimHorizon(List<DynamoDbStreamRecord> records) {
+ // Match any iterator type/seq so a re-kicked poll after a checkpoint advance (AFTER_SEQUENCE_NUMBER)
+ // still resolves an iterator: the second-fetch barrier depends on poll N+1 fetching.
+ when(streamService.getShardIterator(eq(STREAM_ARN), eq(DynamoDbStreamService.SHARD_ID), anyString(), any()))
+ .thenReturn("it");
+ when(streamService.getRecords("it", 10))
+ .thenReturn(new DynamoDbStreamService.GetRecordsResult(records, "it"));
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("fn");
+ when(functionStore.getForAccount(ACCOUNT_ID, "us-east-1", "fn")).thenReturn(Optional.of(fn));
+ }
+
+ private static final String PATTERN =
+ "{\"eventName\":[\"INSERT\"],\"dynamodb\":{\"NewImage\":{\"status\":{\"S\":[\"active\"]}}}}";
+
+ @Test
+ void filterDeliversMatchingRecordsAndCheckpointsNewestFetched() {
+ stubTrimHorizon(List.of(
+ ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"),
+ ddbRecord("s2", "INSERT", "{\"status\":{\"S\":\"inactive\"}}")));
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult());
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm(PATTERN);
+
+ pollerWith(store).pollAndInvoke(esm);
+
+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000)).invoke(any(), payload.capture(), eq(InvocationType.RequestResponse));
+ JsonNode records = readRecords(payload.getValue());
+ assertEquals(1, records.size());
+ assertEquals("s1", records.get(0).path("dynamodb").path("SequenceNumber").asText());
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s2", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+ }
+
+ @Test
+ void fullyFilteredBatchAdvancesCheckpointWithoutInvoking() {
+ stubTrimHorizon(List.of(
+ ddbRecord("s1", "MODIFY", "{\"status\":{\"S\":\"active\"}}"),
+ ddbRecord("s2", "INSERT", "{\"status\":{\"S\":\"inactive\"}}")));
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm(PATTERN);
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ p.pollAndInvoke(esm);
+
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ awaitPollCompletedViaSecondFetch(p, esm);
+ assertEquals("s2", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+ verify(executorService, never()).invoke(any(), any(byte[].class), any());
+ }
+
+ @Test
+ void invokeErrorDoesNotAdvanceCheckpointAndRetriesSameWindow() {
+ stubTrimHorizon(List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}")));
+ InvokeResult err = new InvokeResult();
+ err.setFunctionError("Unhandled");
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(err);
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm(PATTERN);
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ p.pollAndInvoke(esm);
+ verify(executorService, timeout(2000)).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
+ awaitPollCompletedViaSecondFetch(p, esm);
+
+ verify(store, never()).saveForAccount(anyString(), any());
+ assertNull(esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+ // retry-from-old-checkpoint: both polls re-derive TRIM_HORIZON and deliver the same window.
+ ArgumentCaptor<byte[]> cap = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000).atLeast(2)).invoke(any(), cap.capture(), eq(InvocationType.RequestResponse));
+ List<byte[]> payloads = cap.getAllValues();
+ assertEquals(new String(payloads.get(0)), new String(payloads.get(payloads.size() - 1)));
+ }
+
+ @Test
+ void throttleDoesNotAdvanceCheckpoint() {
+ stubTrimHorizon(List.of(
+ ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"),
+ ddbRecord("s2", "MODIFY", "{\"status\":{\"S\":\"inactive\"}}")));
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenThrow(new AwsException("TooManyRequestsException", "throttled", 429));
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm(PATTERN); // s1 matches → invoke attempted → throttled
+ DynamoDbStreamsEventSourcePoller p = pollerWith(store);
+
+ p.pollAndInvoke(esm);
+ verify(executorService, timeout(2000)).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
+ awaitPollCompletedViaSecondFetch(p, esm);
+ verify(store, never()).saveForAccount(anyString(), any());
+ assertNull(esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+ }
+
+ @Test
+ void noFilterCriteriaDeliversAllRecords() {
+ stubTrimHorizon(List.of(
+ ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"),
+ ddbRecord("s2", "MODIFY", "{\"status\":{\"S\":\"inactive\"}}")));
+ when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult());
+ EsmStore store = mock(EsmStore.class);
+ EventSourceMapping esm = filterEsm(); // no FilterCriteria
+
+ pollerWith(store).pollAndInvoke(esm);
+
+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000)).invoke(any(), payload.capture(), eq(InvocationType.RequestResponse));
+ assertEquals(2, readRecords(payload.getValue()).size());
+ verify(store, timeout(2000)).saveForAccount(eq(ACCOUNT_ID), any());
+ assertEquals("s2", esm.getShardSequenceNumbers().get(DynamoDbStreamService.SHARD_ID));
+ }
+
+ private JsonNode readRecords(byte[] payload) {
+ try {
+ return OBJECT_MAPPER.readTree(payload).path("Records");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaMatcherIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaMatcherIntegrationTest.java
new file mode 100644
index 0000000000..00eae0cd89
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaMatcherIntegrationTest.java
@@ -0,0 +1,109 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * End-to-end proof that a stored {@link EventSourceMapping.FilterCriteria}, wrapped by
+ * {@link EsmFilterCriteriaUtils#matcherSourceParameters}, actually drives the REAL
+ * {@link PipesFilterMatcher}, not just that the wrapper has the right field names. Without this, the
+ * wrapper could be shaped wrong (silently disabling filtering) and unit tests inspecting only its fields
+ * would stay green. Uses supported EventBridge operators the matcher implements; known matcher deviations
+ * (boolean literals, event-array intersection, numeric anything-but) are documented, not covered here, per
+ * the reuse-the-matcher scope decision.
+ */
+class EsmFilterCriteriaMatcherIntegrationTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final PipesFilterMatcher MATCHER = new PipesFilterMatcher(MAPPER);
+
+ private static EventSourceMapping.FilterCriteria criteria(String... patterns) {
+ EventSourceMapping.FilterCriteria fc = new EventSourceMapping.FilterCriteria();
+ List<EventSourceMapping.Filter> filters = new ArrayList<>();
+ for (String p : patterns) {
+ EventSourceMapping.Filter f = new EventSourceMapping.Filter();
+ f.setPattern(p);
+ filters.add(f);
+ }
+ fc.setFilters(filters);
+ return fc;
+ }
+
+ /** An SQS-style record: body is a JSON string the matcher re-parses when a pattern nests an object under it. */
+ private static ObjectNode sqsRecord(String messageId, String bodyJson) {
+ ObjectNode n = MAPPER.createObjectNode();
+ n.put("messageId", messageId);
+ n.put("body", bodyJson);
+ return n;
+ }
+
+ private List<String> matchedIds(EventSourceMapping.FilterCriteria fc, List<ObjectNode> records) {
+ JsonNode wrapper = EsmFilterCriteriaUtils.matcherSourceParameters(MAPPER, fc);
+ List<JsonNode> filterNodes = new ArrayList<>(records);
+ List<JsonNode> matched = MATCHER.applyFilterCriteria(filterNodes, wrapper);
+ // Recover source records via the shared correlation helper, then read their ids.
+ List<ObjectNode> matchedRecords = EsmFilterCriteriaUtils.selectMatched(records, filterNodes, matched);
+ List<String> ids = new ArrayList<>();
+ for (ObjectNode r : matchedRecords) {
+ ids.add(r.path("messageId").asText());
+ }
+ return ids;
+ }
+
+ @Test
+ void storedFilterCriteriaFiltersThroughRealMatcher() {
+ List<ObjectNode> records = List.of(
+ sqsRecord("m1", "{\"type\":\"order\"}"),
+ sqsRecord("m2", "{\"type\":\"refund\"}"),
+ sqsRecord("m3", "{\"type\":\"order\"}"));
+ // Wrap the stored criteria and run it through the real matcher.
+ assertEquals(List.of("m1", "m3"),
+ matchedIds(criteria("{\"body\":{\"type\":[\"order\"]}}"), records));
+ }
+
+ @Test
+ void multipleFiltersAreOred() {
+ List<ObjectNode> records = List.of(
+ sqsRecord("m1", "{\"type\":\"order\"}"),
+ sqsRecord("m2", "{\"type\":\"refund\"}"),
+ sqsRecord("m3", "{\"type\":\"chargeback\"}"));
+ assertEquals(List.of("m1", "m2"),
+ matchedIds(criteria("{\"body\":{\"type\":[\"order\"]}}", "{\"body\":{\"type\":[\"refund\"]}}"), records));
+ }
+
+ @Test
+ void topLevelMetadataPatternMatches() {
+ List<ObjectNode> records = List.of(
+ sqsRecord("m1", "{\"ignored\":true}"),
+ sqsRecord("m2", "{\"ignored\":true}"));
+ // pattern on a top-level record field (messageId), not the body
+ assertEquals(List.of("m2"), matchedIds(criteria("{\"messageId\":[\"m2\"]}"), records));
+ }
+
+ @Test
+ void noRecordMatchesYieldsEmpty() {
+ List<ObjectNode> records = List.of(
+ sqsRecord("m1", "{\"type\":\"order\"}"),
+ sqsRecord("m2", "{\"type\":\"refund\"}"));
+ assertTrue(matchedIds(criteria("{\"body\":{\"type\":[\"nonexistent\"]}}"), records).isEmpty());
+ }
+
+ @Test
+ void nonJsonBodyIsDroppedByObjectPattern() {
+ // A body that isn't JSON cannot satisfy an object pattern → dropped (AWS drops on format mismatch).
+ List<ObjectNode> records = List.of(
+ sqsRecord("m1", "not json at all"),
+ sqsRecord("m2", "{\"type\":\"order\"}"));
+ assertEquals(List.of("m2"), matchedIds(criteria("{\"body\":{\"type\":[\"order\"]}}"), records));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaUtilsTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaUtilsTest.java
new file mode 100644
index 0000000000..e4a96e9ca6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaUtilsTest.java
@@ -0,0 +1,91 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class EsmFilterCriteriaUtilsTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static EventSourceMapping.FilterCriteria criteria(String... patterns) {
+ EventSourceMapping.FilterCriteria fc = new EventSourceMapping.FilterCriteria();
+ List<EventSourceMapping.Filter> filters = new ArrayList<>();
+ for (String p : patterns) {
+ EventSourceMapping.Filter f = new EventSourceMapping.Filter();
+ f.setPattern(p);
+ filters.add(f);
+ }
+ fc.setFilters(filters);
+ return fc;
+ }
+
+ @Test
+ void nullOrEmptyCriteriaYieldsNull() {
+ assertNull(EsmFilterCriteriaUtils.matcherSourceParameters(MAPPER, null));
+ assertNull(EsmFilterCriteriaUtils.matcherSourceParameters(MAPPER, new EventSourceMapping.FilterCriteria()));
+ EventSourceMapping.FilterCriteria emptyList = new EventSourceMapping.FilterCriteria();
+ emptyList.setFilters(new ArrayList<>());
+ assertNull(EsmFilterCriteriaUtils.matcherSourceParameters(MAPPER, emptyList));
+ }
+
+ @Test
+ void wrapsFiltersInExactPascalCaseShape() {
+ JsonNode node = EsmFilterCriteriaUtils.matcherSourceParameters(
+ MAPPER, criteria("{\"data\":{\"type\":[\"buy\"]}}", "{\"partitionKey\":[\"pk-1\"]}"));
+ assertNotNull(node);
+ // The matcher path-matches on FilterCriteria.Filters[].Pattern (PascalCase). A drifted key
+ // would silently pass every record through, so pin the exact shape here.
+ assertTrue(node.has("FilterCriteria"));
+ JsonNode filters = node.path("FilterCriteria").path("Filters");
+ assertTrue(filters.isArray());
+ assertEquals(2, filters.size());
+ assertTrue(filters.get(0).has("Pattern"));
+ assertEquals("{\"data\":{\"type\":[\"buy\"]}}", filters.get(0).path("Pattern").asText());
+ assertEquals("{\"partitionKey\":[\"pk-1\"]}", filters.get(1).path("Pattern").asText());
+ }
+
+ @Test
+ void selectMatchedRecoversSourcesByOrder() {
+ List<String> sources = List.of("a", "b", "c", "d");
+ ObjectNode n0 = MAPPER.createObjectNode();
+ ObjectNode n1 = MAPPER.createObjectNode();
+ ObjectNode n2 = MAPPER.createObjectNode();
+ ObjectNode n3 = MAPPER.createObjectNode();
+ List<JsonNode> filterNodes = List.of(n0, n1, n2, n3);
+ List<JsonNode> matched = List.of(n1, n3); // matcher returns a subset, same instances, input order
+ assertEquals(List.of("b", "d"), EsmFilterCriteriaUtils.selectMatched(sources, filterNodes, matched));
+ }
+
+ @Test
+ void selectMatchedUsesIdentityNotEqualityForDuplicatePayloads() {
+ List<String> sources = List.of("first", "second");
+ ObjectNode a = MAPPER.createObjectNode();
+ a.put("body", "same");
+ ObjectNode b = MAPPER.createObjectNode();
+ b.put("body", "same");
+ assertEquals(a, b); // equal by value...
+ assertNotSame(a, b); // ...but distinct instances
+ List<JsonNode> filterNodes = List.of(a, b);
+ // Only the second instance matched; identity (not value-equality) must pick "second".
+ assertEquals(List.of("second"), EsmFilterCriteriaUtils.selectMatched(sources, filterNodes, List.of(b)));
+ }
+
+ @Test
+ void selectMatchedEmptyWhenNothingMatched() {
+ List<String> sources = List.of("a", "b");
+ List<JsonNode> filterNodes = List.of(MAPPER.createObjectNode(), MAPPER.createObjectNode());
+ assertTrue(EsmFilterCriteriaUtils.selectMatched(sources, filterNodes, List.of()).isEmpty());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
index ae3af3e177..461f4b9c5c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java
@@ -1021,4 +1021,241 @@ class EsmIntegrationTest {
}
}
}
+
+ // ──────────────────────────── FilterCriteria ────────────────────────────
+
+ /** Embeds a raw JSON pattern as a properly-escaped JSON string value in a request body. */
+ private static String jsonString(String raw) {
+ return "\"" + raw.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
+ }
+
+ /** Builds {@code n} comma-separated {@code {"Pattern": <raw>}} filter entries for a Filters array. */
+ private static String repeatFilter(String rawPattern, int n) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < n; i++) {
+ if (i > 0) {
+ sb.append(", ");
+ }
+ sb.append("{ \"Pattern\": ").append(jsonString(rawPattern)).append(" }");
+ }
+ return sb.toString();
+ }
+
+ @Test
+ @Order(76)
+ void createEventSourceMappingWithFilterCriteriaRoundTrips() {
+ String pattern = "{\"body\":{\"type\":[\"order\"]}}";
+ String uuid = given()
+ .contentType("application/json")
+ .body("""
+ {
+ "FunctionName": "%s",
+ "EventSourceArn": "%s",
+ "BatchSize": 5,
+ "FilterCriteria": { "Filters": [ { "Pattern": %s } ] }
+ }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN, jsonString(pattern)))
+ .when()
+ .post(LAMBDA_BASE + "/event-source-mappings")
+ .then()
+ .statusCode(202)
+ .body("FilterCriteria.Filters[0].Pattern", equalTo(pattern))
+ .extract()
+ .path("UUID");
+
+ given()
+ .when()
+ .get(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then()
+ .statusCode(200)
+ .body("FilterCriteria.Filters[0].Pattern", equalTo(pattern));
+
+ given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
+ }
+
+ @Test
+ @Order(77)
+ void responseOmitsFilterCriteriaWhenUnset() {
+ // The original bug's wire symptom was FilterCriteria: null; AWS omits the key entirely when unset.
+ String uuid = given()
+ .contentType("application/json")
+ .body("""
+ {
+ "FunctionName": "%s",
+ "EventSourceArn": "%s",
+ "BatchSize": 2
+ }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN))
+ .when()
+ .post(LAMBDA_BASE + "/event-source-mappings")
+ .then()
+ .statusCode(202)
+ .body("$", not(hasKey("FilterCriteria")))
+ .extract()
+ .path("UUID");
+
+ given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
+ }
+
+ @Test
+ @Order(78)
+ void updateEventSourceMappingAddsReplacesAndClearsFilterCriteria() {
+ String uuid = given()
+ .contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s", "BatchSize": 2 }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(202).extract().path("UUID");
+
+ // Add
+ String first = "{\"body\":{\"type\":[\"order\"]}}";
+ given().contentType("application/json")
+ .body("{ \"FilterCriteria\": { \"Filters\": [ { \"Pattern\": " + jsonString(first) + " } ] } }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then().statusCode(202).body("FilterCriteria.Filters[0].Pattern", equalTo(first));
+
+ // Replace whole set
+ String second = "{\"body\":{\"type\":[\"refund\"]}}";
+ given().contentType("application/json")
+ .body("{ \"FilterCriteria\": { \"Filters\": [ { \"Pattern\": " + jsonString(second) + " } ] } }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then().statusCode(202)
+ .body("FilterCriteria.Filters.size()", equalTo(1))
+ .body("FilterCriteria.Filters[0].Pattern", equalTo(second));
+
+ // Clear with empty object
+ given().contentType("application/json").body("{ \"FilterCriteria\": {} }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then().statusCode(202).body("$", not(hasKey("FilterCriteria")));
+
+ // Re-add, then clear with empty Filters array
+ given().contentType("application/json")
+ .body("{ \"FilterCriteria\": { \"Filters\": [ { \"Pattern\": " + jsonString(first) + " } ] } }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
+ given().contentType("application/json").body("{ \"FilterCriteria\": { \"Filters\": [] } }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then().statusCode(202).body("$", not(hasKey("FilterCriteria")));
+
+ given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
+ }
+
+ @Test
+ @Order(79)
+ void createEventSourceMappingRejectsInvalidFilterCriteria() {
+ // malformed JSON pattern
+ given().contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s",
+ "FilterCriteria": { "Filters": [ { "Pattern": %s } ] } }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN, jsonString("{oops")))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(400);
+
+ // scalar (non-array/object) value: a silent drop-all pattern
+ given().contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s",
+ "FilterCriteria": { "Filters": [ { "Pattern": %s } ] } }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN, jsonString("{\"eventName\":\"INSERT\"}")))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(400);
+
+ // FilterCriteria not an object
+ given().contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s", "FilterCriteria": "nope" }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(400);
+
+ // more than 5 filters
+ String sixFilters = repeatFilter("{\"a\":[1]}", 6);
+ given().contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s",
+ "FilterCriteria": { "Filters": [ %s ] } }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN, sixFilters))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(400);
+
+ // pattern longer than 4096 chars
+ String oversized = "{\"a\":[\"" + "x".repeat(4087) + "\"]}"; // 4097 chars
+ given().contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s",
+ "FilterCriteria": { "Filters": [ { "Pattern": %s } ] } }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN, jsonString(oversized)))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(400);
+ }
+
+ @Test
+ @Order(80)
+ void updateEventSourceMappingRejectsInvalidFilterCriteria() {
+ String uuid = given()
+ .contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s", "BatchSize": 2 }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(202).extract().path("UUID");
+
+ given().contentType("application/json")
+ .body("{ \"FilterCriteria\": { \"Filters\": [ { \"Pattern\": " + jsonString("{oops") + " } ] } }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then().statusCode(400);
+
+ // FilterCriteria not an object
+ given().contentType("application/json").body("{ \"FilterCriteria\": \"nope\" }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then().statusCode(400);
+
+ // more than 5 filters
+ given().contentType("application/json")
+ .body("{ \"FilterCriteria\": { \"Filters\": [ " + repeatFilter("{\"a\":[1]}", 6) + " ] } }")
+ .when().put(LAMBDA_BASE + "/event-source-mappings/" + uuid)
+ .then().statusCode(400);
+
+ given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202);
+ }
+
+ @Test
+ @Order(81)
+ void listEventSourceMappingsEchoesFilterCriteria() {
+ String pattern = "{\"body\":{\"type\":[\"order\"]}}";
+ String uuidWith = given()
+ .contentType("application/json")
+ .body("""
+ {
+ "FunctionName": "%s",
+ "EventSourceArn": "%s",
+ "BatchSize": 3,
+ "FilterCriteria": { "Filters": [ { "Pattern": %s } ] }
+ }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN, jsonString(pattern)))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(202).extract().path("UUID");
+
+ String uuidWithout = given()
+ .contentType("application/json")
+ .body("""
+ { "FunctionName": "%s", "EventSourceArn": "%s", "BatchSize": 4 }
+ """.formatted(FUNCTION_NAME, QUEUE_ARN))
+ .when().post(LAMBDA_BASE + "/event-source-mappings")
+ .then().statusCode(202).extract().path("UUID");
+
+ given()
+ .when()
+ .get(LAMBDA_BASE + "/event-source-mappings?FunctionName=" + FUNCTION_ARN)
+ .then()
+ .statusCode(200)
+ .body("EventSourceMappings.find { it.UUID == '" + uuidWith + "' }.FilterCriteria.Filters[0].Pattern",
+ equalTo(pattern))
+ .body("EventSourceMappings.find { it.UUID == '" + uuidWithout + "' }.FilterCriteria",
+ nullValue());
+
+ given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuidWith).then().statusCode(202);
+ given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuidWithout).then().statusCode(202);
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmStoreFilterCriteriaTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmStoreFilterCriteriaTest.java
new file mode 100644
index 0000000000..945b525009
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmStoreFilterCriteriaTest.java
@@ -0,0 +1,84 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Proves {@code FilterCriteria} persists on {@code EventSourceMapping}: once through the real
+ * {@code EsmStore} (wiring), and once through an explicit Jackson serialize/reload leg that reproduces
+ * {@code PersistentStorage}'s mechanism: since {@code InMemoryStorage} keeps live references, the wiring
+ * test alone would not exercise JSON serialization.
+ */
+class EsmStoreFilterCriteriaTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String ACCOUNT_ID = "000000000000";
+
+ private static EventSourceMapping esmWithFilters(String uuid, String... patterns) {
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid(uuid);
+ esm.setAccountId(ACCOUNT_ID);
+ esm.setRegion("us-east-1");
+ esm.setFunctionName("fn");
+ EventSourceMapping.FilterCriteria fc = new EventSourceMapping.FilterCriteria();
+ List<EventSourceMapping.Filter> filters = new ArrayList<>();
+ for (String p : patterns) {
+ EventSourceMapping.Filter f = new EventSourceMapping.Filter();
+ f.setPattern(p);
+ filters.add(f);
+ }
+ fc.setFilters(filters);
+ esm.setFilterCriteria(fc);
+ return esm;
+ }
+
+ @Test
+ void filterCriteriaSurvivesEsmStore() {
+ EsmStore store = new EsmStore(new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT_ID));
+ store.saveForAccount(ACCOUNT_ID, esmWithFilters("esm-fc", "{\"data\":{\"type\":[\"buy\"]}}"));
+ EventSourceMapping reloaded = store.getForAccount(ACCOUNT_ID, "esm-fc").orElseThrow();
+ assertNotNull(reloaded.getFilterCriteria());
+ assertEquals(1, reloaded.getFilterCriteria().getFilters().size());
+ assertEquals("{\"data\":{\"type\":[\"buy\"]}}",
+ reloaded.getFilterCriteria().getFilters().get(0).getPattern());
+ }
+
+ @Test
+ void filterCriteriaSurvivesJacksonSerializeReload() throws Exception {
+ EventSourceMapping esm = esmWithFilters("esm-fc",
+ "{\"body\":{\"status\":[\"active\"]}}", "{\"partitionKey\":[\"pk-1\"]}");
+ // Mirror PersistentStorage: write the whole map to JSON, then read it back into a fresh graph.
+ String json = MAPPER.writeValueAsString(Map.of(esm.getUuid(), esm));
+ Map<String, EventSourceMapping> after =
+ MAPPER.readValue(json, new TypeReference<Map<String, EventSourceMapping>>() {});
+ EventSourceMapping reloaded = after.get("esm-fc");
+ assertNotNull(reloaded.getFilterCriteria());
+ List<EventSourceMapping.Filter> filters = reloaded.getFilterCriteria().getFilters();
+ assertEquals(2, filters.size());
+ assertEquals("{\"body\":{\"status\":[\"active\"]}}", filters.get(0).getPattern());
+ assertEquals("{\"partitionKey\":[\"pk-1\"]}", filters.get(1).getPattern());
+ }
+
+ @Test
+ void unsetFilterCriteriaRoundTripsAsNull() throws Exception {
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("esm-none");
+ esm.setAccountId(ACCOUNT_ID);
+ String json = MAPPER.writeValueAsString(Map.of("esm-none", esm));
+ Map<String, EventSourceMapping> after =
+ MAPPER.readValue(json, new TypeReference<Map<String, EventSourceMapping>>() {});
+ assertNull(after.get("esm-none").getFilterCriteria());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java
new file mode 100644
index 0000000000..4480e0b3b2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java
@@ -0,0 +1,308 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.kinesis.KinesisService;
+import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
+import io.github.hectorvent.floci.services.kinesis.model.KinesisShard;
+import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
+import io.vertx.core.Vertx;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Fills the poller-test gap for Kinesis and covers FilterCriteria enforcement: the checkpoint must advance
+ * past filtered-out records (never wedge the shard), delivery stays base64, and the Kinesis filter dialect is
+ * top-level decoded {@code data}, not the {@code {"kinesis":{"data":...}}} envelope.
+ *
+ * <p>Async note: {@code pollAndInvoke} submits to a background executor. Assertions wait on a positive terminal
+ * signal via Mockito {@code timeout(...)}: {@code esmStore.saveForAccount} for a checkpoint advance, or the
+ * invoke itself. {@code never()} assertions target actions the exercised code path never performs on any thread
+ * (invoke in a fully-filtered path; save in an invoke-error path), so they are timing-independent.
+ */
+class KinesisEventSourcePollerTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String ACCOUNT = "000000000000";
+ private static final String REGION = "us-east-1";
+ private static final String STREAM_ARN = "arn:aws:kinesis:us-east-1:000000000000:stream/s";
+ private static final String SHARD = "shardId-000000000000";
+
+ private KinesisEventSourcePoller poller;
+ private KinesisService kinesisService;
+ private LambdaExecutorService executorService;
+ private LambdaFunctionStore functionStore;
+ private EsmStore esmStore;
+
+ @BeforeEach
+ void setUp() {
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.LambdaServiceConfig lambdaConfig = mock(EmulatorConfig.LambdaServiceConfig.class);
+ when(config.services()).thenReturn(services);
+ when(services.lambda()).thenReturn(lambdaConfig);
+ when(lambdaConfig.pollIntervalMs()).thenReturn(1000L);
+
+ kinesisService = mock(KinesisService.class);
+ executorService = mock(LambdaExecutorService.class);
+ functionStore = mock(LambdaFunctionStore.class);
+ esmStore = mock(EsmStore.class);
+
+ poller = new KinesisEventSourcePoller(mock(Vertx.class), kinesisService, executorService,
+ functionStore, esmStore, config, MAPPER, new PipesFilterMatcher(MAPPER));
+ }
+
+ private EventSourceMapping esm(String... patterns) {
+ EventSourceMapping esm = new EventSourceMapping();
+ esm.setUuid("k-esm");
+ esm.setAccountId(ACCOUNT);
+ esm.setRegion(REGION);
+ esm.setFunctionName("fn");
+ esm.setEventSourceArn(STREAM_ARN);
+ esm.setBatchSize(10);
+ esm.setEnabled(true);
+ if (patterns.length > 0) {
+ EventSourceMapping.FilterCriteria fc = new EventSourceMapping.FilterCriteria();
+ List<EventSourceMapping.Filter> filters = new ArrayList<>();
+ for (String p : patterns) {
+ EventSourceMapping.Filter f = new EventSourceMapping.Filter();
+ f.setPattern(p);
+ filters.add(f);
+ }
+ fc.setFilters(filters);
+ esm.setFilterCriteria(fc);
+ }
+ return esm;
+ }
+
+ private KinesisRecord record(String seq, String partitionKey, String data) {
+ return new KinesisRecord(data.getBytes(StandardCharsets.UTF_8), partitionKey, seq,
+ Instant.parse("2026-01-01T00:00:00Z"));
+ }
+
+ private void stubStreamWith(List<KinesisRecord> records) {
+ KinesisStream stream = new KinesisStream("s", STREAM_ARN);
+ stream.setShards(List.of(new KinesisShard(SHARD, "0", "1", "0")));
+ when(kinesisService.describeStream(anyString(), eq(REGION))).thenReturn(stream);
+ when(kinesisService.getShardIterator(anyString(), eq(SHARD), anyString(), any(), eq(REGION)))
+ .thenReturn("iter-0");
+ when(kinesisService.getRecords(eq("iter-0"), anyInt(), eq(REGION)))
+ .thenReturn(Map.of("Records", records));
+ }
+
+ private void stubFunction() {
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("fn");
+ when(functionStore.getForAccount(ACCOUNT, REGION, "fn")).thenReturn(Optional.of(fn));
+ }
+
+ private JsonNode deliveredRecords(byte[] payload) {
+ try {
+ return MAPPER.readTree(payload).path("Records");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Hard happens-after barrier: re-kick the poll until a SECOND fetch is observed. Because {@code activePolls}
+ * serializes polls per ESM, fetch #2 cannot begin until poll #1's finally-block ran, so poll #1, including its
+ * invoke/checkpoint decision, is fully complete. Negative assertions after this are race-free rather than
+ * relying on structural unreachability alone. (A kick while poll #1 is still in flight is a no-op, so we retry.)
+ */
+ private void awaitPollCompletedViaSecondFetch(EventSourceMapping esm) {
+ long deadline = System.currentTimeMillis() + 5000;
+ while (true) {
+ poller.pollAndInvoke(esm);
+ try {
+ verify(kinesisService, atLeast(2)).getRecords(eq("iter-0"), anyInt(), eq(REGION));
+ return;
+ } catch (AssertionError retry) {
+ if (System.currentTimeMillis() > deadline) {
+ throw retry;
+ }
+ try {
+ Thread.sleep(25);
+ } catch (InterruptedException ie) {
+ Thread.currentThread().interrupt();
+ throw retry;
+ }
+ }
+ }
+ }
+
+ @Test
+ void noFilterInvokesAllRecordsAndCheckpointsNewest() {
+ stubFunction();
+ stubStreamWith(List.of(record("s1", "p1", "{\"type\":\"order\"}"),
+ record("s2", "p2", "{\"type\":\"refund\"}")));
+ when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse))).thenReturn(new InvokeResult());
+ EventSourceMapping esm = esm();
+
+ poller.pollAndInvoke(esm);
+
+ verify(esmStore, timeout(2000)).saveForAccount(eq(ACCOUNT), any());
+ assertEquals("s2", esm.getShardSequenceNumbers().get(SHARD));
+ verify(executorService, timeout(2000)).invoke(any(), any(), eq(InvocationType.RequestResponse));
+ }
+
+ @Test
+ void filterDeliversOnlyMatchingRecordsKeepsDataBase64AndCheckpointsNewestFetched() {
+ stubFunction();
+ // order (matches) then refund (does not): refund is the newest FETCHED record.
+ stubStreamWith(List.of(record("s1", "p1", "{\"type\":\"order\"}"),
+ record("s2", "p2", "{\"type\":\"refund\"}")));
+ when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse))).thenReturn(new InvokeResult());
+ EventSourceMapping esm = esm("{\"data\":{\"type\":[\"order\"]}}");
+
+ poller.pollAndInvoke(esm);
+
+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000)).invoke(any(), payload.capture(), eq(InvocationType.RequestResponse));
+ JsonNode records = deliveredRecords(payload.getValue());
+ assertEquals(1, records.size());
+ assertEquals("s1", records.get(0).path("kinesis").path("sequenceNumber").asText());
+ // Delivery keeps data base64-encoded even though filtering ran on the decoded copy.
+ String base64 = records.get(0).path("kinesis").path("data").asText();
+ assertEquals("{\"type\":\"order\"}",
+ new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8));
+ // Checkpoint advances to the newest FETCHED seq (s2), consuming the trailing filtered-out record.
+ verify(esmStore, timeout(2000)).saveForAccount(eq(ACCOUNT), any());
+ assertEquals("s2", esm.getShardSequenceNumbers().get(SHARD));
+ }
+
+ @Test
+ void fullyFilteredBatchAdvancesCheckpointWithoutInvoking() {
+ stubFunction();
+ stubStreamWith(List.of(record("s1", "p1", "{\"type\":\"refund\"}"),
+ record("s2", "p2", "{\"type\":\"chargeback\"}")));
+ EventSourceMapping esm = esm("{\"data\":{\"type\":[\"order\"]}}");
+
+ poller.pollAndInvoke(esm);
+
+ verify(esmStore, timeout(2000)).saveForAccount(eq(ACCOUNT), any());
+ awaitPollCompletedViaSecondFetch(esm);
+ assertEquals("s2", esm.getShardSequenceNumbers().get(SHARD));
+ verify(executorService, never()).invoke(any(), any(), any());
+ }
+
+ @Test
+ void nonJsonDataDroppedByObjectPattern() {
+ stubFunction();
+ stubStreamWith(List.of(record("s1", "p1", "not json at all"),
+ record("s2", "p2", "{\"type\":\"order\"}")));
+ when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse))).thenReturn(new InvokeResult());
+ EventSourceMapping esm = esm("{\"data\":{\"type\":[\"order\"]}}");
+
+ poller.pollAndInvoke(esm);
+
+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000)).invoke(any(), payload.capture(), eq(InvocationType.RequestResponse));
+ JsonNode records = deliveredRecords(payload.getValue());
+ assertEquals(1, records.size());
+ assertEquals("s2", records.get(0).path("kinesis").path("sequenceNumber").asText());
+ }
+
+ @Test
+ void partitionKeyMetadataPatternMatches() {
+ stubFunction();
+ stubStreamWith(List.of(record("s1", "pk-1", "{}"), record("s2", "pk-2", "{}")));
+ when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse))).thenReturn(new InvokeResult());
+ EventSourceMapping esm = esm("{\"partitionKey\":[\"pk-2\"]}");
+
+ poller.pollAndInvoke(esm);
+
+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000)).invoke(any(), payload.capture(), eq(InvocationType.RequestResponse));
+ JsonNode records = deliveredRecords(payload.getValue());
+ assertEquals(1, records.size());
+ assertEquals("s2", records.get(0).path("kinesis").path("sequenceNumber").asText());
+ }
+
+ @Test
+ void nestedKinesisDataPatternMatchesNothingDialectPin() {
+ stubFunction();
+ stubStreamWith(List.of(record("s1", "p1", "{\"type\":\"order\"}")));
+ // The invocation-envelope dialect {"kinesis":{"data":...}} must NOT match: AWS filters top-level data.
+ EventSourceMapping esm = esm("{\"kinesis\":{\"data\":{\"type\":[\"order\"]}}}");
+
+ poller.pollAndInvoke(esm);
+
+ verify(esmStore, timeout(2000)).saveForAccount(eq(ACCOUNT), any());
+ awaitPollCompletedViaSecondFetch(esm);
+ assertEquals("s1", esm.getShardSequenceNumbers().get(SHARD));
+ verify(executorService, never()).invoke(any(), any(), any());
+ }
+
+ @Test
+ void invokeErrorDoesNotAdvanceCheckpointAndRetriesSameWindow() {
+ stubFunction();
+ stubStreamWith(List.of(record("s1", "p1", "{\"type\":\"order\"}")));
+ InvokeResult err = new InvokeResult();
+ err.setFunctionError("Unhandled");
+ when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse))).thenReturn(err);
+ EventSourceMapping esm = esm("{\"data\":{\"type\":[\"order\"]}}");
+
+ poller.pollAndInvoke(esm);
+ verify(executorService, timeout(2000)).invoke(any(), any(), eq(InvocationType.RequestResponse));
+ // Barrier: a 2nd poll ran (so poll 1 finished). Since the checkpoint never advanced, both polls
+ // re-derive TRIM_HORIZON and fetch the same window.
+ awaitPollCompletedViaSecondFetch(esm);
+
+ verify(esmStore, never()).saveForAccount(eq(ACCOUNT), any());
+ assertNull(esm.getShardSequenceNumbers().get(SHARD));
+ // retry-from-old-checkpoint: both invokes carried the same fetched window.
+ ArgumentCaptor<byte[]> cap = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000).atLeast(2)).invoke(any(), cap.capture(), eq(InvocationType.RequestResponse));
+ List<byte[]> payloads = cap.getAllValues();
+ assertEquals(new String(payloads.get(0), StandardCharsets.UTF_8),
+ new String(payloads.get(payloads.size() - 1), StandardCharsets.UTF_8));
+ }
+
+ @Test
+ void throttleDoesNotAdvanceCheckpointAndRetriesSameWindow() {
+ stubFunction();
+ stubStreamWith(List.of(record("s1", "p1", "{\"type\":\"order\"}"),
+ record("s2", "p2", "{\"type\":\"refund\"}")));
+ // partial match (order) → invoke attempted → throttled → checkpoint must not advance
+ when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse)))
+ .thenThrow(new AwsException("TooManyRequestsException", "throttled", 429));
+ EventSourceMapping esm = esm("{\"data\":{\"type\":[\"order\"]}}");
+
+ poller.pollAndInvoke(esm);
+ verify(executorService, timeout(2000)).invoke(any(), any(), eq(InvocationType.RequestResponse));
+ awaitPollCompletedViaSecondFetch(esm);
+
+ verify(esmStore, never()).saveForAccount(eq(ACCOUNT), any());
+ assertNull(esm.getShardSequenceNumbers().get(SHARD));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java
index 9e9ae6f115..e398fcf1b3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
+import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -68,7 +69,8 @@ class LambdaArnInvocationAccountTest {
null,
null,
null,
- null);
+ null,
+ new ObjectMapper());
InvokeResult result = service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event);
@@ -129,7 +131,8 @@ class LambdaArnInvocationAccountTest {
null,
null,
null,
- null);
+ null,
+ new ObjectMapper());
InvokeResult versionResult = service.invokeArn(
functionArn + ":7", "{}".getBytes(), InvocationType.Event);
@@ -268,6 +271,7 @@ class LambdaArnInvocationAccountTest {
null,
null,
null,
- null);
+ null,
+ new ObjectMapper());
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEsmFilterCriteriaValidationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEsmFilterCriteriaValidationTest.java
new file mode 100644
index 0000000000..cbf5ec375b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEsmFilterCriteriaValidationTest.java
@@ -0,0 +1,240 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * Drives the package-private static {@code LambdaService.parseFilterCriteria} directly: the create/update
+ * validation is a pure function of the request map, so it is unit-testable without constructing the service
+ * (whose full wiring needs the Quarkus runtime, unavailable in this sandbox).
+ */
+class LambdaEsmFilterCriteriaValidationTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static Map<String, Object> reqWithCriteria(Object filterCriteria) {
+ Map<String, Object> req = new HashMap<>();
+ req.put("FilterCriteria", filterCriteria);
+ return req;
+ }
+
+ private static Map<String, Object> filtersReq(String... patterns) {
+ List<Object> filters = new ArrayList<>();
+ for (String p : patterns) {
+ Map<String, Object> f = new HashMap<>();
+ f.put("Pattern", p);
+ filters.add(f);
+ }
+ Map<String, Object> criteria = new HashMap<>();
+ criteria.put("Filters", filters);
+ return reqWithCriteria(criteria);
+ }
+
+ private static void assertRejected(Map<String, Object> request) {
+ AwsException ex = assertThrows(AwsException.class,
+ () -> LambdaService.parseFilterCriteria(request, MAPPER));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ }
+
+ // ──────────── match-element grammar (operator names, arity, operand types) ────────────
+
+ /**
+ * The three shapes that silently corrupted delivery before this validation existed. Each is a
+ * pattern the matcher cannot satisfy as written, and the failure direction differs per shape:
+ * a string operand coerced to zero so every positive value matched, an odd-length array skipped
+ * the comparison loop so every record matched, and an unknown comparison matched nothing so every
+ * record was checkpointed past or deleted.
+ */
+ @Test
+ void malformedNumericOperatorIsRejected() {
+ assertRejected(filtersReq("{\"value\":[{\"numeric\":[\">\",\"abc\"]}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"numeric\":[\">\"]}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"numeric\":[\"~\",3]}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"numeric\":[]}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"numeric\":\">5\"}]}"));
+ }
+
+ @Test
+ void validNumericOperatorIsAccepted() {
+ assertNotNull(LambdaService.parseFilterCriteria(
+ filtersReq("{\"value\":[{\"numeric\":[\">\",5]}]}"), MAPPER));
+ assertNotNull(LambdaService.parseFilterCriteria(
+ filtersReq("{\"value\":[{\"numeric\":[\">=\",1,\"<\",10]}]}"), MAPPER));
+ }
+
+ @Test
+ void unknownOperatorIsRejected() {
+ assertRejected(filtersReq("{\"value\":[{\"frobnicate\":[1]}]}"));
+ }
+
+ /** AWS documents these, the matcher does not implement them, so they fail loudly rather than drop records. */
+ @Test
+ void operatorAwsSupportsButFlociDoesNotIsRejected() {
+ assertRejected(filtersReq("{\"source\":[{\"cidr\":[\"10.0.0.0/8\"]}]}"));
+ assertRejected(filtersReq("{\"source\":[{\"wildcard\":[\"a*b\"]}]}"));
+ }
+
+ /** The matcher tests operators in a fixed order and honours only the first, so two is ambiguous. */
+ @Test
+ void multipleOperatorsInOneElementIsRejected() {
+ assertRejected(filtersReq("{\"value\":[{\"prefix\":\"a\",\"suffix\":\"z\"}]}"));
+ assertRejected(filtersReq("{\"value\":[{}]}"));
+ }
+
+ @Test
+ void wrongOperandTypeIsRejected() {
+ assertRejected(filtersReq("{\"value\":[{\"prefix\":5}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"suffix\":[\"z\"]}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"equals-ignore-case\":true}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"exists\":\"true\"}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"anything-but\":[]}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"anything-but\":[true]}]}"));
+ assertRejected(filtersReq("{\"value\":[{\"anything-but\":{\"suffix\":\"z\"}}]}"));
+ }
+
+ @Test
+ void supportedOperatorsAndLiteralsAreAccepted() {
+ assertNotNull(LambdaService.parseFilterCriteria(filtersReq(
+ "{\"a\":[\"literal\",5,null],"
+ + "\"b\":[{\"prefix\":\"p\"}],"
+ + "\"c\":[{\"suffix\":\"s\"}],"
+ + "\"d\":[{\"equals-ignore-case\":\"Q\"}],"
+ + "\"e\":[{\"exists\":false}],"
+ + "\"f\":[{\"anything-but\":\"x\"}],"
+ + "\"g\":[{\"anything-but\":[1,\"y\"]}],"
+ + "\"h\":[{\"anything-but\":{\"prefix\":\"z\"}}]}"), MAPPER));
+ }
+
+ /** Nested objects still recurse, so a malformed operator is caught at any depth. */
+ @Test
+ void malformedOperatorIsRejectedWhenNested() {
+ assertRejected(filtersReq("{\"body\":{\"inner\":[{\"numeric\":[\">\",\"abc\"]}]}}"));
+ }
+
+ /** A boolean literal is not a match value the matcher compares, so it can never match. */
+ @Test
+ void booleanLiteralMatchValueIsRejected() {
+ assertRejected(filtersReq("{\"value\":[true]}"));
+ }
+
+ // ──────────── accepted ────────────
+
+ @Test
+ void singleValidFilterParses() {
+ EventSourceMapping.FilterCriteria fc =
+ LambdaService.parseFilterCriteria(filtersReq("{\"data\":{\"type\":[\"buy\"]}}"), MAPPER);
+ assertNotNull(fc);
+ assertEquals(1, fc.getFilters().size());
+ assertEquals("{\"data\":{\"type\":[\"buy\"]}}", fc.getFilters().get(0).getPattern());
+ }
+
+ @Test
+ void fiveFiltersOk_nestedObjectMatchArrayAndEmptyObjectValuesAccepted() {
+ EventSourceMapping.FilterCriteria fc = LambdaService.parseFilterCriteria(filtersReq(
+ "{\"eventName\":[\"INSERT\"]}",
+ "{\"dynamodb\":{\"NewImage\":{\"s\":{\"S\":[\"x\"]}}}}",
+ "{\"body\":{\"status\":[\"active\"]}}",
+ "{\"data\":{\"n\":[{\"numeric\":[\">\",0]}]}}",
+ "{}"), MAPPER);
+ assertNotNull(fc);
+ assertEquals(5, fc.getFilters().size());
+ }
+
+ @Test
+ void absentEmptyObjectEmptyFiltersAndExplicitNullAllClear() {
+ assertNull(LambdaService.parseFilterCriteria(new HashMap<>(), MAPPER)); // absent
+ assertNull(LambdaService.parseFilterCriteria(reqWithCriteria(new HashMap<>()), MAPPER)); // {}
+ Map<String, Object> emptyFilters = new HashMap<>();
+ emptyFilters.put("Filters", new ArrayList<>());
+ assertNull(LambdaService.parseFilterCriteria(reqWithCriteria(emptyFilters), MAPPER)); // {"Filters":[]}
+ assertNull(LambdaService.parseFilterCriteria(reqWithCriteria(null), MAPPER)); // explicit null clears
+ }
+
+ // ──────────── rejected ────────────
+
+ @Test
+ void nonObjectCriteriaRejected() {
+ assertRejected(reqWithCriteria("not-an-object"));
+ }
+
+ @Test
+ void nonArrayFiltersRejected() {
+ Map<String, Object> c = new HashMap<>();
+ c.put("Filters", "nope");
+ assertRejected(reqWithCriteria(c));
+ }
+
+ @Test
+ void nonObjectFilterEntryRejected() {
+ Map<String, Object> c = new HashMap<>();
+ c.put("Filters", List.of("nope"));
+ assertRejected(reqWithCriteria(c));
+ }
+
+ @Test
+ void missingBlankAndNonStringPatternRejected() {
+ Map<String, Object> c1 = new HashMap<>();
+ c1.put("Filters", List.of(new HashMap<>())); // entry has no Pattern
+ assertRejected(reqWithCriteria(c1));
+ assertRejected(filtersReq(" ")); // blank Pattern
+ Map<String, Object> intPattern = new HashMap<>();
+ intPattern.put("Pattern", 5);
+ Map<String, Object> c2 = new HashMap<>();
+ c2.put("Filters", List.of(intPattern));
+ assertRejected(reqWithCriteria(c2)); // non-string Pattern
+ }
+
+ @Test
+ void tooManyFiltersRejected() {
+ assertRejected(filtersReq(
+ "{\"a\":[1]}", "{\"a\":[1]}", "{\"a\":[1]}", "{\"a\":[1]}", "{\"a\":[1]}", "{\"a\":[1]}"));
+ }
+
+ @Test
+ void oversizedPatternRejectedButBoundaryOk() {
+ // {"a":["<filler>"]}: fixed chars = 10, so filler 4086 → total exactly 4096.
+ String ok4096 = "{\"a\":[\"" + "x".repeat(4086) + "\"]}";
+ assertEquals(4096, ok4096.length());
+ assertNotNull(LambdaService.parseFilterCriteria(filtersReq(ok4096), MAPPER));
+ String over4097 = "{\"a\":[\"" + "x".repeat(4087) + "\"]}";
+ assertEquals(4097, over4097.length());
+ assertRejected(filtersReq(over4097));
+ }
+
+ @Test
+ void malformedJsonPatternRejected() {
+ assertRejected(filtersReq("{oops"));
+ }
+
+ @Test
+ void nonObjectRootPatternRejected() {
+ assertRejected(filtersReq("[1,2]"));
+ assertRejected(filtersReq("\"x\""));
+ assertRejected(filtersReq("5"));
+ }
+
+ @Test
+ void scalarValuePatternRejected() {
+ // Object root but a scalar value: the matcher can never satisfy this, so with enforcement
+ // active it would silently drop every record, so reject at create/update instead.
+ assertRejected(filtersReq("{\"eventName\":\"INSERT\"}"));
+ }
+
+ @Test
+ void emptyArrayValuePatternRejected() {
+ assertRejected(filtersReq("{\"a\":[]}"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java
index 1f3c24949a..7fc5c9ea2b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java
@@ -7,11 +7,13 @@ import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.vertx.core.Vertx;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.List;
@@ -22,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
@@ -57,7 +60,8 @@ class SqsEventSourcePollerTest {
functionStore,
mock(EsmStore.class),
config,
- OBJECT_MAPPER
+ OBJECT_MAPPER,
+ new PipesFilterMatcher(OBJECT_MAPPER)
);
}
@@ -394,4 +398,195 @@ class SqsEventSourcePollerTest {
assertEquals(firstTs.asText(), secondTs.asText(),
"ApproximateFirstReceiveTimestamp must not change between retries");
}
+
+ // ──────────────────────────── FilterCriteria ────────────────────────────
+
+ private EventSourceMapping esmWithFilter(int batchSize, String... patterns) {
+ EventSourceMapping esm = esm();
+ esm.setBatchSize(batchSize);
+ if (patterns.length > 0) {
+ EventSourceMapping.FilterCriteria fc = new EventSourceMapping.FilterCriteria();
+ List<EventSourceMapping.Filter> filters = new java.util.ArrayList<>();
+ for (String p : patterns) {
+ EventSourceMapping.Filter f = new EventSourceMapping.Filter();
+ f.setPattern(p);
+ filters.add(f);
+ }
+ fc.setFilters(filters);
+ esm.setFilterCriteria(fc);
+ }
+ return esm;
+ }
+
+ private Message msgBody(String id, String body) {
+ Message m = new Message();
+ m.setMessageId(id);
+ m.setReceiptHandle("rh-" + id);
+ m.setBody(body);
+ m.setSentTimestamp(Instant.now());
+ m.setFirstReceiveTimestamp(Instant.now());
+ return m;
+ }
+
+ private LambdaFunction stubThrowFn() {
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("throwfn");
+ fn.setTimeout(10);
+ when(functionStore.getForAccount("000000000000", "us-east-1", "throwfn")).thenReturn(Optional.of(fn));
+ return fn;
+ }
+
+ private void stubReceive(EventSourceMapping esm, List<Message> messages) {
+ when(sqsService.receiveMessage(eq(esm.getQueueUrl()), anyInt(), anyInt(), anyInt(), eq("us-east-1")))
+ .thenReturn(messages);
+ }
+
+ /**
+ * Hard happens-after barrier: re-stub the fetch to return empty, then re-kick until a SECOND
+ * receiveMessage is observed. {@code activePolls} serializes polls per ESM, so fetch #2 cannot begin until
+ * poll #1's finally-block ran, so poll #1 is fully complete. The empty re-stub makes poll #2 a no-op, so
+ * poll #1's exact delete/return counts are preserved for the assertions.
+ */
+ private void awaitPollCompleted(EventSourceMapping esm) {
+ when(sqsService.receiveMessage(eq(esm.getQueueUrl()), anyInt(), anyInt(), anyInt(), eq("us-east-1")))
+ .thenReturn(List.of());
+ long deadline = System.currentTimeMillis() + 5000;
+ while (true) {
+ poller.pollAndInvoke(esm);
+ try {
+ verify(sqsService, atLeast(2))
+ .receiveMessage(eq(esm.getQueueUrl()), anyInt(), anyInt(), anyInt(), eq("us-east-1"));
+ return;
+ } catch (AssertionError retry) {
+ if (System.currentTimeMillis() > deadline) {
+ throw retry;
+ }
+ try {
+ Thread.sleep(25);
+ } catch (InterruptedException ie) {
+ Thread.currentThread().interrupt();
+ throw retry;
+ }
+ }
+ }
+ }
+
+ private static final String BODY_PATTERN = "{\"body\":{\"type\":[\"order\"]}}";
+
+ @Test
+ void filterDeletesNonMatchingAndInvokesMatchedOnly() {
+ LambdaFunction fn = stubThrowFn();
+ EventSourceMapping esm = esmWithFilter(10, BODY_PATTERN);
+ Message m1 = msgBody("m1", "{\"type\":\"order\"}");
+ Message m2 = msgBody("m2", "{\"type\":\"refund\"}");
+ stubReceive(esm, List.of(m1, m2));
+ when(executorService.invoke(eq(fn), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult());
+
+ poller.pollAndInvoke(esm);
+
+ // Non-matching m2 is deleted immediately (consumed, per AWS SQS filtering).
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m2", "us-east-1");
+ // Only m1 is delivered to the function.
+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000)).invoke(eq(fn), payload.capture(), eq(InvocationType.RequestResponse));
+ try {
+ JsonNode records = OBJECT_MAPPER.readTree(payload.getValue()).get("Records");
+ assertEquals(1, records.size());
+ assertEquals("m1", records.get(0).get("messageId").asText());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ // m1 deleted after successful invoke; nothing returned to the queue.
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m1", "us-east-1");
+ verify(sqsService, never()).changeMessageVisibility(any(), any(), anyInt(), any());
+ }
+
+ @Test
+ void fullyFilteredBatchDeletesAllWithoutInvoking() {
+ stubThrowFn();
+ EventSourceMapping esm = esmWithFilter(10, BODY_PATTERN);
+ Message m1 = msgBody("m1", "{\"type\":\"refund\"}");
+ Message m2 = msgBody("m2", "{\"type\":\"chargeback\"}");
+ stubReceive(esm, List.of(m1, m2));
+
+ poller.pollAndInvoke(esm);
+
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m1", "us-east-1");
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m2", "us-east-1");
+ awaitPollCompleted(esm);
+ verify(executorService, never()).invoke(any(), any(byte[].class), any());
+ }
+
+ @Test
+ void invokeErrorStillConsumesFilteredOutButReturnsMatched() {
+ LambdaFunction fn = stubThrowFn();
+ EventSourceMapping esm = esmWithFilter(10, BODY_PATTERN);
+ Message m1 = msgBody("m1", "{\"type\":\"order\"}"); // matches
+ Message m2 = msgBody("m2", "{\"type\":\"refund\"}"); // filtered out
+ stubReceive(esm, List.of(m1, m2));
+ when(sqsService.getQueueAttributes(eq(esm.getQueueUrl()), any(), eq("us-east-1")))
+ .thenReturn(Map.of("VisibilityTimeout", "5"));
+ InvokeResult err = new InvokeResult();
+ err.setFunctionError("Handled");
+ when(executorService.invoke(eq(fn), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(err);
+
+ poller.pollAndInvoke(esm);
+
+ // Filtered-out m2 is consumed (deleted) regardless of the invoke outcome.
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m2", "us-east-1");
+ // Matched m1 failed → returned to the queue (visibility reset), NOT deleted.
+ verify(sqsService, timeout(2000)).changeMessageVisibility(esm.getQueueUrl(), "rh-m1", 5, "us-east-1");
+ awaitPollCompleted(esm);
+ verify(sqsService, never()).deleteMessage(esm.getQueueUrl(), "rh-m1", "us-east-1");
+ }
+
+ @Test
+ void batchItemFailureIdOfFilteredMessageIsInert() {
+ LambdaFunction fn = stubThrowFn();
+ EventSourceMapping esm = esmWithFilter(10, BODY_PATTERN);
+ esm.setFunctionResponseTypes(List.of("ReportBatchItemFailures"));
+ Message m1 = msgBody("m1", "{\"type\":\"order\"}"); // matches, delivered
+ Message m2 = msgBody("m2", "{\"type\":\"refund\"}"); // filtered out, deleted pre-invoke
+ stubReceive(esm, List.of(m1, m2));
+ // Function (defensively) reports the already-filtered id m2 as failed.
+ InvokeResult result = new InvokeResult();
+ result.setPayload("{\"batchItemFailures\":[{\"itemIdentifier\":\"m2\"}]}".getBytes());
+ when(executorService.invoke(eq(fn), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(result);
+
+ poller.pollAndInvoke(esm);
+
+ // m1 (delivered, not reported failed) is deleted post-success; m2 was deleted once as filtered-out.
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m1", "us-east-1");
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m2", "us-east-1");
+ awaitPollCompleted(esm);
+ // The stale failure id does not cause a second delete or a visibility reset.
+ verify(sqsService, never()).changeMessageVisibility(any(), any(), anyInt(), any());
+ }
+
+ @Test
+ void nonJsonBodyDroppedByObjectPattern() {
+ LambdaFunction fn = stubThrowFn();
+ EventSourceMapping esm = esmWithFilter(10, BODY_PATTERN);
+ Message m1 = msgBody("m1", "not json"); // dropped by object pattern
+ Message m2 = msgBody("m2", "{\"type\":\"order\"}"); // matches
+ stubReceive(esm, List.of(m1, m2));
+ when(executorService.invoke(eq(fn), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult());
+
+ poller.pollAndInvoke(esm);
+
+ verify(sqsService, timeout(2000)).deleteMessage(esm.getQueueUrl(), "rh-m1", "us-east-1");
+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
+ verify(executorService, timeout(2000)).invoke(eq(fn), payload.capture(), eq(InvocationType.RequestResponse));
+ try {
+ JsonNode records = OBJECT_MAPPER.readTree(payload.getValue()).get("Records");
+ assertEquals(1, records.size());
+ assertEquals("m2", records.get(0).get("messageId").asText());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
}