diff --git a/docs/services/index.md b/docs/services/index.md index a432828798..4a838e1b30 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -33,7 +33,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*`, `/tag/*` | REST JSON | 30 | | [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 54 | | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | -| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 72 | +| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 74 | | [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 23 | | [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 102 | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 8f9e6ef213..a869e42b8e 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -62,6 +62,8 @@ Floci Lambda runs your function code locally inside real Docker containers - clo | `PutFunctionConcurrency` | Set reserved concurrent executions | | `GetFunctionConcurrency` | Get reserved concurrent executions | | `DeleteFunctionConcurrency` | Clear reserved concurrent executions | +| `PutFunctionRecursionConfig` | Set the function's `RecursiveLoop` setting (`Allow` lifts the destination chain bound) | +| `GetFunctionRecursionConfig` | Get the function's `RecursiveLoop` setting, `Terminate` by default | | `PutProvisionedConcurrencyConfig` | Initialize Docker environments for a published version or simple alias | | `GetProvisionedConcurrencyConfig` | Read the allocation's actual initialization status and capacity | | `ListProvisionedConcurrencyConfigs` | List configured versions and aliases with their current capacity | @@ -192,6 +194,16 @@ Use `GetFunctionConcurrency` to read the function-wide reservation separately. Deleting the reservation with `DeleteFunctionConcurrency` removes the `Concurrency` member from subsequent unqualified `GetFunction` responses. +### Recursion Config + +`PutFunctionRecursionConfig` stores `RecursiveLoop` (`Allow` or `Terminate`) on the function and +`GetFunctionRecursionConfig` reads it back, `Terminate` until one is put. The setting is +function-wide: it is read from `$LATEST` whichever version or alias is invoked. + +Under `Terminate`, a chain of Lambda destinations stops at 16 hops (see Asynchronous Invocation +Destinations below). Under `Allow`, the function is not stopped at that bound, as on AWS, so a +function that continues itself through a destination runs on until it stops invoking itself. + ### Asynchronous Invocation Retries and Dead-Letter Queues An asynchronous invocation (`InvocationType: Event`) answers `202` immediately and runs on the background @@ -268,7 +280,8 @@ Two limits are worth knowing: - **A chain of Lambda destinations stops at 16 hops, but only a chain of Lambda destinations.** A function whose `OnSuccess` names another function would otherwise invoke forever; AWS halts such a chain at about the same depth through recursive loop detection, and here the record at the - sixteenth hop is dropped with a warning. The bound is keyed on the destination being a Lambda + sixteenth hop is dropped with a warning. A function whose `RecursiveLoop` is `Allow` (see + Recursion Config above) is not stopped there. The bound is keyed on the destination being a Lambda ARN, so a cycle that leaves and re-enters Lambda by another route is **not** bounded: a topic that fans back to the function, or a bus rule targeting it, each start a fresh chain at zero. Avoid configuring one until this is closed. diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java index 7cf1570c41..69c9ab5ca8 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java @@ -220,7 +220,8 @@ public class LambdaExecutorService implements Resettable { *

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. + * one a destination chain can re-enter through. A function whose {@code RecursiveLoop} is + * {@code Allow} is not dropped: AWS takes no action on a loop it detects for such a function. */ InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth) { return invoke(fn, payload, type, chainDepth, null); @@ -273,7 +274,8 @@ public class LambdaExecutorService implements Resettable { return new InvokeResult(204, null, new byte[0], null, requestId); } - if (type == InvocationType.Event && LambdaInvocationChain.exhausted(chainDepth)) { + if (type == InvocationType.Event && LambdaInvocationChain.exhausted(chainDepth) + && !allowsRecursiveLoop(fn)) { 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); @@ -308,7 +310,15 @@ public class LambdaExecutorService implements Resettable { if (lambdaService != null && !lambdaService.isLive(fn)) { return new InvokeResult(202, null, new byte[0], null, requestId); } - asyncExecutor.submit(() -> attempt(event, 1, null, THROTTLED_RETRY_FIRST_WAIT_MS)); + Runnable firstAttempt = () -> attempt(event, 1, null, THROTTLED_RETRY_FIRST_WAIT_MS); + if (LambdaInvocationChain.exhausted(chainDepth)) { + // Only a function whose RecursiveLoop is Allow gets here, and its loop has no bound. A + // full pool's caller-runs fallback would nest each further hop on one stack, so these + // start on a thread of their own. + retryScheduler.schedule(firstAttempt, 0); + } else { + asyncExecutor.submit(firstAttempt); + } return new InvokeResult(202, null, new byte[0], null, requestId); } @@ -330,6 +340,19 @@ public class LambdaExecutorService implements Resettable { return null; } + /** + * Whether the function opted out of recursive loop detection. {@code RecursiveLoop} is + * function-wide, so it is read from {@code $LATEST} rather than a version's snapshot. + */ + private boolean allowsRecursiveLoop(LambdaFunction fn) { + try { + return LambdaService.RECURSIVE_LOOP_ALLOW.equals(latest(resolveLambdaService(), fn).getRecursiveLoop()); + } catch (RuntimeException e) { + LOG.warnv("Could not read the recursion config of {0}: {1}", fn.getFunctionArn(), e.getMessage()); + return false; + } + } + /** * Reserved concurrency is function-wide, so the permit is taken against the function's {@code $LATEST} * record, which holds the reservation, rather than a version's snapshot, which has none. diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaInvocationChain.java b/src/main/java/io/floci/aws/services/lambda/LambdaInvocationChain.java index f4fccc7111..534319a13f 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaInvocationChain.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaInvocationChain.java @@ -17,7 +17,9 @@ import java.util.function.Supplier; * *

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. + * otherwise recurse until the stack ran out. A function whose {@code RecursiveLoop} is + * {@code Allow} runs past the bound, so the executor starts those invocations off the pool, where + * no fallback can put them on the caller's stack. * *

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 diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaRecursionConfigController.java b/src/main/java/io/floci/aws/services/lambda/LambdaRecursionConfigController.java new file mode 100644 index 0000000000..258d798483 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/LambdaRecursionConfigController.java @@ -0,0 +1,95 @@ +package io.floci.aws.services.lambda; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.SmithyValidationErrors; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.List; + +/** + * Lambda recursion config endpoints. + * + * PutFunctionRecursionConfig: PUT /2024-08-31/functions/{FunctionName}/recursion-config + * GetFunctionRecursionConfig: GET /2024-08-31/functions/{FunctionName}/recursion-config + * + * {@code Allow} lifts the bound {@link LambdaInvocationChain} puts on a chain of asynchronous + * invocations; {@code Terminate}, the default, keeps it. + */ +@Path("/2024-08-31/functions/{functionName}/recursion-config") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LambdaRecursionConfigController { + + private static final String RECURSIVE_LOOP = "RecursiveLoop"; + private static final List RECURSIVE_LOOP_VALUES = List.of("Allow", "Terminate"); + + private final LambdaService lambdaService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public LambdaRecursionConfigController(LambdaService lambdaService, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.lambdaService = lambdaService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @PUT + public Response putFunctionRecursionConfig(@Context HttpHeaders headers, + @PathParam("functionName") String functionName, + String body) { + String region = regionResolver.resolveRegion(headers); + String recursiveLoop = recursiveLoopOf(body); + return response(lambdaService.putFunctionRecursionConfig(region, functionName, recursiveLoop)); + } + + @GET + public Response getFunctionRecursionConfig(@Context HttpHeaders headers, + @PathParam("functionName") String functionName) { + String region = regionResolver.resolveRegion(headers); + return response(lambdaService.getFunctionRecursionConfig(region, functionName)); + } + + private String recursiveLoopOf(String body) { + JsonNode request; + try { + request = objectMapper.readTree(body == null ? "" : body); + } catch (JsonProcessingException e) { + throw new AwsException("InvalidRequestContentException", + "Could not parse request body into json: " + e.getOriginalMessage(), 400); + } + JsonNode value = request == null ? null : request.get(RECURSIVE_LOOP); + if (value == null || value.isNull()) { + throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("recursiveLoop")); + } + String recursiveLoop = value.asText(); + if (!value.isTextual() || !RECURSIVE_LOOP_VALUES.contains(recursiveLoop)) { + throw SmithyValidationErrors.validationException( + SmithyValidationErrors.notInEnum(recursiveLoop, "recursiveLoop", RECURSIVE_LOOP_VALUES)); + } + return recursiveLoop; + } + + private Response response(String recursiveLoop) { + ObjectNode root = objectMapper.createObjectNode(); + root.put(RECURSIVE_LOOP, recursiveLoop); + return Response.ok(root).build(); + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaService.java b/src/main/java/io/floci/aws/services/lambda/LambdaService.java index 64fd8f3670..bf27566af4 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaService.java @@ -98,6 +98,8 @@ import java.util.stream.Collectors; public class LambdaService implements ResourceProvider, VpcDependencyProvider { private static final Logger LOG = Logger.getLogger(LambdaService.class); + static final String RECURSIVE_LOOP_ALLOW = "Allow"; + private static final String DEFAULT_RECURSIVE_LOOP = "Terminate"; /** * Qualifier constraint the live service enforces, taken from its own ValidationException @@ -3846,6 +3848,44 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { return fn.getReservedConcurrentExecutions(); } + /** + * Stores the function's {@code RecursiveLoop} setting. {@code Allow} lifts the bound + * {@link LambdaInvocationChain} puts on a chain of asynchronous invocations. The record is read + * again under the function's lock, so a save cannot bring back a function that a concurrent + * DeleteFunction removed. + */ + public String putFunctionRecursionConfig(String region, String functionName, String recursiveLoop) { + LambdaFunction observed = getOwnFunction(region, functionName); + synchronized (lockForConcurrencyOp(observed.getFunctionArn())) { + LambdaFunction fn = getFunction(region, observed.getFunctionName()); + fn.setRecursiveLoop(recursiveLoop); + functionStore.save(region, fn); + } + return recursiveLoop; + } + + /** The function's {@code RecursiveLoop} setting, {@code Terminate} until one is put. */ + public String getFunctionRecursionConfig(String region, String functionName) { + String recursiveLoop = getOwnFunction(region, functionName).getRecursiveLoop(); + return recursiveLoop == null ? DEFAULT_RECURSIVE_LOOP : recursiveLoop; + } + + /** + * The caller's function that {@code functionName} names. An ARN of another account or + * partition names no function of the caller's, even when the caller has one of that name. + */ + private LambdaFunction getOwnFunction(String region, String functionName) { + LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionName); + LambdaArnUtils.enforceRegion(region, ref); + boolean foreignAccount = ref.account() != null && !regionResolver.getAccountId().equals(ref.account()); + boolean foreignPartition = AwsArnUtils.isArn(functionName) + && !regionResolver.partitionForRegion(region).equals(AwsArnUtils.parse(functionName).partition()); + if (foreignAccount || foreignPartition) { + throw new AwsException("ResourceNotFoundException", "Function not found: " + functionName, 404); + } + return getFunction(region, ref.name()); + } + /** * Aggregates the caller's stored {@code $LATEST} functions in a region: code-size usage, * function count, and the unreserved share of the configured concurrency limit. diff --git a/src/main/java/io/floci/aws/services/lambda/model/LambdaFunction.java b/src/main/java/io/floci/aws/services/lambda/model/LambdaFunction.java index aef1023ee0..53541773db 100644 --- a/src/main/java/io/floci/aws/services/lambda/model/LambdaFunction.java +++ b/src/main/java/io/floci/aws/services/lambda/model/LambdaFunction.java @@ -50,6 +50,7 @@ public class LambdaFunction { private String version = "$LATEST"; private LambdaUrlConfig urlConfig; private Integer reservedConcurrentExecutions; + private String recursiveLoop; private List architectures; private int ephemeralStorageSize = 512; private String tracingMode = "PassThrough"; @@ -172,6 +173,8 @@ public class LambdaFunction { public void setUrlConfig(LambdaUrlConfig urlConfig) { this.urlConfig = urlConfig; } public Integer getReservedConcurrentExecutions() { return reservedConcurrentExecutions; } + public String getRecursiveLoop() { return recursiveLoop; } + public void setRecursiveLoop(String recursiveLoop) { this.recursiveLoop = recursiveLoop; } public void setReservedConcurrentExecutions(Integer reservedConcurrentExecutions) { this.reservedConcurrentExecutions = reservedConcurrentExecutions; } public List getArchitectures() { return architectures; } diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java index 97b9817128..367e0d4109 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java @@ -742,6 +742,8 @@ class IamRestRouteEnforcementIntegrationTest { {"POST", "/2015-03-31/functions/" + name + "/versions", "lambda:PublishVersion"}, {"PUT", "/2017-10-31/functions/" + name + "/concurrency", "lambda:PutFunctionConcurrency"}, {"GET", "/2019-09-30/functions/" + name + "/concurrency", "lambda:GetFunctionConcurrency"}, + {"PUT", "/2024-08-31/functions/" + name + "/recursion-config", "lambda:PutFunctionRecursionConfig"}, + {"GET", "/2024-08-31/functions/" + name + "/recursion-config", "lambda:GetFunctionRecursionConfig"}, {"PUT", "/2019-09-25/functions/" + name + "/event-invoke-config", "lambda:PutFunctionEventInvokeConfig"}, {"GET", "/2020-06-30/functions/" + name + "/code-signing-config", "lambda:GetFunctionCodeSigningConfig"}, }; diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java index ef69a4c4e5..74dae9f0a6 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java @@ -18,6 +18,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; @@ -96,10 +99,15 @@ class LambdaExecutorServiceTest { return owned; } - @Test - void asyncInvocationPastTheChainBound_isDroppedWithoutRunningTheFunction() { + @ParameterizedTest + @NullSource + @ValueSource(strings = "Terminate") + void asyncInvocationPastTheChainBound_isDroppedWithoutRunningTheFunction(String recursiveLoop) { // 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. + // An unset RecursiveLoop is Terminate. + fn.setRecursiveLoop(recursiveLoop); + InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH); @@ -129,6 +137,53 @@ class LambdaExecutorServiceTest { verify(warmPool, never()).acquire(any()); } + @Test + void asyncInvocationPastTheChainBound_stillRunsWhenRecursiveLoopIsAllow() { + fn.setRecursiveLoop("Allow"); + + executor.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH); + + verify(warmPool, timeout(5000).atLeastOnce()).acquire(fn); + } + + @Test + void asyncInvocationPastTheChainBound_startsOffThePoolWhenRecursiveLoopIsAllow() { + // The pool's caller-runs fallback would nest an unbounded loop on one stack. + ManualRetries retries = new ManualRetries(); + LambdaExecutorService scheduled = registerExecutor(new LambdaExecutorService(warmPool, new ObjectMapper(), + concurrencyLimiter, null, null, retries.clock, Duration.ZERO, Duration.ofSeconds(30), retries)); + fn.setRecursiveLoop("Allow"); + when(warmPool.acquire(fn)).thenThrow(new IllegalStateException("no container in this test")); + + scheduled.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH); + + assertEquals(List.of(0L), retries.delays); + verify(warmPool, never()).acquire(any()); + retries.due.remove().run(); + verify(warmPool).acquire(fn); + } + + @Test + void aVersionPastTheChainBound_readsRecursiveLoopFromTheFunction() { + // A version's snapshot does not carry the setting; RecursiveLoop is function-wide. + fn.setRecursiveLoop("Allow"); + LambdaFunction version = new LambdaFunction(); + version.setFunctionName("test-fn"); + version.setVersion("1"); + version.setFunctionArn(fn.getFunctionArn() + ":1"); + version.setTimeout(1); + LambdaService lambdaService = mock(LambdaService.class); + when(lambdaService.findLatest(version)).thenReturn(Optional.of(fn)); + when(lambdaService.isLive(version)).thenReturn(true); + when(lambdaService.findEventInvokeConfig(version, null)).thenReturn(Optional.empty()); + LambdaExecutorService versionExecutor = registerExecutor(new LambdaExecutorService(warmPool, new ObjectMapper(), + concurrencyLimiter, null, lambdaService)); + + versionExecutor.invoke(version, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH); + + verify(warmPool, timeout(5000).atLeastOnce()).acquire(version); + } + @Test void asyncInvocationShortOfTheChainBound_stillRuns() { executor.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH - 1); diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaRecursionConfigIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaRecursionConfigIntegrationTest.java new file mode 100644 index 0000000000..d8d63bc9fa --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/LambdaRecursionConfigIntegrationTest.java @@ -0,0 +1,189 @@ +package io.floci.aws.services.lambda; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.LambdaCodeFixtures; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.LambdaException; +import software.amazon.awssdk.services.lambda.model.RecursiveLoop; +import software.amazon.awssdk.services.lambda.model.ResourceNotFoundException; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +class LambdaRecursionConfigIntegrationTest { + + private static final String ACCOUNT = "000000009480"; + private static final String OTHER_ACCOUNT = "000000009481"; + + private final List functions = new ArrayList<>(); + private LambdaClient client; + + @BeforeEach + void openClient() { + client = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_EAST_1); + } + + @AfterEach + void cleanUp() { + try { + for (String name : functions) { + client.deleteFunction(request -> request.functionName(name)); + } + } finally { + client.close(); + } + } + + @Test + void recursiveLoopIsTerminateUntilOneIsPut() { + String name = createFunction(client); + + assertEquals(RecursiveLoop.TERMINATE, + client.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + } + + @Test + void putStoresTheSettingAndGetReadsItBack() { + String name = createFunction(client); + + assertEquals(RecursiveLoop.ALLOW, client.putFunctionRecursionConfig( + request -> request.functionName(name).recursiveLoop(RecursiveLoop.ALLOW)).recursiveLoop()); + assertEquals(RecursiveLoop.ALLOW, + client.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + + assertEquals(RecursiveLoop.TERMINATE, client.putFunctionRecursionConfig( + request -> request.functionName(name).recursiveLoop(RecursiveLoop.TERMINATE)).recursiveLoop()); + assertEquals(RecursiveLoop.TERMINATE, + client.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + } + + @Test + void theFunctionIsNamedByItsArnToo() { + String name = createFunction(client); + String arn = client.getFunctionConfiguration(request -> request.functionName(name)).functionArn(); + + client.putFunctionRecursionConfig(request -> request.functionName(arn).recursiveLoop(RecursiveLoop.ALLOW)); + + assertEquals(RecursiveLoop.ALLOW, + client.getFunctionRecursionConfig(request -> request.functionName(arn)).recursiveLoop()); + assertEquals(RecursiveLoop.ALLOW, + client.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + } + + @Test + void theSettingSurvivesAConfigurationUpdate() { + String name = createFunction(client); + client.putFunctionRecursionConfig(request -> request.functionName(name).recursiveLoop(RecursiveLoop.ALLOW)); + + client.updateFunctionConfiguration(request -> request.functionName(name).description("updated")); + + assertEquals(RecursiveLoop.ALLOW, + client.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + } + + @Test + void anotherAccountsFunctionOfTheSameNameKeepsItsOwnSetting() { + String name = createFunction(client); + try (LambdaClient other = AwsTestClients.create(LambdaClient.builder(), OTHER_ACCOUNT, Region.US_EAST_1)) { + createFunction(other, OTHER_ACCOUNT, name); + try { + client.putFunctionRecursionConfig( + request -> request.functionName(name).recursiveLoop(RecursiveLoop.ALLOW)); + + assertEquals(RecursiveLoop.TERMINATE, + other.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + } finally { + other.deleteFunction(request -> request.functionName(name)); + } + } + } + + @Test + void anotherAccountsArnDoesNotNameTheCallersFunctionOfThatName() { + String name = createFunction(client); + String foreignArn = "arn:aws:lambda:us-east-1:" + OTHER_ACCOUNT + ":function:" + name; + + assertThrows(ResourceNotFoundException.class, () -> client.putFunctionRecursionConfig( + request -> request.functionName(foreignArn).recursiveLoop(RecursiveLoop.ALLOW))); + assertThrows(ResourceNotFoundException.class, + () -> client.getFunctionRecursionConfig(request -> request.functionName(foreignArn))); + assertThrows(ResourceNotFoundException.class, () -> client.getFunctionRecursionConfig( + request -> request.functionName(OTHER_ACCOUNT + ":function:" + name))); + + assertEquals(RecursiveLoop.TERMINATE, + client.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + } + + @Test + void anUnknownFunctionIsNotFound() { + assertThrows(ResourceNotFoundException.class, + () -> client.getFunctionRecursionConfig(request -> request.functionName("no-such-function"))); + assertThrows(ResourceNotFoundException.class, () -> client.putFunctionRecursionConfig( + request -> request.functionName("no-such-function").recursiveLoop(RecursiveLoop.ALLOW))); + } + + @Test + void aValueOutsideTheEnumIsRefusedAndLeavesTheSettingAlone() { + String name = createFunction(client); + + LambdaException error = assertThrows(LambdaException.class, () -> client.putFunctionRecursionConfig( + request -> request.functionName(name).recursiveLoop("Sometimes"))); + assertEquals(400, error.statusCode()); + + assertEquals(RecursiveLoop.TERMINATE, + client.getFunctionRecursionConfig(request -> request.functionName(name)).recursiveLoop()); + } + + @Test + void aMissingRecursiveLoopIsRefused() { + String name = createFunction(client); + + given().header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + + "/20260101/us-east-1/lambda/aws4_request") + .contentType("application/json").body("{}") + .when().put("/2024-08-31/functions/" + name + "/recursion-config") + .then().statusCode(400) + .body(containsString("recursiveLoop")); + } + + @Test + void theResponseCarriesOnlyRecursiveLoop() { + String name = createFunction(client); + + given().header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + + "/20260101/us-east-1/lambda/aws4_request") + .contentType("application/json").body("{\"RecursiveLoop\":\"Allow\"}") + .when().put("/2024-08-31/functions/" + name + "/recursion-config") + .then().statusCode(200) + .body("RecursiveLoop", equalTo("Allow")) + .body("size()", equalTo(1)); + } + + private String createFunction(LambdaClient owner) { + String name = "recursion-config-" + UUID.randomUUID(); + createFunction(owner, ACCOUNT, name); + functions.add(name); + return name; + } + + private static void createFunction(LambdaClient owner, String account, String name) { + owner.createFunction(request -> request.functionName(name).runtime("nodejs20.x") + .role("arn:aws:iam::" + account + ":role/lambda-role").handler("index.handler") + .code(code -> code.zipFile(SdkBytes.fromByteArray( + LambdaCodeFixtures.nodeJsZip("exports.handler = async () => ({});"))))); + } +} diff --git a/tools/docs/service_matrix.yaml b/tools/docs/service_matrix.yaml index 6afa1bee2d..38bbc3f939 100644 --- a/tools/docs/service_matrix.yaml +++ b/tools/docs/service_matrix.yaml @@ -290,6 +290,7 @@ action_count_sources: - { path: services/lambda/LambdaCodeSigningConfigFunctionsController.java, mode: rest } - { path: services/lambda/LambdaResponseStreamController.java, mode: rest } - { path: services/lambda/LambdaConcurrencyController.java, mode: rest } + - { path: services/lambda/LambdaRecursionConfigController.java, mode: rest } - { path: services/lambda/LambdaProvisionedConcurrencyController.java, mode: rest } - { path: services/lambda/LambdaEventInvokeController.java, mode: rest } - { path: services/lambda/LambdaLayerController.java, mode: rest }