Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambda): bound a destination cycle that re-enters through SNS or EventBridge (#4279)
Matheus Oliveirafc81cdedd932
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java b/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.javaindex 8b6a2e87dd..64b9048b16 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouter.java@@ -70,13 +70,6 @@ public class AsyncInvokeDestinationRouter {private static final String DEFAULT_VERSION = "$LATEST";/** Floci does not retry a failed asynchronous invocation, so every record is the first attempt. */private static final int APPROXIMATE_INVOKE_COUNT = 1;- /**- * How many Lambda destination hops a single originating invocation may take. A function whose- * destination leads back into itself would otherwise invoke forever, which on a laptop is a- * worse failure than on AWS, where recursive loop detection halts the chain. The bound matches- * the depth AWS stops at.- */- private static final int MAX_DESTINATION_CHAIN_DEPTH = 16;private final Instance<LambdaService> lambdaService;private final Instance<EventBridgeService> eventBridgeService;@@ -109,8 +102,10 @@ public class AsyncInvokeDestinationRouter {* finished, so a destination that rejects the record has nowhere left to be reported and is* logged instead.*- * @param chainDepth how many Lambda destination deliveries led to this invocation, which- * bounds a chain of them that leads back into itself+ * @param chainDepth how many destination deliveries led to this invocation. The delivery runs+ * one hop further along, so a chain that leads back into Lambda, through a+ * function ARN or through SNS or EventBridge, is stopped at the bound in+ * {@link LambdaInvocationChain} instead of running forever*/public void route(LambdaFunction fn, byte[] requestPayload, InvokeResult result, int chainDepth) {// A runtime that never started, timed out, or crashed is reported as a function error by@@ -200,51 +195,43 @@ public class AsyncInvokeDestinationRouter {// The invocation ran on a pool thread that carries no request context, so the account the// destination lives in has to be re-established before any account-aware store is read.- boolean delivered = switch (AwsArnUtils.isArn(arn) ? AwsArnUtils.parse(arn).service() : "") {- case "events" -> {- RequestScopes.runAs(accountId, () ->- putOnEventBus(arn, body, region, failed, fn.getFunctionArn()));- yield true;- }- case "sqs" -> {- RequestScopes.runAs(accountId, () ->- sqsService.get().sendMessage(AwsArnUtils.arnToQueueUrl(arn, baseUrl), body, 0, region));- yield true;- }- case "sns" -> {- RequestScopes.runAs(accountId, () ->- snsService.get().publish(arn, null, body, "Lambda", region));- yield true;- }- case "lambda" -> invokeDestinationFunction(arn, fn, body, accountId, failed, chainDepth);- default -> {- LOG.warnv("Unsupported Lambda {0} destination, dropping the record: {1}", side(failed), arn);- yield false;- }- };+ // The whole delivery runs one hop further along the chain, which is what bounds a+ // destination that comes back into Lambda through SNS or EventBridge rather than naming a+ // function outright: those deliver to their Lambda targets on this very thread.+ boolean delivered = LambdaInvocationChain.callAtDepth(chainDepth + 1, () ->+ switch (AwsArnUtils.isArn(arn) ? AwsArnUtils.parse(arn).service() : "") {+ case "events" -> {+ RequestScopes.runAs(accountId, () ->+ putOnEventBus(arn, body, region, failed, fn.getFunctionArn()));+ yield true;+ }+ case "sqs" -> {+ RequestScopes.runAs(accountId, () ->+ sqsService.get().sendMessage(AwsArnUtils.arnToQueueUrl(arn, baseUrl), body, 0, region));+ yield true;+ }+ case "sns" -> {+ RequestScopes.runAs(accountId, () ->+ snsService.get().publish(arn, null, body, "Lambda", region));+ yield true;+ }+ case "lambda" -> {+ RequestScopes.runAs(accountId, () ->+ lambdaService.get().invokeArnFromDestination(+ arn, body.getBytes(StandardCharsets.UTF_8), chainDepth + 1));+ yield true;+ }+ default -> {+ LOG.warnv("Unsupported Lambda {0} destination, dropping the record: {1}",+ side(failed), arn);+ yield false;+ }+ });if (delivered) {LOG.debugv("Lambda {0} destination delivered to {1}", side(failed), arn);}}- /**- * Invokes a Lambda destination unless the chain that reached it is already at its bound, and- * answers whether it did.- */- private boolean invokeDestinationFunction(String arn, LambdaFunction fn, String body,- String accountId, boolean failed, int chainDepth) {- if (chainDepth >= MAX_DESTINATION_CHAIN_DEPTH) {- LOG.warnv("Lambda {0} destination chain from {1} reached {2} hops at {3}; dropping the "- + "record rather than continuing a chain that leads back into itself",- side(failed), fn.getFunctionArn(), MAX_DESTINATION_CHAIN_DEPTH, arn);- return false;- }- RequestScopes.runAs(accountId, () ->- lambdaService.get().invokeArnFromDestination(- arn, body.getBytes(StandardCharsets.UTF_8), chainDepth + 1));- return true;- }-/*** Puts the record on the bus as the event {@code detail}. The source and detail type are the* fixed ones AWS uses, which is what a rule on a Lambda destination matches against.diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.javaindex b52463f236..7d1716cf73 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorService.java@@ -70,9 +70,14 @@ public class LambdaExecutorService {}/**- * Invokes {@code fn}, carrying the number of Lambda destination deliveries that led here.- * A direct invoke starts at zero; each delivery to a Lambda destination adds one, which is- * what bounds a destination chain that points back at a function already in it.+ * Invokes {@code fn}, carrying the number of invocations that the same originating event has+ * already caused. A direct invoke starts at zero; each destination delivery adds one, whether+ * it names the next function outright or reaches it back through SNS or EventBridge.+ *+ * <p>An asynchronous invocation past the bound is dropped rather than run, which is how AWS+ * breaks a recursive loop: the event goes no further and the caller, which was answered with+ * 202 long before, sees nothing. Only the asynchronous path is guarded because it is the only+ * one a destination chain can re-enter through.*/InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth) {String requestId = UUID.randomUUID().toString();@@ -81,6 +86,13 @@ public class LambdaExecutorService {return new InvokeResult(204, null, new byte[0], null, requestId);}+ if (type == InvocationType.Event && LambdaInvocationChain.exhausted(chainDepth)) {+ LOG.warnv("Dropping the asynchronous invocation of {0}: the same event already caused "+ + "{1} invocations, so something in the chain is feeding itself",+ fn.getFunctionArn(), chainDepth);+ return new InvokeResult(202, null, new byte[0], null, requestId);+ }+LambdaConcurrencyLimiter.Permit permit = concurrencyLimiter.acquire(fn);if (type == InvocationType.Event) {diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaInvocationChain.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaInvocationChain.javanew file mode 100644index 0000000000..c46b5bb00f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaInvocationChain.java@@ -0,0 +1,66 @@+package io.github.hectorvent.floci.services.lambda;++import java.util.function.Supplier;++/**+ * Where the current thread sits in a Lambda chain of requests, the sequence of invocations that+ * one originating event causes.+ *+ * <p>AWS tracks this out of band, in the X-Ray tracing header it annotates every event with, and+ * stops the next invocation once a function has been invoked roughly {@value #MAX_DEPTH} times in+ * the same chain. Floci has no tracing header to hang the count on, and a member added to the+ * event would change what the function receives, which has to stay exactly what AWS sends. The+ * calling thread carries it instead: SNS delivers to a Lambda subscriber, and EventBridge to a+ * Lambda target, synchronously on the thread that published, so a destination record looping back+ * into Lambda through either of them arrives on the thread that delivered it.+ * {@code EventBridgeInvoker} bounds bus-to-bus forwarding the same way.+ *+ * <p>The bound therefore holds even when the async pool is saturated and its caller-runs fallback+ * puts the next invocation on the publishing thread's own stack, which is the case that would+ * otherwise recurse until the stack ran out.+ *+ * <p>A cycle that leaves the thread is not counted and is not bounded here. An SQS event source+ * mapping is the one that matters: its poller runs on a thread of its own, and AWS closes that gap+ * with the same tracing header, carried as an SQS system attribute.+ */+final class LambdaInvocationChain {++ /**+ * How many invocations one originating event may cause before the next one is dropped. AWS+ * stops a chain at approximately this many.+ */+ static final int MAX_DEPTH = 16;++ private static final ThreadLocal<Integer> DEPTH = ThreadLocal.withInitial(() -> 0);++ private LambdaInvocationChain() {}++ /** How many invocations already led to the work running on this thread. */+ static int currentDepth() {+ return DEPTH.get();+ }++ /** Whether an invocation at {@code depth} is the one past the bound, and so has to be dropped. */+ static boolean exhausted(int depth) {+ return depth >= MAX_DEPTH;+ }++ /**+ * Runs {@code body} at the given position in the chain, so everything it reaches synchronously,+ * a re-entrant Lambda invocation included, counts from there rather than starting over.+ */+ static <T> T callAtDepth(int depth, Supplier<T> body) {+ int previous = DEPTH.get();+ DEPTH.set(depth);+ try {+ return body.get();+ } finally {+ // Pool and request threads are reused, so the counter cannot be left behind on one.+ if (previous == 0) {+ DEPTH.remove();+ } else {+ DEPTH.set(previous);+ }+ }+ }+}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.javaindex bc73712385..9df08f973f 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@@ -1040,19 +1040,26 @@ public class LambdaService implements ResourceProvider {fn = resolveInvokeTarget(region, name, qualifier);}reportCustomResourceLiveness(payload);- InvokeResult result = executorService.invoke(fn, payload, type);+ InvokeResult result = executorService.invoke(fn, payload, type,+ LambdaInvocationChain.currentDepth());result.setExecutedVersion(fn.getVersion());return result;}- /** Invokes a Lambda target ARN using the account encoded in that ARN. */+ /**+ * Invokes a Lambda target ARN using the account encoded in that ARN.+ *+ * <p>The chain position comes from the calling thread, so a delivery that arrives here through+ * an EventBridge target or an SNS subscription keeps counting from where it was rather than+ * starting a fresh chain.+ */public InvokeResult invokeArn(String functionArn, byte[] payload, InvocationType type) {- return invokeArn(functionArn, payload, type, 0);+ return invokeArn(functionArn, payload, type, LambdaInvocationChain.currentDepth());}/**- * Invokes a Lambda destination, carrying the number of destination deliveries that reached it- * so {@link AsyncInvokeDestinationRouter} can bound a chain that leads back into itself.+ * Invokes a Lambda destination at the position in the chain the delivery reached, so that a+ * chain leading back into a function already in it is stopped at the bound.*/InvokeResult invokeArnFromDestination(String functionArn, byte[] payload, int chainDepth) {return invokeArn(functionArn, payload, InvocationType.Event, chainDepth);diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.javaindex 280a01b291..2e63e8c085 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/AsyncInvokeDestinationRouterTest.java@@ -23,16 +23,17 @@ import org.mockito.quality.Strictness;import java.util.List;import java.util.Map;import java.util.Optional;+import java.util.concurrent.atomic.AtomicInteger;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;@@ -190,23 +191,73 @@ class AsyncInvokeDestinationRouterTest {}@Test- void lambdaDestinationAtTheChainLimit_stopsRatherThanInvokingAgain() {- configure(COLLECTOR_ARN, null);+ void nonLambdaDestinationAtTheChainLimit_isStillDelivered() {+ // The bound exists to stop a chain re-entering Lambda; a queue is the end of one, and AWS+ // lets the message through and stops the invocation it would cause instead.+ configure(QUEUE_ARN, null);router.route(fn, request(), success("{\"rate\":3.5}"), 16);- verify(lambdaService, never()).invokeArnFromDestination(anyString(), any(), anyInt());+ verify(sqsService).sendMessage(eq("http://localhost:4566/000000000000/quotes-queue"),+ anyString(), eq(0), eq("us-east-1"));}@Test- void nonLambdaDestinationAtTheChainLimit_isStillDelivered() {- // The bound exists to stop a chain re-entering Lambda; a queue is the end of one.- configure(QUEUE_ARN, null);+ void snsDestination_publishesOneHopFurtherAlongTheChain() {+ // SnsService invokes a Lambda subscriber on the publishing thread, so the depth it reads+ // there is what stops a topic that fans straight back into the function.+ configure(TOPIC_ARN, null);+ AtomicInteger depthWhilePublishing = new AtomicInteger(-1);+ doAnswer(invocation -> {+ depthWhilePublishing.set(LambdaInvocationChain.currentDepth());+ return null;+ }).when(snsService).publish(anyString(), any(), anyString(), anyString(), anyString());- router.route(fn, request(), success("{\"rate\":3.5}"), 16);+ router.route(fn, request(), success("{\"rate\":3.5}"), 3);- verify(sqsService).sendMessage(eq("http://localhost:4566/000000000000/quotes-queue"),- anyString(), eq(0), eq("us-east-1"));+ assertEquals(4, depthWhilePublishing.get());+ assertEquals(0, LambdaInvocationChain.currentDepth(), "the thread must be left as it was found");+ }++ @Test+ void eventBridgeDestination_putsTheEventOneHopFurtherAlongTheChain() {+ configure(BUS_ARN, null);+ AtomicInteger depthWhilePutting = new AtomicInteger(-1);+ when(eventBridgeService.putEvents(any(), any(), any())).thenAnswer(invocation -> {+ depthWhilePutting.set(LambdaInvocationChain.currentDepth());+ return new EventBridgeService.PutEventsResult(0, List.of());+ });++ router.route(fn, request(), success("{\"rate\":3.5}"), 3);++ assertEquals(4, depthWhilePutting.get());+ assertEquals(0, LambdaInvocationChain.currentDepth(), "the thread must be left as it was found");+ }++ @Test+ void snsDestinationFanningBackIntoTheFunction_stopsAtTheChainBound() {+ // The reported cycle: the function's OnSuccess is a topic the function itself subscribes+ // to. The stand-in below re-enters where SnsService would, on the publishing thread, and+ // refuses the invocation on the same rule LambdaExecutorService applies. Before the depth+ // travelled through SNS every hop started a fresh chain and this never came back.+ configure(TOPIC_ARN, null);+ AtomicInteger invocations = new AtomicInteger();+ doAnswer(invocation -> {+ int depth = LambdaInvocationChain.currentDepth();+ if (LambdaInvocationChain.exhausted(depth)) {+ return null;+ }+ invocations.incrementAndGet();+ router.route(fn, request(), success("{\"rate\":3.5}"), depth);+ return null;+ }).when(snsService).publish(anyString(), any(), anyString(), anyString(), anyString());++ router.route(fn, request(), success("{\"rate\":3.5}"), 0);++ assertEquals(LambdaInvocationChain.MAX_DEPTH - 1, invocations.get(),+ "the originating invocation plus these re-entrant ones is the bound");+ verify(snsService, times(LambdaInvocationChain.MAX_DEPTH))+ .publish(anyString(), any(), anyString(), anyString(), anyString());}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.javaindex dc36855f24..e9f09f2ca0 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutorServiceTest.java@@ -30,6 +30,7 @@ import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;+import static org.mockito.Mockito.timeout;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -55,6 +56,40 @@ class LambdaExecutorServiceTest {when(concurrencyLimiter.acquire(any())).thenReturn(() -> {});}+ @Test+ void asyncInvocationPastTheChainBound_isDroppedWithoutRunningTheFunction() {+ // AWS stops the next invocation in a chain of requests once the same originating event has+ // caused about this many, which is what keeps a destination cycle from running forever.+ InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.Event,+ LambdaInvocationChain.MAX_DEPTH);++ assertEquals(202, result.getStatusCode());+ assertNotNull(result.getRequestId());+ verify(concurrencyLimiter, never()).acquire(any());+ verify(warmPool, never()).acquire(any());+ }++ @Test+ void asyncInvocationShortOfTheChainBound_stillRuns() {+ executor.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH - 1);++ verify(warmPool, timeout(5000)).acquire(fn);+ }++ @Test+ void syncInvocationPastTheChainBound_isNotAffected() {+ // Only the asynchronous path can be re-entered by a destination chain, and refusing a+ // RequestResponse invoke would need an error shape AWS does not define here.+ RuntimeApiServer rtas = mock(RuntimeApiServer.class);+ ContainerHandle handle = new ContainerHandle("cid-bound", "test-fn", rtas, ContainerState.WARM);+ when(warmPool.acquire(any())).thenReturn(handle);+ when(rtas.enqueue(any())).thenReturn(new CompletableFuture<>());++ executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, LambdaInvocationChain.MAX_DEPTH);++ verify(warmPool).acquire(fn);+ }+@Testvoid timeoutInvocation_destroysHandle_doesNotRelease() {RuntimeApiServer rtas = mock(RuntimeApiServer.class);