feat(lambda): support self-managed Apache Kafka event source mappings (#3062) (#3082)

* feat(lambda): support self-managed Apache Kafka event source mappings (#3062)

- Add SelfManagedEventSource, Topics, and SourceAccessConfigurations metadata to EventSourceMapping
- Omit EventSourceArn in REST response when null to comply with AWS wire protocol
- Support Kafka source discrimination in LambdaService and guard pollers against null EventSourceArn
- Forward Kafka ESM properties in CloudFormation provisioner
- Add serialization, service, integration, and CloudFormation tests

* fix(lambda): address review comments for self-managed Kafka ESM

* fix(lambda): handle batch size validation, function target update, and cfn access config clearing

* fix(lambda): bind qualified function targets correctly in event source mappings

* fix(cloudformation): use CfnDeletes.safeDelete in Lambda ESM provisioner

* fix(cloudformation): throw AwsException on missing FunctionName in Lambda ESM provisioner

* fix(lambda): handle create-only ESM update, allow AT_TIMESTAMP for Kafka and populate EventSourceMappingArn

* test(cloudformation): assert exact Fn::GetAtt attributes for Lambda ESM
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-05 23:41:44 -04:00
1 parent 025ac714f6
commit ee5c87d6d6
13 files changed
+1450 -97

No files matched your search

@@ -256,7 +256,6 @@ public class CloudFormationResourceProvisioner {
"AWS::IAM::ManagedPolicy",
"AWS::IAM::Policy",
"AWS::IAM::User",
"AWS::Lambda::EventSourceMapping",
"AWS::Lambda::Function",
"AWS::Lambda::LayerVersion",
"AWS::RDS::DBCluster",
@@ -452,8 +451,6 @@ public class CloudFormationResourceProvisioner {
region,
accountId,
stackName);
case "AWS::Lambda::EventSourceMapping" ->
provisionLambdaEventSourceMapping(resource, properties, engine, region);
case "AWS::Cognito::UserPool" ->
provisionCognitoUserPool(resource, properties, engine, region, accountId, stackName);
case "AWS::Cognito::UserPoolClient" ->
@@ -744,7 +741,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId);
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);
case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);
case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);
@@ -4115,58 +4111,6 @@ public class CloudFormationResourceProvisioner {
}
}
// ── Lambda EventSourceMapping ─────────────────────────────────────────────
private void provisionLambdaEventSourceMapping(StackResource r, JsonNode props,
CloudFormationTemplateEngine engine, String region) {
Map<String, Object> req = new HashMap<>();
req.put("FunctionName", resolveOptional(props, "FunctionName", engine));
req.put("EventSourceArn", resolveOptional(props, "EventSourceArn", engine));
String enabledStr = resolveOptional(props, "Enabled", engine);
if (enabledStr != null) {
req.put("Enabled", Boolean.parseBoolean(enabledStr));
}
String batchSize = resolveOptional(props, "BatchSize", engine);
if (batchSize != null) {
try { req.put("BatchSize", Integer.parseInt(batchSize)); } catch (NumberFormatException ignored) {}
}
String startingPosition = resolveOptional(props, "StartingPosition", engine);
if (startingPosition != null) {
req.put("StartingPosition", startingPosition);
}
String startingPositionTimestamp = resolveOptional(props, "StartingPositionTimestamp", engine);
if (startingPositionTimestamp != null) {
try {
double timestamp = Double.parseDouble(startingPositionTimestamp);
if (!Double.isFinite(timestamp)) {
throw new NumberFormatException("Non-finite timestamp");
}
req.put("StartingPositionTimestamp", timestamp);
} catch (NumberFormatException e) {
// Not swallowed the way BatchSize above is: dropping this one degrades into the
// "StartingPositionTimestamp is required" error from the service, which points at
// the wrong problem and hides the value that actually failed to parse. Double.parseDouble
// accepts "NaN"/"Infinity"/"-Infinity" without throwing, so isFinite is checked explicitly
// to keep those from silently becoming epoch-zero or long-extremum timestamps downstream.
throw new AwsException("ValidationError",
"Value of property StartingPositionTimestamp must be a number.", 400);
}
}
List<String> functionResponseTypes = resolveStringList(props, "FunctionResponseTypes", engine);
if (!functionResponseTypes.isEmpty()) {
req.put("FunctionResponseTypes", functionResponseTypes);
}
var esm = lambdaService.createEventSourceMapping(region, req);
r.setPhysicalId(esm.getUuid());
r.getAttributes().put("Id", esm.getUuid());
}
// ── Pipes ──────────────────────────────────────────────────────────────────
private void provisionStepFunctionsStateMachine(StackResource r, JsonNode props,
@@ -0,0 +1,183 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::Lambda::EventSourceMapping}.
*/
@ApplicationScoped
public class LambdaEventSourceMappingCfnProvisioner implements CfnResourceProvisioner {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final LambdaService lambdaService;
@Inject
public LambdaEventSourceMappingCfnProvisioner(LambdaService lambdaService) {
this.lambdaService = lambdaService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::Lambda::EventSourceMapping");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
if (!"AWS::Lambda::EventSourceMapping".equals(r.getResourceType())) {
throw new IllegalStateException(
"LambdaEventSourceMappingCfnProvisioner cannot handle " + r.getResourceType());
}
Map<String, Object> req = new HashMap<>();
String functionName = ctx.resolveOptional(props, "FunctionName");
if (functionName == null || functionName.isBlank()) {
throw new AwsException("ValidationError",
"Property FunctionName is required for AWS::Lambda::EventSourceMapping", 400);
}
req.put("FunctionName", functionName);
String eventSourceArn = ctx.resolveOptional(props, "EventSourceArn");
if (eventSourceArn != null) {
req.put("EventSourceArn", eventSourceArn);
}
String enabledStr = ctx.resolveOptional(props, "Enabled");
if (enabledStr != null) {
req.put("Enabled", Boolean.parseBoolean(enabledStr));
}
String batchSize = ctx.resolveOptional(props, "BatchSize");
if (batchSize != null) {
try {
req.put("BatchSize", Integer.parseInt(batchSize));
} catch (NumberFormatException e) {
throw new AwsException("ValidationError",
"Value of property BatchSize must be an integer.", 400);
}
}
String startingPosition = ctx.resolveOptional(props, "StartingPosition");
if (startingPosition != null) {
req.put("StartingPosition", startingPosition);
}
String startingPositionTimestamp = ctx.resolveOptional(props, "StartingPositionTimestamp");
if (startingPositionTimestamp != null) {
try {
double timestamp = Double.parseDouble(startingPositionTimestamp);
if (!Double.isFinite(timestamp)) {
throw new NumberFormatException("Non-finite timestamp");
}
req.put("StartingPositionTimestamp", timestamp);
} catch (NumberFormatException e) {
throw new AwsException("ValidationError",
"Value of property StartingPositionTimestamp must be a number.", 400);
}
}
List<String> functionResponseTypes = ctx.resolveStringList(props, "FunctionResponseTypes");
if (!functionResponseTypes.isEmpty()) {
req.put("FunctionResponseTypes", functionResponseTypes);
}
if (props != null && props.has("SelfManagedEventSource")) {
JsonNode resolvedSource = ctx.engine().resolveNode(props.get("SelfManagedEventSource"));
if (resolvedSource != null && !resolvedSource.isNull()) {
req.put("SelfManagedEventSource", MAPPER.convertValue(resolvedSource, Map.class));
}
}
List<String> topics = ctx.resolveStringList(props, "Topics");
if (!topics.isEmpty()) {
req.put("Topics", topics);
}
if (props != null && props.has("SourceAccessConfigurations") && !props.get("SourceAccessConfigurations").isNull()) {
JsonNode resolvedAccess = ctx.engine().resolveNode(props.get("SourceAccessConfigurations"));
if (resolvedAccess != null && !resolvedAccess.isNull()) {
req.put("SourceAccessConfigurations", MAPPER.convertValue(resolvedAccess, List.class));
}
} else if (ctx.isUpdate()) {
req.put("SourceAccessConfigurations", null);
}
if (ctx.isUpdate() && ctx.priorPhysicalId() != null) {
String uuid = ctx.priorPhysicalId();
EventSourceMapping existing = findExisting(uuid);
if (existing != null) {
rejectIfChanged("EventSourceArn", existing.getEventSourceArn(), (String) req.get("EventSourceArn"));
rejectIfChanged("StartingPosition", existing.getStartingPosition(), (String) req.get("StartingPosition"));
Long existingTs = existing.getStartingPositionTimestamp();
Long requestedTs = req.get("StartingPositionTimestamp") instanceof Number num
? Math.round(num.doubleValue() * 1000.0)
: null;
if (!Objects.equals(existingTs, requestedTs)) {
throw new AwsException("ValidationError",
"Updating StartingPositionTimestamp requires resource replacement, which is not supported.", 400);
}
if (!Objects.equals(existing.getSelfManagedEventSource(), req.get("SelfManagedEventSource"))) {
throw new AwsException("ValidationError",
"Updating SelfManagedEventSource requires resource replacement, which is not supported.", 400);
}
}
lambdaService.updateEventSourceMapping(uuid, req);
String esmArn = AwsArnUtils.Arn.of("lambda", ctx.region(), ctx.accountId(), "event-source-mapping:" + uuid).toString();
r.setPhysicalId(uuid);
r.getAttributes().put("Id", uuid);
r.getAttributes().put("EventSourceMappingArn", esmArn);
} else {
var esm = lambdaService.createEventSourceMapping(ctx.region(), req);
String esmArn = AwsArnUtils.Arn.of("lambda", ctx.region(), ctx.accountId(), "event-source-mapping:" + esm.getUuid()).toString();
r.setPhysicalId(esm.getUuid());
r.getAttributes().put("Id", esm.getUuid());
r.getAttributes().put("EventSourceMappingArn", esmArn);
}
}
private EventSourceMapping findExisting(String uuid) {
try {
return lambdaService.getEventSourceMapping(uuid);
} catch (AwsException e) {
if ("ResourceNotFoundException".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
private void rejectIfChanged(String property, String existing, String requested) {
String a = existing == null || existing.isBlank() ? null : existing;
String b = requested == null || requested.isBlank() ? null : requested;
if (Objects.equals(a, b)) {
return;
}
throw new AwsException("ValidationError",
"Updating " + property + " requires resource replacement, which is not supported.", 400);
}
@Override
public void delete(String resourceType, String physicalId, String region) {
if (!"AWS::Lambda::EventSourceMapping".equals(resourceType) || physicalId == null) {
return;
}
CfnDeletes.safeDelete("event source mapping", physicalId,
() -> lambdaService.deleteEventSourceMapping(physicalId), "ResourceNotFoundException");
}
}
@@ -341,11 +341,13 @@ public class LambdaController {
return Response.status(202).entity(buildEsmResponse(esm)).build();
}
private Map<String, Object> buildEsmResponse(EventSourceMapping esm) {
Map<String, Object> buildEsmResponse(EventSourceMapping esm) {
ObjectNode node = objectMapper.createObjectNode();
node.put("UUID", esm.getUuid());
node.put("FunctionArn", esm.getFunctionArn());
node.put("EventSourceArn", esm.getEventSourceArn());
if (esm.getEventSourceArn() != null) {
node.put("EventSourceArn", esm.getEventSourceArn());
}
node.put("BatchSize", esm.getBatchSize());
node.put("State", esm.getState());
node.put("LastModified", (double) esm.getLastModified() / 1000.0);
@@ -370,6 +372,19 @@ public class LambdaController {
onFailure.put("Destination", esm.getDestinationConfig().getOnFailure().getDestination());
}
if (esm.getSelfManagedEventSource() != null) {
node.set("SelfManagedEventSource", objectMapper.valueToTree(esm.getSelfManagedEventSource()));
}
if (esm.getTopics() != null && !esm.getTopics().isEmpty()) {
ArrayNode topicsNode = node.putArray("Topics");
esm.getTopics().forEach(topicsNode::add);
}
if (esm.getSourceAccessConfigurations() != null && !esm.getSourceAccessConfigurations().isEmpty()) {
node.set("SourceAccessConfigurations", objectMapper.valueToTree(esm.getSourceAccessConfigurations()));
}
if (esm.getFunctionResponseTypes() != null) {
esm.getFunctionResponseTypes().forEach(responseTypes::add);
}
@@ -162,8 +162,8 @@ public class LambdaService implements ResourceProvider {
this.zipExtractor = zipExtractor;
this.config = config;
this.regionResolver = regionResolver;
this.esmStore = null;
this.aliasStore = null;
this.esmStore = storageFactory != null ? new EsmStore(storageFactory) : null;
this.aliasStore = storageFactory != null ? new LambdaAliasStore(storageFactory) : null;
this.s3Service = null;
this.sqsService = null;
this.poller = null;
@@ -555,6 +555,28 @@ public class LambdaService implements ResourceProvider {
}
}
private record ResolvedFunctionTarget(String functionArn, String functionName) {}
private ResolvedFunctionTarget resolveFunctionTarget(String region, LambdaArnUtils.ResolvedFunctionRef fnRef) {
String name = fnRef.name();
LambdaFunction fn = getFunction(region, name);
String qualifier = fnRef.qualifier();
if (qualifier == null) {
return new ResolvedFunctionTarget(fn.getFunctionArn(), name);
}
if ("$LATEST".equals(qualifier)) {
return new ResolvedFunctionTarget(fn.getFunctionArn() + ":$LATEST", name);
}
if (qualifier.chars().allMatch(Character::isDigit)) {
LambdaFunction versionFn = functionStore.get(region, name, qualifier)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Function version not found: " + name + ":" + qualifier, 404));
return new ResolvedFunctionTarget(versionFn.getFunctionArn(), name);
}
LambdaAlias alias = getAlias(region, name, qualifier);
return new ResolvedFunctionTarget(alias.getAliasArn(), name);
}
public List<LambdaFunction> listFunctions(String region) {
return functionStore.list(region);
}
@@ -1047,42 +1069,132 @@ public class LambdaService implements ResourceProvider {
validateEventSourceMappingStructures(request);
String functionName = (String) request.get("FunctionName");
String eventSourceArn = (String) request.get("EventSourceArn");
if (functionName == null || functionName.isBlank()) {
throw new AwsException("InvalidParameterValueException", "FunctionName is required", 400);
}
if (eventSourceArn == null || eventSourceArn.isBlank()) {
throw new AwsException("InvalidParameterValueException", "EventSourceArn is required", 400);
}
if (!eventSourceArn.contains(":sqs:") && !eventSourceArn.contains(":kinesis:")
&& !eventSourceArn.contains(":dynamodb:")) {
throw new AwsException("InvalidParameterValueException",
"Only SQS, Kinesis, and DynamoDB Streams event sources are supported.", 400);
}
// Resolve function — supports bare name, partial ARN, or full ARN
LambdaArnUtils.ResolvedFunctionRef fnRef = LambdaArnUtils.resolve(functionName);
String resolvedName = fnRef.name();
// Extract region from the event source ARN (parts[3] for all supported ARN formats)
boolean hasKafkaSource = request.containsKey("SelfManagedEventSource") && request.get("SelfManagedEventSource") != null;
boolean hasTopics = request.containsKey("Topics") && request.get("Topics") != null;
boolean hasEventSourceArn = request.containsKey("EventSourceArn") && request.get("EventSourceArn") != null;
boolean isSelfManagedKafka = hasKafkaSource || hasTopics;
String eventSourceArn;
String resolvedRegion;
if (eventSourceArn.contains(":sqs:")) {
resolvedRegion = SqsEventSourcePoller.regionFromArn(eventSourceArn);
Map<String, Object> selfManagedEventSource = null;
List<String> topics = null;
List<Map<String, Object>> sourceAccessConfigurations = null;
if (isSelfManagedKafka) {
if (hasEventSourceArn) {
throw new AwsException("InvalidParameterValueException",
"Cannot specify both EventSourceArn and SelfManagedEventSource/Topics", 400);
}
if (!hasKafkaSource) {
throw new AwsException("InvalidParameterValueException",
"SelfManagedEventSource is required for self-managed Apache Kafka event sources", 400);
}
if (!hasTopics) {
throw new AwsException("InvalidParameterValueException",
"Topics is required for self-managed Apache Kafka event sources", 400);
}
eventSourceArn = null;
enforceRegion(region, fnRef);
resolvedRegion = region;
Object rawSource = request.get("SelfManagedEventSource");
if (!(rawSource instanceof Map<?, ?> sourceMap)) {
throw new AwsException("InvalidParameterValueException",
"SelfManagedEventSource must be a JSON object", 400);
}
Object rawEndpoints = sourceMap.get("Endpoints");
if (!(rawEndpoints instanceof Map<?, ?> endpointsMap)) {
throw new AwsException("InvalidParameterValueException",
"SelfManagedEventSource must contain Endpoints", 400);
}
Object rawServers = endpointsMap.get("KAFKA_BOOTSTRAP_SERVERS");
if (!(rawServers instanceof List<?> serverList) || serverList.isEmpty()) {
throw new AwsException("InvalidParameterValueException",
"SelfManagedEventSource must contain KAFKA_BOOTSTRAP_SERVERS", 400);
}
for (Object server : serverList) {
if (!(server instanceof String s) || s.isBlank()) {
throw new AwsException("InvalidParameterValueException",
"KAFKA_BOOTSTRAP_SERVERS elements must be non-blank strings", 400);
}
}
@SuppressWarnings("unchecked")
Map<String, Object> typedSource = (Map<String, Object>) rawSource;
selfManagedEventSource = typedSource;
Object rawTopics = request.get("Topics");
if (!(rawTopics instanceof List<?> topicList) || topicList.isEmpty()) {
throw new AwsException("InvalidParameterValueException",
"Topics must be a non-empty list of strings", 400);
}
List<String> validatedTopics = new ArrayList<>();
for (Object item : topicList) {
if (!(item instanceof String s) || s.isBlank()) {
throw new AwsException("InvalidParameterValueException",
"Topics elements must be non-blank strings", 400);
}
validatedTopics.add(s);
}
topics = validatedTopics;
if (request.containsKey("SourceAccessConfigurations")) {
Object rawAccess = request.get("SourceAccessConfigurations");
if (rawAccess != null) {
if (!(rawAccess instanceof List<?> accessList)) {
throw new AwsException("InvalidParameterValueException",
"SourceAccessConfigurations must be a list", 400);
}
List<Map<String, Object>> typedAccess = new ArrayList<>();
for (Object item : accessList) {
if (!(item instanceof Map<?, ?> m)) {
throw new AwsException("InvalidParameterValueException",
"SourceAccessConfiguration entries must be JSON objects", 400);
}
@SuppressWarnings("unchecked")
Map<String, Object> typedMap = (Map<String, Object>) m;
typedAccess.add(typedMap);
}
sourceAccessConfigurations = typedAccess;
}
}
} else {
// arn:aws:kinesis:region:... or arn:aws:dynamodb:region:...
resolvedRegion = AwsArnUtils.regionOrDefault(eventSourceArn, region);
eventSourceArn = (String) request.get("EventSourceArn");
if (eventSourceArn == null || eventSourceArn.isBlank()) {
throw new AwsException("InvalidParameterValueException", "EventSourceArn is required", 400);
}
if (!eventSourceArn.contains(":sqs:") && !eventSourceArn.contains(":kinesis:")
&& !eventSourceArn.contains(":dynamodb:")) {
throw new AwsException("InvalidParameterValueException",
"Only SQS, Kinesis, and DynamoDB Streams event sources are supported.", 400);
}
// Extract region from the event source ARN (parts[3] for all supported ARN formats)
if (eventSourceArn.contains(":sqs:")) {
resolvedRegion = SqsEventSourcePoller.regionFromArn(eventSourceArn);
} else {
// arn:aws:kinesis:region:... or arn:aws:dynamodb:region:...
resolvedRegion = AwsArnUtils.regionOrDefault(eventSourceArn, region);
}
// If the caller supplied a full function ARN, its region must agree
// with the region derived from the event source ARN. Otherwise we'd
// silently bind a different-region function of the same name.
if (fnRef.region() != null && !fnRef.region().equals(resolvedRegion)) {
throw new AwsException("InvalidParameterValueException",
"Function ARN region '" + fnRef.region() + "' does not match event source region '" + resolvedRegion + "'", 400);
}
}
// If the caller supplied a full function ARN, its region must agree
// with the region derived from the event source ARN. Otherwise we'd
// silently bind a different-region function of the same name.
if (fnRef.region() != null && !fnRef.region().equals(resolvedRegion)) {
throw new AwsException("InvalidParameterValueException",
"Function ARN region '" + fnRef.region() + "' does not match event source region '" + resolvedRegion + "'", 400);
}
LambdaFunction fn = getFunction(resolvedRegion, resolvedName);
ResolvedFunctionTarget target = resolveFunctionTarget(resolvedRegion, fnRef);
int batchSize = toInt(request.get("BatchSize"), 10);
boolean enabled = !Boolean.FALSE.equals(request.get("Enabled"));
@@ -1102,15 +1214,17 @@ public class LambdaService implements ResourceProvider {
EventSourceMapping.FilterCriteria filterCriteria = parseFilterCriteria(request, objectMapper);
StartingPositionSpec startingPosition = parseStartingPosition(request, eventSourceArn);
StartingPositionSpec startingPosition = parseStartingPosition(request, eventSourceArn, isSelfManagedKafka);
String queueUrl = eventSourceArn.contains(":sqs:") ? AwsArnUtils.arnToQueueUrl(eventSourceArn, config.effectiveBaseUrl()) : null;
String queueUrl = (eventSourceArn != null && eventSourceArn.contains(":sqs:"))
? AwsArnUtils.arnToQueueUrl(eventSourceArn, config != null ? config.effectiveBaseUrl() : null)
: null;
EventSourceMapping esm = new EventSourceMapping();
esm.setUuid(UUID.randomUUID().toString());
esm.setAccountId(regionResolver.getAccountId());
esm.setFunctionArn(fn.getFunctionArn());
esm.setFunctionName(resolvedName);
esm.setFunctionArn(target.functionArn());
esm.setFunctionName(target.functionName());
esm.setEventSourceArn(eventSourceArn);
esm.setQueueUrl(queueUrl);
esm.setRegion(resolvedRegion);
@@ -1124,6 +1238,9 @@ public class LambdaService implements ResourceProvider {
esm.setFilterCriteria(filterCriteria);
esm.setStartingPosition(startingPosition.position());
esm.setStartingPositionTimestamp(startingPosition.timestampMillis());
esm.setSelfManagedEventSource(selfManagedEventSource);
esm.setTopics(topics);
esm.setSourceAccessConfigurations(sourceAccessConfigurations);
esm.setLastModified(System.currentTimeMillis());
esmStore.save(esm);
@@ -1393,7 +1510,7 @@ public class LambdaService implements ResourceProvider {
* requests that used to succeed. There is no update counterpart because AWS's
* UpdateEventSourceMapping does not accept the field at all - it is replace-only.
*/
private StartingPositionSpec parseStartingPosition(Map<String, Object> request, String eventSourceArn) {
private StartingPositionSpec parseStartingPosition(Map<String, Object> request, String eventSourceArn, boolean isSelfManagedKafka) {
Object raw = request.get("StartingPosition");
if (raw == null) {
return new StartingPositionSpec(null, null);
@@ -1409,12 +1526,13 @@ public class LambdaService implements ResourceProvider {
if (!"AT_TIMESTAMP".equals(position)) {
return new StartingPositionSpec(position, null);
}
// AT_TIMESTAMP is Kinesis-only among the event sources Floci supports - DynamoDB Streams
// shard iterators have no timestamp form at all, so silently accepting it there would
// promise a starting point that can never be honoured.
if (eventSourceArn != null && !eventSourceArn.contains(":kinesis:")) {
// AT_TIMESTAMP is supported for Amazon Kinesis and self-managed Apache Kafka event sources -
// DynamoDB Streams shard iterators have no timestamp form at all, so silently accepting it there
// would promise a starting point that can never be honoured.
boolean isKinesis = eventSourceArn != null && eventSourceArn.contains(":kinesis:");
if (!isKinesis && !isSelfManagedKafka) {
throw new AwsException("InvalidParameterValueException",
"AT_TIMESTAMP is only supported for Amazon Kinesis event sources", 400);
"AT_TIMESTAMP is only supported for Amazon Kinesis and self-managed Apache Kafka event sources", 400);
}
Object rawTimestamp = request.get("StartingPositionTimestamp");
if (rawTimestamp == null) {
@@ -1473,6 +1591,9 @@ public class LambdaService implements ResourceProvider {
}
private void startPollingHelper(EventSourceMapping esm) {
if (esm.getEventSourceArn() == null) {
return;
}
if (esm.getEventSourceArn().contains(":sqs:")) {
poller.startPolling(esm);
} else if (esm.getEventSourceArn().contains(":kinesis:")) {
@@ -1483,6 +1604,9 @@ public class LambdaService implements ResourceProvider {
}
private void stopPollingHelper(EventSourceMapping esm) {
if (esm.getEventSourceArn() == null) {
return;
}
if (esm.getEventSourceArn().contains(":sqs:")) {
poller.stopPolling(esm.getUuid());
} else if (esm.getEventSourceArn().contains(":kinesis:")) {
@@ -1544,6 +1668,60 @@ public class LambdaService implements ResourceProvider {
esm.setFilterCriteria(parseFilterCriteria(request, objectMapper));
}
if (request.containsKey("FunctionName")) {
String fnName = (String) request.get("FunctionName");
if (fnName != null && !fnName.isBlank()) {
LambdaArnUtils.ResolvedFunctionRef fnRef = LambdaArnUtils.resolve(fnName);
if (fnRef.region() != null && !fnRef.region().equals(esm.getRegion())) {
throw new AwsException("InvalidParameterValueException",
"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());
}
}
if (request.containsKey("Topics")) {
Object rawTopics = request.get("Topics");
if (!(rawTopics instanceof List<?> topicList) || topicList.isEmpty()) {
throw new AwsException("InvalidParameterValueException",
"Topics must be a non-empty list of strings", 400);
}
List<String> validatedTopics = new ArrayList<>();
for (Object item : topicList) {
if (!(item instanceof String s) || s.isBlank()) {
throw new AwsException("InvalidParameterValueException",
"Topics elements must be non-blank strings", 400);
}
validatedTopics.add(s);
}
esm.setTopics(validatedTopics);
}
if (request.containsKey("SourceAccessConfigurations")) {
Object rawAccess = request.get("SourceAccessConfigurations");
if (rawAccess != null) {
if (!(rawAccess instanceof List<?> accessList)) {
throw new AwsException("InvalidParameterValueException",
"SourceAccessConfigurations must be a list", 400);
}
List<Map<String, Object>> typedAccess = new ArrayList<>();
for (Object item : accessList) {
if (!(item instanceof Map<?, ?> m)) {
throw new AwsException("InvalidParameterValueException",
"SourceAccessConfiguration entries must be JSON objects", 400);
}
@SuppressWarnings("unchecked")
Map<String, Object> typedMap = (Map<String, Object>) m;
typedAccess.add(typedMap);
}
esm.setSourceAccessConfigurations(typedAccess);
} else {
esm.setSourceAccessConfigurations(null);
}
}
esm.setLastModified(System.currentTimeMillis());
esmStore.save(esm);
@@ -32,6 +32,9 @@ public class EventSourceMapping {
private Boolean bisectBatchOnFunctionError;
private DestinationConfig destinationConfig;
private FilterCriteria filterCriteria;
private Map<String, Object> selfManagedEventSource;
private List<String> topics = new ArrayList<>();
private List<Map<String, Object>> sourceAccessConfigurations = new ArrayList<>();
public EventSourceMapping() {
}
@@ -124,6 +127,30 @@ public class EventSourceMapping {
this.filterCriteria = filterCriteria;
}
public Map<String, Object> getSelfManagedEventSource() {
return selfManagedEventSource;
}
public void setSelfManagedEventSource(Map<String, Object> selfManagedEventSource) {
this.selfManagedEventSource = selfManagedEventSource;
}
public List<String> getTopics() {
return topics;
}
public void setTopics(List<String> topics) {
this.topics = topics != null ? topics : new ArrayList<>();
}
public List<Map<String, Object>> getSourceAccessConfigurations() {
return sourceAccessConfigurations;
}
public void setSourceAccessConfigurations(List<Map<String, Object>> sourceAccessConfigurations) {
this.sourceAccessConfigurations = sourceAccessConfigurations != null ? sourceAccessConfigurations : new ArrayList<>();
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class DestinationConfig {