mirror of
https://github.com/floci-io/floci.git
synced 2026-11-30 08:55:17 -05:00
fix(lambda): apply FunctionResponseTypes on UpdateEventSourceMapping (#4584)
* fix(lambda): apply FunctionResponseTypes on UpdateEventSourceMapping UpdateEventSourceMapping ignored FunctionResponseTypes, so turning ReportBatchItemFailures on or off for an existing mapping succeeded but changed nothing: GetEventSourceMapping kept the old list and the pollers kept retrying whole batches. Apply the member when present, sharing the create path's parsing; an empty list clears it. * fix(lambda): validate FunctionResponseTypes on event source mappings AWS accepts at most one FunctionResponseTypes entry, and only ReportBatchItemFailures. Reject anything else with InvalidParameterValueException on both CreateEventSourceMapping and UpdateEventSourceMapping instead of storing it. * fix(lambda): validate every UpdateEventSourceMapping member before applying any A request that failed on a later member (FunctionName in another region, empty Topics) still changed the members parsed before it on the stored mapping, which the pollers share. A JSON null FunctionResponseTypes is now an absent member, and a non-array value is a SerializationException rather than silently clearing ReportBatchItemFailures. * fix(lambda): honour ReportBatchItemFailures on Kinesis event source mappings The Kinesis poller checkpointed the whole batch after a successful invoke, so records the function reported in batchItemFailures were never retried. It now checkpoints just before the lowest reported record and retries the whole batch on a malformed response, matching the DynamoDB Streams poller.
This commit is contained in:
1 parent
1d646c6fea
commit
e8b768382a
6 files changed
+386
-22
No files matched your search
+76
-2
@@ -26,8 +26,11 @@ import org.jboss.logging.Logger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -140,7 +143,8 @@ public class KinesisEventSourcePoller implements Resettable {
|
||||
// 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).
|
||||
// attempted and failed leaves the checkpoint unmoved (the whole window retries), and
|
||||
// reported batch item failures move it only up to the lowest failed record.
|
||||
String newestFetchedSeq = records.get(records.size() - 1).getSequenceNumber();
|
||||
|
||||
List<KinesisRecord> matched = records;
|
||||
@@ -174,7 +178,11 @@ public class KinesisEventSourcePoller implements Resettable {
|
||||
}
|
||||
|
||||
if (invokeResult.getFunctionError() == null) {
|
||||
advanceCheckpoint(esm, shard.getShardId(), newestFetchedSeq);
|
||||
String checkpoint = successfulInvocationCheckpoint(
|
||||
esm, invokeResult.getPayload(), lastSeq, records, matched);
|
||||
if (checkpoint != null && !checkpoint.equals(lastSeq)) {
|
||||
advanceCheckpoint(esm, shard.getShardId(), checkpoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -239,6 +247,72 @@ public class KinesisEventSourcePoller implements Resettable {
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sequence number to checkpoint after a successful invocation. With
|
||||
* {@code ReportBatchItemFailures} the shard resumes at the lowest reported failure; Floci
|
||||
* resumes {@code AFTER_SEQUENCE_NUMBER}, so that is the fetched record just before it. A
|
||||
* malformed {@code batchItemFailures} response retries the whole batch, as on AWS.
|
||||
*/
|
||||
private String successfulInvocationCheckpoint(EventSourceMapping esm, byte[] payload, String previousCheckpoint,
|
||||
List<KinesisRecord> fetched, List<KinesisRecord> delivered) {
|
||||
String newestFetchedSeq = fetched.get(fetched.size() - 1).getSequenceNumber();
|
||||
if (!esm.isReportBatchItemFailures() || payload == null || payload.length == 0) {
|
||||
return newestFetchedSeq;
|
||||
}
|
||||
|
||||
try {
|
||||
JsonNode failures = objectMapper.readTree(payload).get("batchItemFailures");
|
||||
if (failures == null || failures.isNull()) {
|
||||
return newestFetchedSeq;
|
||||
}
|
||||
if (!failures.isArray()) {
|
||||
return retryWholeBatch(esm, previousCheckpoint, "batchItemFailures is not an array");
|
||||
}
|
||||
|
||||
Map<String, Integer> fetchedIndexes = new HashMap<>();
|
||||
for (int i = 0; i < fetched.size(); i++) {
|
||||
fetchedIndexes.put(fetched.get(i).getSequenceNumber(), i);
|
||||
}
|
||||
Set<String> deliveredSequences = new HashSet<>();
|
||||
for (KinesisRecord rec : delivered) {
|
||||
deliveredSequences.add(rec.getSequenceNumber());
|
||||
}
|
||||
|
||||
int lowestFailedIndex = fetched.size();
|
||||
for (JsonNode item : failures) {
|
||||
JsonNode identifier = item.get("itemIdentifier");
|
||||
if (identifier == null || identifier.isNull() || identifier.asText().isEmpty()) {
|
||||
return retryWholeBatch(esm, previousCheckpoint,
|
||||
"entry has a missing, null or empty itemIdentifier");
|
||||
}
|
||||
String sequenceNumber = identifier.asText();
|
||||
Integer index = fetchedIndexes.get(sequenceNumber);
|
||||
if (index == null || !deliveredSequences.contains(sequenceNumber)) {
|
||||
return retryWholeBatch(esm, previousCheckpoint,
|
||||
"itemIdentifier " + sequenceNumber + " is not in the delivered batch");
|
||||
}
|
||||
lowestFailedIndex = Math.min(lowestFailedIndex, index);
|
||||
}
|
||||
|
||||
if (lowestFailedIndex == fetched.size()) {
|
||||
return newestFetchedSeq;
|
||||
}
|
||||
LOG.warnv("Kinesis ESM {0}: function reported batch item failures, resuming at {1}",
|
||||
esm.getUuid(), fetched.get(lowestFailedIndex).getSequenceNumber());
|
||||
return lowestFailedIndex == 0
|
||||
? previousCheckpoint
|
||||
: fetched.get(lowestFailedIndex - 1).getSequenceNumber();
|
||||
} catch (Exception e) {
|
||||
return retryWholeBatch(esm, previousCheckpoint, "response is not valid JSON: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String retryWholeBatch(EventSourceMapping esm, String previousCheckpoint, String reason) {
|
||||
LOG.warnv("Kinesis ESM {0}: malformed batchItemFailures response ({1}), retrying the whole batch",
|
||||
esm.getUuid(), reason);
|
||||
return previousCheckpoint;
|
||||
}
|
||||
|
||||
private void advanceCheckpoint(EventSourceMapping esm, String shardId, String newestSeq) {
|
||||
esm.getShardSequenceNumbers().put(shardId, newestSeq);
|
||||
esmStore.saveForAccount(esm.getAccountId(), esm);
|
||||
|
||||
@@ -55,6 +55,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -85,6 +86,7 @@ public class LambdaService implements ResourceProvider {
|
||||
private static final Pattern HANDLER_PATTERN = Pattern.compile("\\S+");
|
||||
private static final int MAX_HANDLER_LENGTH = 128;
|
||||
private static final List<String> FUNCTION_ARCHITECTURES = List.of("x86_64", "arm64");
|
||||
private static final List<String> FUNCTION_RESPONSE_TYPES = List.of("ReportBatchItemFailures");
|
||||
|
||||
/**
|
||||
* Structure members {@code UpdateFunctionConfiguration} accepts. Shape-checked before the
|
||||
@@ -1234,10 +1236,7 @@ public class LambdaService implements ResourceProvider {
|
||||
Integer maximumBatchingWindowInSeconds = parseMaximumBatchingWindow(request);
|
||||
boolean enabled = !Boolean.FALSE.equals(request.get("Enabled"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> functionResponseTypes = request.get("FunctionResponseTypes") instanceof List
|
||||
? (List<String>) request.get("FunctionResponseTypes")
|
||||
: new ArrayList<>();
|
||||
List<String> functionResponseTypes = parseFunctionResponseTypes(request);
|
||||
|
||||
ScalingConfig scalingConfig = parseScalingConfig(request, eventSourceArn);
|
||||
|
||||
@@ -1321,6 +1320,35 @@ public class LambdaService implements ResourceProvider {
|
||||
return destinationConfig;
|
||||
}
|
||||
|
||||
static List<String> parseFunctionResponseTypes(Map<String, Object> request) {
|
||||
Object raw = request.get("FunctionResponseTypes");
|
||||
if (raw == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
if (!(raw instanceof List<?> types)) {
|
||||
throw new AwsException("SerializationException",
|
||||
"FunctionResponseTypes must be a JSON array or null", 400);
|
||||
}
|
||||
if (types.size() > 1) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"1 validation error detected: Value '" + types + "' at 'functionResponseTypes' "
|
||||
+ "failed to satisfy constraint: Member must have length less than or equal to 1",
|
||||
400);
|
||||
}
|
||||
List<String> validated = new ArrayList<>();
|
||||
for (Object type : types) {
|
||||
if (!FUNCTION_RESPONSE_TYPES.contains(type)) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"1 validation error detected: Value '" + types + "' at 'functionResponseTypes' "
|
||||
+ "failed to satisfy constraint: Member must satisfy constraint: "
|
||||
+ "[Member must satisfy enum value set: " + FUNCTION_RESPONSE_TYPES + "]",
|
||||
400);
|
||||
}
|
||||
validated.add((String) type);
|
||||
}
|
||||
return validated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -1755,43 +1783,63 @@ public class LambdaService implements ResourceProvider {
|
||||
|
||||
boolean wasEnabled = esm.isEnabled();
|
||||
|
||||
// The stored mapping is shared with the pollers, so every member is validated before any
|
||||
// of them is applied: a request that fails validation must leave the mapping unchanged.
|
||||
List<Consumer<EventSourceMapping>> changes = new ArrayList<>();
|
||||
|
||||
if (request.containsKey("BatchSize")) {
|
||||
esm.setBatchSize(toInt(request.get("BatchSize"), esm.getBatchSize()));
|
||||
int batchSize = toInt(request.get("BatchSize"), esm.getBatchSize());
|
||||
changes.add(m -> m.setBatchSize(batchSize));
|
||||
}
|
||||
if (request.containsKey("MaximumBatchingWindowInSeconds")) {
|
||||
esm.setMaximumBatchingWindowInSeconds(parseMaximumBatchingWindow(request));
|
||||
Integer batchingWindow = parseMaximumBatchingWindow(request);
|
||||
changes.add(m -> m.setMaximumBatchingWindowInSeconds(batchingWindow));
|
||||
}
|
||||
if (request.containsKey("Enabled")) {
|
||||
boolean nowEnabled = !Boolean.FALSE.equals(request.get("Enabled"));
|
||||
esm.setEnabled(nowEnabled);
|
||||
esm.setState(nowEnabled ? "Enabled" : "Disabled");
|
||||
changes.add(m -> {
|
||||
m.setEnabled(nowEnabled);
|
||||
m.setState(nowEnabled ? "Enabled" : "Disabled");
|
||||
});
|
||||
}
|
||||
if (request.containsKey("ScalingConfig")) {
|
||||
// AWS: passing ScalingConfig resets it. An empty object or one
|
||||
// with MaximumConcurrency=null clears the cap.
|
||||
esm.setScalingConfig(parseScalingConfig(request, esm.getEventSourceArn()));
|
||||
ScalingConfig scalingConfig = parseScalingConfig(request, esm.getEventSourceArn());
|
||||
changes.add(m -> m.setScalingConfig(scalingConfig));
|
||||
}
|
||||
|
||||
if (request.containsKey("BisectBatchOnFunctionError")) {
|
||||
Object raw = request.get("BisectBatchOnFunctionError");
|
||||
esm.setBisectBatchOnFunctionError(raw instanceof Boolean b ? b : null);
|
||||
Boolean bisect = request.get("BisectBatchOnFunctionError") instanceof Boolean b ? b : null;
|
||||
changes.add(m -> m.setBisectBatchOnFunctionError(bisect));
|
||||
}
|
||||
|
||||
if (request.containsKey("MaximumRetryAttempts")) {
|
||||
esm.setMaximumRetryAttempts(parseMaximumRetryAttempts(request));
|
||||
Integer maximumRetryAttempts = parseMaximumRetryAttempts(request);
|
||||
changes.add(m -> m.setMaximumRetryAttempts(maximumRetryAttempts));
|
||||
}
|
||||
if (request.containsKey("MaximumRecordAgeInSeconds")) {
|
||||
esm.setMaximumRecordAgeInSeconds(parseMaximumRecordAgeInSeconds(request));
|
||||
Integer maximumRecordAge = parseMaximumRecordAgeInSeconds(request);
|
||||
changes.add(m -> m.setMaximumRecordAgeInSeconds(maximumRecordAge));
|
||||
}
|
||||
|
||||
if (request.containsKey("DestinationConfig")) {
|
||||
esm.setDestinationConfig(parseDestinationConfig(request));
|
||||
EventSourceMapping.DestinationConfig destinationConfig = parseDestinationConfig(request);
|
||||
changes.add(m -> m.setDestinationConfig(destinationConfig));
|
||||
}
|
||||
|
||||
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));
|
||||
EventSourceMapping.FilterCriteria filterCriteria = parseFilterCriteria(request, objectMapper);
|
||||
changes.add(m -> m.setFilterCriteria(filterCriteria));
|
||||
}
|
||||
|
||||
if (request.get("FunctionResponseTypes") != null) {
|
||||
// AWS: passing FunctionResponseTypes replaces the list; an empty list turns
|
||||
// ReportBatchItemFailures off. A JSON null is an absent member and changes nothing.
|
||||
List<String> functionResponseTypes = parseFunctionResponseTypes(request);
|
||||
changes.add(m -> m.setFunctionResponseTypes(functionResponseTypes));
|
||||
}
|
||||
|
||||
if (request.containsKey("FunctionName")) {
|
||||
@@ -1803,8 +1851,10 @@ public class LambdaService implements ResourceProvider {
|
||||
"Function ARN region '" + fnRef.region() + "' does not match event source region '" + esm.getRegion() + "'", 400);
|
||||
}
|
||||
ResolvedFunctionTarget target = resolveFunctionTarget(esm.getRegion(), fnRef);
|
||||
esm.setFunctionArn(target.functionArn());
|
||||
esm.setFunctionName(target.functionName());
|
||||
changes.add(m -> {
|
||||
m.setFunctionArn(target.functionArn());
|
||||
m.setFunctionName(target.functionName());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1822,7 +1872,7 @@ public class LambdaService implements ResourceProvider {
|
||||
}
|
||||
validatedTopics.add(s);
|
||||
}
|
||||
esm.setTopics(validatedTopics);
|
||||
changes.add(m -> m.setTopics(validatedTopics));
|
||||
}
|
||||
|
||||
if (request.containsKey("SourceAccessConfigurations")) {
|
||||
@@ -1842,12 +1892,13 @@ public class LambdaService implements ResourceProvider {
|
||||
Map<String, Object> typedMap = (Map<String, Object>) m;
|
||||
typedAccess.add(typedMap);
|
||||
}
|
||||
esm.setSourceAccessConfigurations(typedAccess);
|
||||
changes.add(m -> m.setSourceAccessConfigurations(typedAccess));
|
||||
} else {
|
||||
esm.setSourceAccessConfigurations(null);
|
||||
changes.add(m -> m.setSourceAccessConfigurations(null));
|
||||
}
|
||||
}
|
||||
|
||||
changes.forEach(change -> change.accept(esm));
|
||||
esm.setLastModified(System.currentTimeMillis());
|
||||
esmStore.save(esm);
|
||||
|
||||
|
||||
Reference in new issue
Block a user