From 6d95dfe3e1654f0ea617bdb9df7697a746195b3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Thu, 24 Sep 2026 20:24:32 +0900 Subject: [PATCH] fix(lambda): invoke the version or alias that a qualified function reference names (#4231) * fix(lambda): invoke the version or alias an event source mapping names An event source mapping created with a qualified FunctionName, such as my-fn:1 or my-fn:prod, always invoked $LATEST. The SQS, Kinesis and DynamoDB Streams pollers now read the qualifier from the mapping's function ARN. They invoke that version, or the version the alias points to. * fix(sns): invoke the version or alias a Lambda subscription names A Lambda subscription to a qualified ARN, such as my-fn:PROD, always invoked $LATEST because the qualifier was cut off before the invoke. The full endpoint ARN now goes to the Lambda invoke, which resolves the qualifier. * fix(s3): invoke the version or alias a Lambda notification names A bucket notification to a qualified function ARN, such as my-fn:PROD, always invoked $LATEST because the qualifier was cut off before the invoke. The qualifier now stays on the function reference passed to Lambda. * fix(pipes): invoke the version or alias a Lambda target or enrichment names A pipe whose target or enrichment is a qualified function ARN, such as my-fn:PROD, always invoked $LATEST because the qualifier was cut off before the invoke. The qualifier now stays on the function reference passed to Lambda. * fix(stepfunctions): invoke the version or alias a Lambda task names A Lambda task whose Resource or FunctionName is qualified, such as my-fn:1 or my-fn:PROD, always invoked $LATEST because the qualifier was cut off before the function lookup. The task now invokes that version, or the version the alias points to. * test(lambda): run an SQS event source mapping on an alias through a real function The alias points to version 1, which succeeds. $LATEST throws. The message leaves the queue only when the mapping invokes the alias version. * fix(lambda): resolve a qualified function in one place LambdaService, the event source mapping pollers and the Step Functions executor each had their own copy of the qualifier rule. The rule now lives in LambdaTargetResolver, which all of them use. Mappings and Step Functions tasks on an alias with AdditionalVersionWeights now follow the weights, as a direct invoke already did. * test(lambda): drop the Docker SQS alias mapping test It starts a real function and waits on the queue on every CI run with Docker. LambdaServiceTest and the poller unit tests already cover a mapping on an alias through the shared resolver. --- .../DynamoDbStreamsEventSourcePoller.java | 12 +- .../lambda/KinesisEventSourcePoller.java | 8 +- .../floci/services/lambda/LambdaService.java | 116 ++------------ .../services/lambda/LambdaTargetResolver.java | 149 ++++++++++++++++++ .../services/lambda/SqsEventSourcePoller.java | 11 +- .../services/pipes/PipesTargetInvoker.java | 17 +- .../floci/services/s3/S3Service.java | 4 +- .../floci/services/sns/SnsService.java | 27 +--- .../services/stepfunctions/AslExecutor.java | 43 +++-- .../DynamoDbStreamsEventSourcePollerTest.java | 48 +++++- .../lambda/KinesisEventSourcePollerTest.java | 46 +++++- .../LambdaArnInvocationAccountTest.java | 3 + .../lambda/SqsEventSourcePollerTest.java | 51 +++++- .../pipes/PipesTargetInvokerTest.java | 19 ++- .../floci/services/s3/S3ServiceTest.java | 21 +++ .../floci/services/sns/SnsServiceTest.java | 52 +++--- .../AslExecutorLambdaInvokeResultTest.java | 76 ++++++++- 17 files changed, 487 insertions(+), 216 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTargetResolver.java diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java index 0f2afc64a6..c9963764db 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java @@ -57,7 +57,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable { private final Vertx vertx; private final DynamoDbStreamService streamService; private final LambdaExecutorService executorService; - private final LambdaFunctionStore functionStore; + private final LambdaTargetResolver targetResolver; private final EsmStore esmStore; private final ObjectMapper objectMapper; private final PipesFilterMatcher filterMatcher; @@ -80,7 +80,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable { @Inject public DynamoDbStreamsEventSourcePoller(Vertx vertx, DynamoDbStreamService streamService, LambdaExecutorService executorService, - LambdaFunctionStore functionStore, + LambdaTargetResolver targetResolver, EsmStore esmStore, ObjectMapper objectMapper, EmulatorConfig config, @@ -88,13 +88,13 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable { SqsService sqsService, SnsService snsService, S3Service s3Service) { - this(vertx, streamService, executorService, functionStore, esmStore, objectMapper, config, + this(vertx, streamService, executorService, targetResolver, esmStore, objectMapper, config, filterMatcher, sqsService, snsService, s3Service, System::currentTimeMillis); } DynamoDbStreamsEventSourcePoller(Vertx vertx, DynamoDbStreamService streamService, LambdaExecutorService executorService, - LambdaFunctionStore functionStore, + LambdaTargetResolver targetResolver, EsmStore esmStore, ObjectMapper objectMapper, EmulatorConfig config, @@ -106,7 +106,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable { this.vertx = vertx; this.streamService = streamService; this.executorService = executorService; - this.functionStore = functionStore; + this.targetResolver = targetResolver; this.esmStore = esmStore; this.objectMapper = objectMapper; this.pollIntervalMs = config.services().lambda().pollIntervalMs(); @@ -201,7 +201,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable { } pollExecutor.submit(() -> { try { - LambdaFunction fn = functionStore.getForAccount(esm.getAccountId(), esm.getRegion(), esm.getFunctionName()).orElse(null); + LambdaFunction fn = targetResolver.resolveMappingTarget(esm).orElse(null); if (fn == null) { LOG.warnv("DynamoDB Streams ESM {0}: function {1} not found, skipping", esm.getUuid(), esm.getFunctionName()); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java index f9e724eafc..6c753eba80 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java @@ -40,7 +40,7 @@ public class KinesisEventSourcePoller implements Resettable { private final Vertx vertx; private final KinesisService kinesisService; private final LambdaExecutorService executorService; - private final LambdaFunctionStore functionStore; + private final LambdaTargetResolver targetResolver; private final EsmStore esmStore; private final long pollIntervalMs; private final ObjectMapper objectMapper; @@ -56,14 +56,14 @@ public class KinesisEventSourcePoller implements Resettable { @Inject public KinesisEventSourcePoller(Vertx vertx, KinesisService kinesisService, LambdaExecutorService executorService, - LambdaFunctionStore functionStore, + LambdaTargetResolver targetResolver, EsmStore esmStore, EmulatorConfig config, ObjectMapper objectMapper, PipesFilterMatcher filterMatcher) { this.vertx = vertx; this.kinesisService = kinesisService; this.executorService = executorService; - this.functionStore = functionStore; + this.targetResolver = targetResolver; this.esmStore = esmStore; this.pollIntervalMs = config.services().lambda().pollIntervalMs(); this.objectMapper = objectMapper; @@ -115,7 +115,7 @@ public class KinesisEventSourcePoller implements Resettable { if (activePolls.putIfAbsent(esm.getUuid(), Boolean.TRUE) != null) return; pollExecutor.submit(() -> { try { - LambdaFunction fn = functionStore.getForAccount(esm.getAccountId(), esm.getRegion(), esm.getFunctionName()).orElse(null); + LambdaFunction fn = targetResolver.resolveMappingTarget(esm).orElse(null); if (fn == null) return; String streamName = streamNameFromArn(esm.getEventSourceArn()); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 9df08f973f..742f1dbc01 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -102,6 +102,7 @@ public class LambdaService implements ResourceProvider { private final RegionResolver regionResolver; private final EsmStore esmStore; private final LambdaAliasStore aliasStore; + private final LambdaTargetResolver targetResolver; private final S3Service s3Service; private final SqsService sqsService; private final SqsEventSourcePoller poller; @@ -175,6 +176,7 @@ public class LambdaService implements ResourceProvider { this.regionResolver = regionResolver; this.esmStore = storageFactory != null ? new EsmStore(storageFactory) : null; this.aliasStore = storageFactory != null ? new LambdaAliasStore(storageFactory) : null; + this.targetResolver = new LambdaTargetResolver(functionStore, aliasStore); this.s3Service = null; this.sqsService = null; this.poller = null; @@ -198,6 +200,7 @@ public class LambdaService implements ResourceProvider { RegionResolver regionResolver, EsmStore esmStore, LambdaAliasStore aliasStore, + LambdaTargetResolver targetResolver, S3Service s3Service, SqsService sqsService, SqsEventSourcePoller poller, @@ -219,6 +222,7 @@ public class LambdaService implements ResourceProvider { this.regionResolver = regionResolver; this.esmStore = esmStore; this.aliasStore = aliasStore; + this.targetResolver = targetResolver; this.s3Service = s3Service; this.sqsService = sqsService; this.poller = poller; @@ -561,9 +565,9 @@ public class LambdaService implements ResourceProvider { } if (functionName.startsWith("arn:")) { AwsArnUtils.Arn arn = AwsArnUtils.parse(functionName); - return resolveReadTargetForAccount(arn.accountId(), region, ref.name(), effective); + return targetResolver.resolveReadTargetForAccount(arn.accountId(), region, ref.name(), effective); } - return resolveReadTarget(region, ref.name(), effective); + return targetResolver.resolveReadTarget(region, ref.name(), effective); } /** @@ -1035,9 +1039,9 @@ public class LambdaService implements ResourceProvider { LambdaFunction fn; if (functionName.startsWith("arn:")) { AwsArnUtils.Arn arn = AwsArnUtils.parse(functionName); - fn = resolveInvokeTargetForAccount(arn.accountId(), region, name, qualifier); + fn = targetResolver.resolveInvokeTargetForAccount(arn.accountId(), region, name, qualifier); } else { - fn = resolveInvokeTarget(region, name, qualifier); + fn = targetResolver.resolveInvokeTarget(region, name, qualifier); } reportCustomResourceLiveness(payload); InvokeResult result = executorService.invoke(fn, payload, type, @@ -1068,7 +1072,7 @@ public class LambdaService implements ResourceProvider { private InvokeResult invokeArn(String functionArn, byte[] payload, InvocationType type, int chainDepth) { AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn); LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn); - LambdaFunction fn = resolveInvokeTargetForAccount( + LambdaFunction fn = targetResolver.resolveInvokeTargetForAccount( arn.accountId(), arn.region(), ref.name(), ref.qualifier()); InvokeResult result = executorService.invoke(fn, payload, type, chainDepth); result.setExecutedVersion(fn.getVersion()); @@ -1090,108 +1094,6 @@ public class LambdaService implements ResourceProvider { CustomResourceLiveness.tokenIn(payload).ifPresent(customResourceLiveness::touch); } - private LambdaFunction resolveInvokeTarget(String region, String name, String qualifier) { - return resolveTarget(region, name, qualifier, this::pickAliasVersion); - } - - /** - * Resolves a qualifier for a read. Identical to the invoke path except for aliases: - * an alias with {@code AdditionalVersionWeights} shifts traffic, so {@link #pickAliasVersion} - * chooses randomly among the weighted versions, which is right for running the function and - * wrong for describing it. Two reads of one alias must not disagree, so a read follows the - * alias's primary {@code FunctionVersion}, which is what AWS reports. - */ - private LambdaFunction resolveReadTarget(String region, String name, String qualifier) { - return resolveTarget(region, name, qualifier, LambdaAlias::getFunctionVersion); - } - - private LambdaFunction resolveTarget(String region, String name, String qualifier, - java.util.function.Function aliasVersion) { - if (qualifier == null || qualifier.equals("$LATEST")) { - return functionStore.get(region, name) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Function not found: " + name, 404)); - } - if (qualifier.chars().allMatch(Character::isDigit)) { - return functionStore.get(region, name, qualifier) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Function version not found: " + name + ":" + qualifier, 404)); - } - // qualifier is an alias name - LambdaAlias alias = getAlias(region, name, qualifier); - String version = aliasVersion.apply(alias); - if (version == null || version.equals("$LATEST")) { - return functionStore.get(region, name) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Function not found: " + name, 404)); - } - return functionStore.get(region, name, version) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Function version not found: " + name + ":" + version, 404)); - } - - private LambdaFunction resolveInvokeTargetForAccount( - String accountId, String region, String name, String qualifier) { - return resolveTargetForAccount(accountId, region, name, qualifier, this::pickAliasVersion); - } - - /** The read counterpart of {@link #resolveInvokeTargetForAccount}; see {@link #resolveReadTarget}. */ - private LambdaFunction resolveReadTargetForAccount( - String accountId, String region, String name, String qualifier) { - return resolveTargetForAccount(accountId, region, name, qualifier, LambdaAlias::getFunctionVersion); - } - - private LambdaFunction resolveTargetForAccount( - String accountId, String region, String name, String qualifier, - java.util.function.Function aliasVersion) { - if (qualifier == null || qualifier.equals("$LATEST")) { - return functionStore.getForAccount(accountId, region, name) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Function not found: " + name, 404)); - } - if (qualifier.chars().allMatch(Character::isDigit)) { - return functionStore.getForAccount(accountId, region, name, qualifier) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Function version not found: " + name + ":" + qualifier, 404)); - } - LambdaAlias alias = aliasStore != null - ? aliasStore.getForAccount(accountId, region, name, qualifier) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Alias not found: " + qualifier, 404)) - : null; - if (alias == null) { - throw new AwsException("ResourceNotFoundException", "Alias not found: " + qualifier, 404); - } - String version = aliasVersion.apply(alias); - if (version == null || version.equals("$LATEST")) { - return functionStore.getForAccount(accountId, region, name) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Function not found: " + name, 404)); - } - return functionStore.getForAccount(accountId, region, name, version) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Function version not found: " + name + ":" + version, 404)); - } - - private String pickAliasVersion(LambdaAlias alias) { - java.util.Map weights = alias.getRoutingConfig(); - if (weights == null || weights.isEmpty()) { - return alias.getFunctionVersion(); - } - double rand = java.util.concurrent.ThreadLocalRandom.current().nextDouble(); - double additionalTotal = weights.values().stream().mapToDouble(Double::doubleValue).sum(); - double primaryWeight = Math.max(0.0, 1.0 - additionalTotal); - if (rand < primaryWeight) { - return alias.getFunctionVersion(); - } - double cumulative = primaryWeight; - for (java.util.Map.Entry entry : weights.entrySet()) { - cumulative += entry.getValue(); - if (rand < cumulative) { - return entry.getKey(); - } - } - return alias.getFunctionVersion(); - } - // ──────────────────────────── Event Source Mapping (SQS) ──────────────────────────── public EventSourceMapping createEventSourceMapping(String region, Map request) { diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTargetResolver.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTargetResolver.java new file mode 100644 index 0000000000..5863d8bd14 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTargetResolver.java @@ -0,0 +1,149 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; +import io.github.hectorvent.floci.services.lambda.model.LambdaAlias; +import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Function; + +@ApplicationScoped +public class LambdaTargetResolver { + + private final LambdaFunctionStore functionStore; + private final LambdaAliasStore aliasStore; + + @Inject + public LambdaTargetResolver(LambdaFunctionStore functionStore, LambdaAliasStore aliasStore) { + this.functionStore = functionStore; + this.aliasStore = aliasStore; + } + + public LambdaFunction resolveInvokeTarget(String region, String name, String qualifier) { + return resolveTarget(region, name, qualifier, this::pickAliasVersion); + } + + /** + * Resolves a qualifier for a read. Identical to the invoke path except for aliases: + * an alias with {@code AdditionalVersionWeights} shifts traffic, so {@link #pickAliasVersion} + * chooses randomly among the weighted versions, which is right for running the function and + * wrong for describing it. Two reads of one alias must not disagree, so a read follows the + * alias's primary {@code FunctionVersion}, which is what AWS reports. + */ + public LambdaFunction resolveReadTarget(String region, String name, String qualifier) { + return resolveTarget(region, name, qualifier, LambdaAlias::getFunctionVersion); + } + + public LambdaFunction resolveInvokeTargetForAccount( + String accountId, String region, String name, String qualifier) { + return resolveTargetForAccount(accountId, region, name, qualifier, this::pickAliasVersion); + } + + /** The read counterpart of {@link #resolveInvokeTargetForAccount}; see {@link #resolveReadTarget}. */ + public LambdaFunction resolveReadTargetForAccount( + String accountId, String region, String name, String qualifier) { + return resolveTargetForAccount(accountId, region, name, qualifier, LambdaAlias::getFunctionVersion); + } + + /** The function a mapping invokes, or empty when it or its version or alias is gone. */ + public Optional resolveMappingTarget(EventSourceMapping esm) { + String qualifier = esm.getFunctionArn() == null + ? null : LambdaArnUtils.resolve(esm.getFunctionArn()).qualifier(); + try { + return Optional.of(resolveInvokeTargetForAccount( + esm.getAccountId(), esm.getRegion(), esm.getFunctionName(), qualifier)); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + return Optional.empty(); + } + throw e; + } + } + + private LambdaFunction resolveTarget(String region, String name, String qualifier, + Function aliasVersion) { + if (qualifier == null || qualifier.equals("$LATEST")) { + return functionStore.get(region, name) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Function not found: " + name, 404)); + } + if (qualifier.chars().allMatch(Character::isDigit)) { + return functionStore.get(region, name, qualifier) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Function version not found: " + name + ":" + qualifier, 404)); + } + LambdaAlias alias = aliasStore != null + ? aliasStore.get(region, name, qualifier) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Alias not found: " + qualifier, 404)) + : null; + if (alias == null) { + throw new AwsException("ResourceNotFoundException", "Alias not found: " + qualifier, 404); + } + String version = aliasVersion.apply(alias); + if (version == null || version.equals("$LATEST")) { + return functionStore.get(region, name) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Function not found: " + name, 404)); + } + return functionStore.get(region, name, version) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Function version not found: " + name + ":" + version, 404)); + } + + private LambdaFunction resolveTargetForAccount( + String accountId, String region, String name, String qualifier, + Function aliasVersion) { + if (qualifier == null || qualifier.equals("$LATEST")) { + return functionStore.getForAccount(accountId, region, name) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Function not found: " + name, 404)); + } + if (qualifier.chars().allMatch(Character::isDigit)) { + return functionStore.getForAccount(accountId, region, name, qualifier) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Function version not found: " + name + ":" + qualifier, 404)); + } + LambdaAlias alias = aliasStore != null + ? aliasStore.getForAccount(accountId, region, name, qualifier) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Alias not found: " + qualifier, 404)) + : null; + if (alias == null) { + throw new AwsException("ResourceNotFoundException", "Alias not found: " + qualifier, 404); + } + String version = aliasVersion.apply(alias); + if (version == null || version.equals("$LATEST")) { + return functionStore.getForAccount(accountId, region, name) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Function not found: " + name, 404)); + } + return functionStore.getForAccount(accountId, region, name, version) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Function version not found: " + name + ":" + version, 404)); + } + + private String pickAliasVersion(LambdaAlias alias) { + Map weights = alias.getRoutingConfig(); + if (weights == null || weights.isEmpty()) { + return alias.getFunctionVersion(); + } + double rand = ThreadLocalRandom.current().nextDouble(); + double additionalTotal = weights.values().stream().mapToDouble(Double::doubleValue).sum(); + double primaryWeight = Math.max(0.0, 1.0 - additionalTotal); + if (rand < primaryWeight) { + return alias.getFunctionVersion(); + } + double cumulative = primaryWeight; + for (Map.Entry entry : weights.entrySet()) { + cumulative += entry.getValue(); + if (rand < cumulative) { + return entry.getKey(); + } + } + return alias.getFunctionVersion(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java index be1c95a6ed..909416eca0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java @@ -35,7 +35,7 @@ import java.util.stream.Collectors; /** * Polls SQS queues on behalf of Lambda Event Source Mappings. * Uses Vert.x periodic timers so polling is non-blocking. - * Injects LambdaExecutorService + LambdaFunctionStore directly (not LambdaService) + * Injects LambdaExecutorService + LambdaTargetResolver directly (not LambdaService) * to avoid a circular CDI dependency. */ @ApplicationScoped @@ -49,7 +49,7 @@ public class SqsEventSourcePoller implements Resettable { private final Vertx vertx; private final SqsService sqsService; private final LambdaExecutorService executorService; - private final LambdaFunctionStore functionStore; + private final LambdaTargetResolver targetResolver; private final EsmStore esmStore; private final long pollIntervalMs; private final String baseUrl; @@ -72,14 +72,14 @@ public class SqsEventSourcePoller implements Resettable { @Inject public SqsEventSourcePoller(Vertx vertx, SqsService sqsService, LambdaExecutorService executorService, - LambdaFunctionStore functionStore, + LambdaTargetResolver targetResolver, EsmStore esmStore, EmulatorConfig config, ObjectMapper objectMapper, PipesFilterMatcher filterMatcher) { this.vertx = vertx; this.sqsService = sqsService; this.executorService = executorService; - this.functionStore = functionStore; + this.targetResolver = targetResolver; this.esmStore = esmStore; this.pollIntervalMs = config.services().lambda().pollIntervalMs(); this.baseUrl = config.effectiveBaseUrl(); @@ -165,8 +165,7 @@ public class SqsEventSourcePoller implements Resettable { // Look up the function first so we can set an appropriate visibility // timeout: fn.timeout + 30s keeps messages hidden while Lambda runs. // Use account-scoped lookup since this runs outside request scope. - LambdaFunction fn = functionStore.getForAccount(esm.getAccountId(), esm.getRegion(), esm.getFunctionName()) - .orElse(null); + LambdaFunction fn = targetResolver.resolveMappingTarget(esm).orElse(null); if (fn == null) { LOG.warnv("ESM {0}: function {1} not found in region {2}, skipping", esm.getUuid(), esm.getFunctionName(), esm.getRegion()); diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java index 826445a801..ab848a2cc3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java @@ -148,25 +148,16 @@ public class PipesTargetInvoker { } /** - * Extracts a Lambda function name from a bare name, a name with a version/alias qualifier - * (e.g. "name:$LATEST"), or a full/partial function ARN - * ("arn:aws:lambda:region:acct:function:NAME[:qualifier]"). Taking the last ':'-segment is - * wrong for a qualified ARN — it yields the qualifier instead of the name. + * Function reference out of a bare name or a full/partial function ARN + * ("arn:aws:lambda:region:acct:function:NAME[:qualifier]"). The qualifier stays, so Lambda + * invokes the version or alias it names. */ static String lambdaFunctionName(String ref) { if (ref == null) { return null; } - String fn = ref; int fi = ref.indexOf(":function:"); - if (fi >= 0) { - fn = ref.substring(fi + ":function:".length()); - } - int colon = fn.indexOf(':'); - if (colon >= 0) { - fn = fn.substring(0, colon); - } - return fn; + return fi >= 0 ? ref.substring(fi + ":function:".length()) : ref; } private void invokeSqs(String arn, String payload, String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index 050ca261f7..f9aec66fe3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -4411,9 +4411,7 @@ public class S3Service implements Resettable, ResourceProvider { if (functionMarker < 0) { return null; } - String suffix = functionArn.substring(functionMarker + ":function:".length()); - int qualifierSeparator = suffix.indexOf(':'); - return qualifierSeparator >= 0 ? suffix.substring(0, qualifierSeparator) : suffix; + return functionArn.substring(functionMarker + ":function:".length()); } private LambdaService resolveLambdaService() { diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java index 5cdd0bb6f4..e8b00bca65 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java @@ -1727,11 +1727,10 @@ public class SnsService implements Resettable, ResourceProvider { LOG.debugv("Delivered SNS message to SQS: {0} ({1}) raw={2}", sub.getEndpoint(), queueUrl, rawDelivery); } case "lambda" -> { - String fnName = extractFunctionName(sub.getEndpoint()); String region = extractRegionFromArn(sub.getEndpoint()); String eventJson = buildSnsLambdaEvent(topicArn, messageId, protocolMessage, subject, messageAttributes, sub.getSubscriptionArn()); - lambdaService.invoke(region, fnName, eventJson.getBytes(), InvocationType.Event); + lambdaService.invoke(region, sub.getEndpoint(), eventJson.getBytes(), InvocationType.Event); LOG.debugv("Delivered SNS message to Lambda: {0}", sub.getEndpoint()); } case "http", "https" -> { @@ -1884,30 +1883,6 @@ public class SnsService implements Resettable, ResourceProvider { } } - private static final String FUNCTION_MARKER = ":function:"; - - /** - * Function name out of a Lambda ARN, which may carry a qualifier: - * {@code arn:aws:lambda:::function:[:]}. - * - *

Taking the segment after the last colon reads the qualifier as the function name, so a - * subscription to {@code ...:function:order-processor:PROD} invoked a function called - * {@code PROD} and the message went nowhere. Cut after {@code :function:} instead, matching - * what S3 and Step Functions already do for the same ARN. - */ - static String extractFunctionName(String functionArn) { - if (functionArn == null) { - return null; - } - int functionMarker = functionArn.indexOf(FUNCTION_MARKER); - if (functionMarker < 0) { - return functionArn; - } - String suffix = functionArn.substring(functionMarker + FUNCTION_MARKER.length()); - int qualifierSeparator = suffix.indexOf(':'); - return qualifierSeparator >= 0 ? suffix.substring(0, qualifierSeparator) : suffix; - } - private static String extractRegionFromArn(String arn) { return AwsArnUtils.regionOrDefault(arn, null); } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 06d119eb7a..e61f75ef50 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -28,6 +28,7 @@ import io.github.hectorvent.floci.services.scheduler.model.Schedule; import io.github.hectorvent.floci.services.scheduler.model.ScheduleRequest; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; +import io.github.hectorvent.floci.services.lambda.LambdaTargetResolver; 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; @@ -232,7 +233,7 @@ public class AslExecutor { "warning"); private final LambdaExecutorService lambdaExecutor; - private final LambdaFunctionStore functionStore; + private final LambdaTargetResolver targetResolver; private final DynamoDbService dynamoDbService; private final DynamoDbJsonHandler dynamoDbJsonHandler; private final SqsJsonHandler sqsJsonHandler; @@ -265,7 +266,7 @@ public class AslExecutor { }); @Inject - public AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore, + public AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver, DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, CloudFormationQueryHandler cloudFormationHandler, @@ -276,7 +277,7 @@ public class AslExecutor { ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator, Instance sfnService, EmulatorConfig config, Vertx vertx, CustomResourceLiveness customResourceLiveness) { - this(lambdaExecutor, functionStore, dynamoDbService, dynamoDbJsonHandler, + this(lambdaExecutor, targetResolver, dynamoDbService, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService, schedulerController, rdsDataService, @@ -284,7 +285,7 @@ public class AslExecutor { Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null); } - AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore, + AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver, DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, CloudFormationQueryHandler cloudFormationHandler, @@ -298,7 +299,7 @@ public class AslExecutor { Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride) { this.customResourceLiveness = customResourceLiveness; this.lambdaExecutor = lambdaExecutor; - this.functionStore = functionStore; + this.targetResolver = targetResolver; this.dynamoDbService = dynamoDbService; this.dynamoDbJsonHandler = dynamoDbJsonHandler; this.sqsJsonHandler = sqsJsonHandler; @@ -346,7 +347,7 @@ public class AslExecutor { Instance sfnService, EmulatorConfig config, Vertx vertx, CustomResourceLiveness customResourceLiveness, Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride) { - this(lambdaExecutor, functionStore, dynamoDbService, dynamoDbJsonHandler, + this(lambdaExecutor, new LambdaTargetResolver(functionStore, null), dynamoDbService, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService, schedulerController, null, objectMapper, jsonataEvaluator, sfnService, config, @@ -370,7 +371,7 @@ public class AslExecutor { ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator, Instance sfnService, EmulatorConfig config, Vertx vertx, CustomResourceLiveness customResourceLiveness) { - this(lambdaExecutor, functionStore, dynamoDbService, dynamoDbJsonHandler, + this(lambdaExecutor, new LambdaTargetResolver(functionStore, null), dynamoDbService, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, eventBridgeHandler, schedulerService, schedulerController, null, objectMapper, jsonataEvaluator, sfnService, config, @@ -978,7 +979,7 @@ public class AslExecutor { * Extracts the Lambda function name from a reference that may be a bare name, a name with a * version/alias qualifier (e.g. "name:$LATEST"), or a full/partial function ARN * (e.g. "arn:aws:lambda:region:acct:function:name[:qualifier]"). The qualifier is dropped - * because the function store is keyed by name. Taking the last ':'-segment is wrong for a + * here and read by {@link #extractLambdaQualifier}. Taking the last ':'-segment is wrong for a * qualified ARN — it yields the qualifier (e.g. "$LATEST") instead of the function name. */ static String extractLambdaFunctionName(String ref) { @@ -998,6 +999,27 @@ public class AslExecutor { return fn; } + static String extractLambdaQualifier(String ref) { + if (ref == null) { + return null; + } + int fi = ref.indexOf(":function:"); + String fn = fi >= 0 ? ref.substring(fi + ":function:".length()) : ref; + int colon = fn.indexOf(':'); + return colon >= 0 ? fn.substring(colon + 1) : null; + } + + private LambdaFunction resolveLambdaFunction(String region, String name, String qualifier) { + try { + return targetResolver.resolveInvokeTarget(region, name, qualifier); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + return null; + } + throw e; + } + } + /** * Reports that a pending custom resource is still making progress, if this payload belongs to * one. The Step Functions Task path drives a CDK provider-framework waiter's {@code @@ -1042,17 +1064,20 @@ public class AslExecutor { long executionDeadlineNanos, JsonNode rawParameters) throws Exception { // Support Lambda resources: direct ARN or optimized integration String functionName = null; + String functionRef = null; JsonNode lambdaPayload = input; boolean optimizedLambdaInvoke = false; if (resource.contains(":lambda:") && resource.contains(":function:")) { // Direct Lambda ARN: arn:aws:lambda:region:account:function:name[:qualifier] + functionRef = resource; functionName = extractLambdaFunctionName(resource); } else if (resource.equals("arn:aws:states:::lambda:invoke")) { // Optimized Lambda integration — function name and payload come from resolved input optimizedLambdaInvoke = true; String fnRef = input.path("FunctionName").asText(null); if (fnRef != null) { + functionRef = fnRef; functionName = extractLambdaFunctionName(fnRef); } JsonNode payload = input.path("Payload"); @@ -1064,7 +1089,7 @@ public class AslExecutor { if (functionName != null) { // Extract region from the state machine ARN: arn:aws:states:REGION:... String region = extractRegionFromArn(sm.getStateMachineArn()); - LambdaFunction fn = functionStore.get(region, functionName).orElse(null); + LambdaFunction fn = resolveLambdaFunction(region, functionName, extractLambdaQualifier(functionRef)); if (fn == null) { // A missing function is a task failure on AWS, so it must stay reachable for // Retry and Catch instead of surfacing as States.Runtime. diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java index 52d9d61fbd..abdcb1f7ef 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePollerTest.java @@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.iam.IamService; 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.LambdaAlias; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher; import io.github.hectorvent.floci.services.s3.S3Service; @@ -81,6 +82,7 @@ class DynamoDbStreamsEventSourcePollerTest { private DynamoDbStreamService streamService; private LambdaExecutorService executorService; private LambdaFunctionStore functionStore; + private LambdaAliasStore aliasStore; private EsmStore esmStore; private EmulatorConfig config; private PipesFilterMatcher filterMatcher; @@ -106,6 +108,7 @@ class DynamoDbStreamsEventSourcePollerTest { streamService = mock(DynamoDbStreamService.class); executorService = mock(LambdaExecutorService.class); functionStore = mock(LambdaFunctionStore.class); + aliasStore = mock(LambdaAliasStore.class); esmStore = new EsmStore(new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT_ID)); filterMatcher = new PipesFilterMatcher(OBJECT_MAPPER); sqsService = mock(io.github.hectorvent.floci.services.sqs.SqsService.class); @@ -115,7 +118,7 @@ class DynamoDbStreamsEventSourcePollerTest { // A mocked Vertx makes setPeriodic a no-op, so startPolling registers no live timer and // the tests drive pollAndInvoke deterministically. poller = new DynamoDbStreamsEventSourcePoller( - mock(Vertx.class), streamService, executorService, functionStore, + mock(Vertx.class), streamService, executorService, new LambdaTargetResolver(functionStore, aliasStore), esmStore, OBJECT_MAPPER, config, filterMatcher, sqsService, snsService, s3Service, clock::get); } @@ -189,7 +192,7 @@ class DynamoDbStreamsEventSourcePollerTest { private DynamoDbStreamsEventSourcePoller pollerWith(EsmStore store) { return new DynamoDbStreamsEventSourcePoller( - mock(Vertx.class), streamService, executorService, functionStore, + mock(Vertx.class), streamService, executorService, new LambdaTargetResolver(functionStore, aliasStore), store, OBJECT_MAPPER, config, filterMatcher, sqsService, snsService, s3Service, clock::get); } @@ -275,6 +278,47 @@ class DynamoDbStreamsEventSourcePollerTest { private static final String PATTERN = "{\"eventName\":[\"INSERT\"],\"dynamodb\":{\"NewImage\":{\"status\":{\"S\":[\"active\"]}}}}"; + @Test + void versionQualifiedMappingInvokesThatVersion() { + stubTrimHorizon(List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"))); + LambdaFunction version1 = stubVersion("1"); + when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult()); + EventSourceMapping esm = filterEsm(); + esm.setFunctionArn("arn:aws:lambda:us-east-1:" + ACCOUNT_ID + ":function:fn:1"); + + pollerWith(mock(EsmStore.class)).pollAndInvoke(esm); + + verify(executorService, timeout(2000)).invoke(eq(version1), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @Test + void aliasQualifiedMappingInvokesTheAliasVersion() { + stubTrimHorizon(List.of(ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"))); + LambdaFunction version2 = stubVersion("2"); + LambdaAlias alias = new LambdaAlias(); + alias.setName("live"); + alias.setFunctionName("fn"); + alias.setFunctionVersion("2"); + when(aliasStore.getForAccount(ACCOUNT_ID, "us-east-1", "fn", "live")).thenReturn(Optional.of(alias)); + when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult()); + EventSourceMapping esm = filterEsm(); + esm.setFunctionArn("arn:aws:lambda:us-east-1:" + ACCOUNT_ID + ":function:fn:live"); + + pollerWith(mock(EsmStore.class)).pollAndInvoke(esm); + + verify(executorService, timeout(2000)).invoke(eq(version2), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + private LambdaFunction stubVersion(String version) { + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName("fn"); + fn.setVersion(version); + when(functionStore.getForAccount(ACCOUNT_ID, "us-east-1", "fn", version)).thenReturn(Optional.of(fn)); + return fn; + } + @Test void filterDeliversMatchingRecordsAndCheckpointsNewestFetched() { stubTrimHorizon(List.of( diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java index 4480e0b3b2..35cdcebef4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.kinesis.model.KinesisStream; import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.github.hectorvent.floci.services.lambda.model.LambdaAlias; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher; import io.vertx.core.Vertx; @@ -61,6 +62,7 @@ class KinesisEventSourcePollerTest { private KinesisService kinesisService; private LambdaExecutorService executorService; private LambdaFunctionStore functionStore; + private LambdaAliasStore aliasStore; private EsmStore esmStore; @BeforeEach @@ -75,10 +77,11 @@ class KinesisEventSourcePollerTest { kinesisService = mock(KinesisService.class); executorService = mock(LambdaExecutorService.class); functionStore = mock(LambdaFunctionStore.class); + aliasStore = mock(LambdaAliasStore.class); esmStore = mock(EsmStore.class); poller = new KinesisEventSourcePoller(mock(Vertx.class), kinesisService, executorService, - functionStore, esmStore, config, MAPPER, new PipesFilterMatcher(MAPPER)); + new LambdaTargetResolver(functionStore, aliasStore), esmStore, config, MAPPER, new PipesFilterMatcher(MAPPER)); } private EventSourceMapping esm(String... patterns) { @@ -160,6 +163,47 @@ class KinesisEventSourcePollerTest { } } + @Test + void versionQualifiedMappingInvokesThatVersion() { + stubFunction(); + LambdaFunction version1 = stubVersion("1"); + stubStreamWith(List.of(record("s1", "p1", "{}"))); + when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse))).thenReturn(new InvokeResult()); + EventSourceMapping esm = esm(); + esm.setFunctionArn("arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:fn:1"); + + poller.pollAndInvoke(esm); + + verify(executorService, timeout(2000)).invoke(eq(version1), any(), eq(InvocationType.RequestResponse)); + } + + @Test + void aliasQualifiedMappingInvokesTheAliasVersion() { + stubFunction(); + LambdaFunction version2 = stubVersion("2"); + LambdaAlias alias = new LambdaAlias(); + alias.setName("live"); + alias.setFunctionName("fn"); + alias.setFunctionVersion("2"); + when(aliasStore.getForAccount(ACCOUNT, REGION, "fn", "live")).thenReturn(Optional.of(alias)); + stubStreamWith(List.of(record("s1", "p1", "{}"))); + when(executorService.invoke(any(), any(), eq(InvocationType.RequestResponse))).thenReturn(new InvokeResult()); + EventSourceMapping esm = esm(); + esm.setFunctionArn("arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:fn:live"); + + poller.pollAndInvoke(esm); + + verify(executorService, timeout(2000)).invoke(eq(version2), any(), eq(InvocationType.RequestResponse)); + } + + private LambdaFunction stubVersion(String version) { + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName("fn"); + fn.setVersion(version); + when(functionStore.getForAccount(ACCOUNT, REGION, "fn", version)).thenReturn(Optional.of(fn)); + return fn; + } + @Test void noFilterInvokesAllRecordsAndCheckpointsNewest() { stubFunction(); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java index 2c5924ff85..0ae08b667a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java @@ -61,6 +61,7 @@ class LambdaArnInvocationAccountTest { new RegionResolver(region, defaultAccount), null, null, + new LambdaTargetResolver(store, null), null, null, null, @@ -123,6 +124,7 @@ class LambdaArnInvocationAccountTest { new RegionResolver(region, defaultAccount), null, aliasStore, + new LambdaTargetResolver(functionStore, aliasStore), null, null, null, @@ -263,6 +265,7 @@ class LambdaArnInvocationAccountTest { new RegionResolver(region, defaultAccount), null, aliasStore, + new LambdaTargetResolver(functionStore, aliasStore), null, null, null, diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java index bfbe578d9d..b6a79423db 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePollerTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; 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.LambdaAlias; 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; @@ -41,6 +42,7 @@ class SqsEventSourcePollerTest { private SqsService sqsService; private LambdaExecutorService executorService; private LambdaFunctionStore functionStore; + private LambdaAliasStore aliasStore; @BeforeEach void setUp() { @@ -55,12 +57,13 @@ class SqsEventSourcePollerTest { sqsService = mock(SqsService.class); executorService = mock(LambdaExecutorService.class); functionStore = mock(LambdaFunctionStore.class); + aliasStore = mock(LambdaAliasStore.class); poller = new SqsEventSourcePoller( mock(Vertx.class), sqsService, executorService, - functionStore, + new LambdaTargetResolver(functionStore, aliasStore), mock(EsmStore.class), config, OBJECT_MAPPER, @@ -325,6 +328,52 @@ class SqsEventSourcePollerTest { verify(sqsService, never()).deleteMessage(any(), any(), any()); } + @Test + void versionQualifiedMappingInvokesThatVersion() { + EventSourceMapping esm = esm(); + esm.setFunctionArn("arn:aws:lambda:us-east-1:000000000000:function:throwfn:1"); + stubThrowFn(); + LambdaFunction version1 = new LambdaFunction(); + version1.setFunctionName("throwfn"); + version1.setVersion("1"); + version1.setTimeout(10); + when(functionStore.getForAccount("000000000000", "us-east-1", "throwfn", "1")) + .thenReturn(Optional.of(version1)); + stubReceive(esm, List.of(message("m1"))); + when(executorService.invoke(any(LambdaFunction.class), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult()); + + poller.pollAndInvoke(esm); + + verify(executorService, timeout(2000)).invoke(eq(version1), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @Test + void aliasQualifiedMappingInvokesTheAliasVersion() { + EventSourceMapping esm = esm(); + esm.setFunctionArn("arn:aws:lambda:us-east-1:000000000000:function:throwfn:live"); + stubThrowFn(); + LambdaAlias alias = new LambdaAlias(); + alias.setName("live"); + alias.setFunctionName("throwfn"); + alias.setFunctionVersion("2"); + when(aliasStore.getForAccount("000000000000", "us-east-1", "throwfn", "live")) + .thenReturn(Optional.of(alias)); + LambdaFunction version2 = new LambdaFunction(); + version2.setFunctionName("throwfn"); + version2.setVersion("2"); + version2.setTimeout(10); + when(functionStore.getForAccount("000000000000", "us-east-1", "throwfn", "2")) + .thenReturn(Optional.of(version2)); + stubReceive(esm, List.of(message("m1"))); + when(executorService.invoke(any(LambdaFunction.class), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult()); + + poller.pollAndInvoke(esm); + + verify(executorService, timeout(2000)).invoke(eq(version2), any(byte[].class), eq(InvocationType.RequestResponse)); + } + @Test void failedInvocationFallsBackToDefaultVisibilityWhenQueueHasNone() { EventSourceMapping esm = esm(); diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java index 66ee3a4964..827050a554 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java @@ -102,6 +102,17 @@ class PipesTargetInvokerTest { verify(sqsService).sendMessage(anyString(), eq(payload), eq(0), eq(region)); } + @Test + void invoke_keepsTheQualifierOfTheTargetFunctionArn() { + Pipe pipe = createPipe("arn:aws:lambda:us-east-1:000000000000:function:my-fn:PROD", null); + when(lambdaService.invoke(anyString(), anyString(), any(byte[].class), any(InvocationType.class))) + .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(200, null, "{}".getBytes(), null, "req")); + + invoker.invoke(pipe, "{}", "us-east-1"); + + verify(lambdaService).invoke(eq("us-east-1"), eq("my-fn:PROD"), any(byte[].class), eq(InvocationType.RequestResponse)); + } + @Test void invoke_throwsOnDeliveryFailure() { Pipe pipe = createPipe("arn:aws:lambda:us-east-1:000000000000:function:my-fn", null); @@ -275,15 +286,15 @@ class PipesTargetInvokerTest { } @Test - void applyEnrichment_qualifiedArnResolvesFunctionName() { + void applyEnrichment_keepsTheQualifierOfTheFunctionArn() { String region = "us-east-1"; - Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn:$LATEST"); - when(lambdaService.invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse))) + Pipe pipe = enrichmentPipe(region, "arn:aws:lambda:" + region + ":000000000000:function:enrich-fn:PROD"); + when(lambdaService.invoke(eq(region), eq("enrich-fn:PROD"), any(byte[].class), eq(InvocationType.RequestResponse))) .thenReturn(new io.github.hectorvent.floci.services.lambda.model.InvokeResult(200, null, "{}".getBytes(), null, "req")); invoker.applyEnrichment(pipe, "[]", region); - verify(lambdaService).invoke(eq(region), eq("enrich-fn"), any(byte[].class), eq(InvocationType.RequestResponse)); + verify(lambdaService).invoke(eq(region), eq("enrich-fn:PROD"), any(byte[].class), eq(InvocationType.RequestResponse)); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java index 45195af6d1..32cffc6765 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java @@ -618,6 +618,27 @@ class S3ServiceTest { assertNull(lambdaInvoker.functionName); } + @Test + void putObjectKeepsTheQualifierOfTheNotificationFunctionArn() { + RecordingLambdaInvoker lambdaInvoker = new RecordingLambdaInvoker(); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + + S3Service service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), tempDir.resolve("notif-s3-alias"), + false, lambdaInvoker, regionResolver); + service.createBucket("test-bucket", "ap-northeast-1"); + NotificationConfiguration config = new NotificationConfiguration(); + config.getLambdaFunctionConfigurations().add(new LambdaNotification( + "lambda-notif", + "arn:aws:lambda:ap-northeast-1:000000000000:function:s3-notif-test:PROD", + List.of("s3:ObjectCreated:Put"), + List.of())); + service.putBucketNotificationConfiguration("test-bucket", config); + + service.putObject("test-bucket", "a.json", "{}".getBytes(StandardCharsets.UTF_8), "application/json", null); + + assertEquals("s3-notif-test:PROD", lambdaInvoker.functionName); + } + private static NotificationConfiguration lambdaNotificationConfig(String prefix, String suffix) { NotificationConfiguration config = new NotificationConfiguration(); config.getLambdaFunctionConfigurations().add(new LambdaNotification( diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java index 97641d2723..b647c1e66e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java @@ -7,6 +7,8 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.firehose.FirehoseService; import io.github.hectorvent.floci.services.firehose.model.Record; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.sns.model.Subscription; import io.github.hectorvent.floci.services.sns.model.Topic; import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue; @@ -614,37 +616,6 @@ class SnsServiceTest { "arn:aws:sns:us-east-1:000000000000:ghost-topic", REGION)); } - - /** - * A Lambda subscription endpoint may be a qualified ARN. Taking the segment after the last - * colon read the alias as the function name, so a subscription to - * {@code ...:function:order-processor:PROD} invoked a function called {@code PROD}: the - * message was accepted, reported as published, and delivered nowhere. - */ - @Test - void extractFunctionNameIgnoresTheQualifier() { - String base = "arn:aws:lambda:us-east-1:000000000000:function:order-processor"; - - assertEquals("order-processor", SnsService.extractFunctionName(base)); - assertEquals("order-processor", SnsService.extractFunctionName(base + ":PROD")); - assertEquals("order-processor", SnsService.extractFunctionName(base + ":42")); - assertEquals("order-processor", SnsService.extractFunctionName(base + ":$LATEST")); - } - - /** Other partitions carry the same resource grammar. */ - @Test - void extractFunctionNameWorksInAnyPartition() { - assertEquals("order-processor", SnsService.extractFunctionName( - "arn:aws-us-gov:lambda:us-gov-west-1:000000000000:function:order-processor:PROD")); - } - - /** A bare function name is a legal endpoint too and passes through unchanged. */ - @Test - void extractFunctionNameLeavesABareNameAlone() { - assertEquals("order-processor", SnsService.extractFunctionName("order-processor")); - assertNull(SnsService.extractFunctionName(null)); - } - private static Map attr(String name, String value, String dataType) { return Map.of(name, new MessageAttributeValue(value, dataType)); } @@ -844,6 +815,25 @@ class SnsServiceTest { assertFalse(snsService.matchesFilterPolicy(nested, body("{\"detail\":{\"b\":\"3\"}}"), null)); } + @Test + void publish_invokesTheQualifiedLambdaSubscriptionEndpoint() { + LambdaService lambdaService = mock(LambdaService.class); + SnsService service = new SnsService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new RegionResolver(REGION, ACCOUNT), + null, + lambdaService + ); + Topic topic = service.createTopic("lambda-topic", null, null, REGION); + String aliasArn = "arn:aws:lambda:us-east-1:000000000000:function:order-processor:PROD"; + service.subscribe(topic.getTopicArn(), "lambda", aliasArn, REGION, Map.of()); + + service.publish(topic.getTopicArn(), null, "hello", null, REGION); + + verify(lambdaService).invoke(eq(REGION), eq(aliasArn), any(byte[].class), eq(InvocationType.Event)); + } + @Test void publish_deliversToFirehoseSubscription_withJsonEnvelope() throws Exception { FirehoseService firehoseService = mock(FirehoseService.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java index 357b15bac8..8bbb67082c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java @@ -5,10 +5,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.lambda.LambdaAliasStore; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; +import io.github.hectorvent.floci.services.lambda.LambdaTargetResolver; 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.LambdaAlias; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; import io.github.hectorvent.floci.services.s3.S3Service; import io.github.hectorvent.floci.services.sns.SnsJsonHandler; @@ -54,14 +57,18 @@ class AslExecutorLambdaInvokeResultTest { private final ObjectMapper objectMapper = new ObjectMapper(); private AslExecutor executor; + private LambdaExecutorService lambdaExecutor; + private LambdaFunctionStore functionStore; + private LambdaAliasStore aliasStore; @Inject Vertx vertx; @BeforeEach void setUp() throws Exception { - LambdaExecutorService lambdaExecutor = mock(LambdaExecutorService.class); - LambdaFunctionStore functionStore = mock(LambdaFunctionStore.class); + lambdaExecutor = mock(LambdaExecutorService.class); + functionStore = mock(LambdaFunctionStore.class); + aliasStore = mock(LambdaAliasStore.class); LambdaFunction function = new LambdaFunction(); function.setFunctionName(FUNCTION_NAME); function.setFunctionArn(FUNCTION_ARN); @@ -78,7 +85,7 @@ class AslExecutorLambdaInvokeResultTest { executor = new AslExecutor( lambdaExecutor, - functionStore, + new LambdaTargetResolver(functionStore, aliasStore), mock(DynamoDbService.class), mock(DynamoDbJsonHandler.class), mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), @@ -90,6 +97,7 @@ class AslExecutorLambdaInvokeResultTest { mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class), mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class), mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class), + null, objectMapper, new JsonataEvaluator(objectMapper), mock(Instance.class), mock(EmulatorConfig.class), vertx, null); @@ -245,6 +253,68 @@ class AslExecutorLambdaInvokeResultTest { assertEquals(1, output.path("echo").path("in").asInt()); } + @Test + void directVersionQualifiedArnInvokesThatVersion() throws Exception { + stubVersion("1", "V1"); + + Execution execution = run(""" + { + "StartAt": "Call", + "States": { + "Call": { + "Type": "Task", + "Resource": "%s:1", + "End": true + } + } + } + """.formatted(FUNCTION_ARN)); + + assertEquals("SUCCEEDED", execution.getStatus()); + assertEquals("V1", objectMapper.readTree(execution.getOutput()).path("marker").asText()); + } + + @Test + void optimizedInvokeWithAliasInvokesTheAliasVersion() throws Exception { + stubVersion("2", "V2"); + LambdaAlias alias = new LambdaAlias(); + alias.setName("live"); + alias.setFunctionName(FUNCTION_NAME); + alias.setFunctionVersion("2"); + when(aliasStore.get(REGION, FUNCTION_NAME, "live")).thenReturn(Optional.of(alias)); + + Execution execution = run(""" + { + "StartAt": "Call", + "States": { + "Call": { + "Type": "Task", + "Resource": "arn:aws:states:::lambda:invoke", + "Parameters": {"FunctionName": "%s:live", "Payload": {}}, + "End": true + } + } + } + """.formatted(FUNCTION_ARN)); + + assertEquals("SUCCEEDED", execution.getStatus()); + JsonNode output = objectMapper.readTree(execution.getOutput()); + assertEquals("V2", output.path("Payload").path("marker").asText()); + assertEquals("2", output.path("ExecutedVersion").asText()); + } + + private void stubVersion(String version, String marker) throws Exception { + LambdaFunction function = new LambdaFunction(); + function.setFunctionName(FUNCTION_NAME); + function.setFunctionArn(FUNCTION_ARN + ":" + version); + function.setVersion(version); + when(functionStore.get(REGION, FUNCTION_NAME, version)).thenReturn(Optional.of(function)); + when(lambdaExecutor.invoke(eq(function), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult(200, null, + objectMapper.writeValueAsBytes(objectMapper.createObjectNode().put("marker", marker)), + null, "version-request")); + } + private Execution run(String definition) { StateMachine stateMachine = new StateMachine(); stateMachine.setName("lambda-invoke-result");