mirror of
https://github.com/floci-io/floci.git
synced 2026-11-25 06:47:41 -05:00
fix(lambda): persist, validate and enforce event source mapping FilterCriteria (#3060)
* fix(lambda): persist and validate event source mapping FilterCriteria
CreateEventSourceMapping/UpdateEventSourceMapping accepted FilterCriteria,
returned 200, then silently dropped it (get-event-source-mapping reported
null): EventSourceMapping had no such field and the hand-maintained
parse/response allowlists never mentioned it.
Persist it as a typed nested FilterCriteria/Filter on EventSourceMapping
(Jackson round-trips it via EsmStore); parse and validate it at create and
update (well-formed JSON object patterns whose values are non-empty match
arrays or nested objects; max 5 filters; max 4096-char pattern; empty
object / empty Filters / null clear); echo it back omit-when-unset. Add
EsmFilterCriteriaUtils to wrap a stored FilterCriteria as the
{"FilterCriteria":{"Filters":[...]}} node PipesFilterMatcher consumes and
to correlate matched records to their sources by identity.
Poller enforcement (Kinesis/DynamoDB/SQS) follows in a separate change.
* fix(lambda): enforce event source mapping FilterCriteria in the pollers
Round 1 persisted and validated FilterCriteria; this wires it into the three
Lambda event-source pollers so filters actually take effect, reusing the
existing PipesFilterMatcher (unchanged) via EsmFilterCriteriaUtils.
- Kinesis: filter against the AWS dialect, top-level base64-DECODED `data`
(plus `partitionKey`), while the delivered event keeps `kinesis.data`
base64. The shard checkpoint now advances to the newest FETCHED sequence
whenever a batch is disposed of (successful invoke OR fully filtered out),
so filtered-out records are consumed rather than re-read forever; an invoke
that errors or is throttled still leaves the checkpoint unmoved.
- DynamoDB Streams: same checkpoint discipline; the per-record node
(top-level eventName + dynamodb.*) is both the delivery and filter shape.
- SQS: non-matching messages are deleted immediately (AWS consumes filtered
SQS messages), a fully-filtered batch returns without invoking, and all
post-filter delete/return logic operates only on the matched subset.
Unfiltered mappings are unchanged (no filter nodes built, same list reference).
Adds KinesisEventSourcePollerTest and extends the DynamoDB/SQS poller tests
(matching-only delivery, fully-filtered checkpoint-advance/delete, invoke-error
and throttle no-advance with same-window retry, dialect pin, non-JSON drop).
Also documents FilterCriteria in docs/services/lambda.md.
* style(lambda): remove em dashes from lines this branch adds
AGENTS.md requires colons, commas or periods instead of em dashes. Comment,
javadoc and docs prose only; no code or string literals change.
* fix(lambda): validate filter-pattern operators, arity and operand types
The structural check accepted any non-empty match array, so a malformed operator
reached the matcher and corrupted delivery silently, in whichever direction the
matcher happened to fail. {"numeric":[">","abc"]} coerced its operand to zero and
matched every positive value; {"numeric":[">"]} matched every record because the
comparison loop never ran; an unknown operator matched nothing, so the pollers
checkpointed past or deleted every record. Enforcement makes an unsatisfiable
pattern destructive rather than inert, so it is now rejected at create/update.
Each match element must be a string, number, null, or an object carrying exactly
one operator. Operands are checked per operator, and numeric must be a sequence
of comparison/value pairs. An operator AWS documents but the matcher does not
implement (cidr, wildcard) is rejected with a distinct message rather than
silently dropping records. This couples the validator to PipesFilterMatcher's
operator set, which the previous comment avoided on purpose; that trade no longer
holds now the pollers act on the result.
Stricter than AWS for cidr, wildcard and boolean literals, all of which AWS
accepts. Docs record the deviation and the reason.
This commit is contained in:
1 parent
f00fb4c289
commit
5512db0e05
17 files changed
+2159
-112
No files matched your search
+70
-29
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+80
-19
@@ -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;
|
||||
}
|
||||
|
||||
if (invokeResult.getFunctionError() == null) {
|
||||
String newestSeq = records.get(records.size() - 1).getSequenceNumber();
|
||||
esm.getShardSequenceNumbers().put(shard.getShardId(), newestSeq);
|
||||
esmStore.saveForAccount(esm.getAccountId(), esm);
|
||||
// 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 (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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
+105
-57
@@ -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
|
||||
|
||||
+43
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user