Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambdaweb): delete the oldest unused revisions past 50 as AWS does (#6518)
TATSUNO “Taz” Yasuhiro29eae434f675
diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdindex d773599b32..77616dad75 100644--- a/docs/services/lambda-web-functions.md+++ b/docs/services/lambda-web-functions.md@@ -38,13 +38,14 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A- **Failed revisions:** a revision whose code is not a zip, or whose files add up to more than 512 MiB, is stored `Failed`, as on AWS. It cannot be deployed: weights that name it, or `LatestRevision` while it is the newest revision, are `409 ConflictException`, and `LatestRevision` endpoints stay on their revision. The endpoint of a `CreateWebFunction` whose revision fails is `Failed` too. It answers every request with `409` and `Platform.EndpointNotActive` and refuses updates until it is deleted. In a stack, the revision's resource fails with the revision's `stateReason` and the rollback deletes it. An empty object is a `500 InternalServerException` with the body `{}`, and an object over 512 MiB is a `400 ValidationException`, as on AWS.- **Code comes from S3 only.** The object named in `buildConfig.codeConfig.s3Object` must exist in Floci's S3, as on AWS. A request without `versionId` is refused when the latest version is the null version, so the object has to be written after the bucket's versioning is enabled, as on AWS. When IAM enforcement is on, the bucket policy must also let `lambda.amazonaws.com` take `s3:GetObjectVersion` on the object. The policy sees the new revision ARN as `aws:SourceArn`, the function's account as `aws:SourceAccount` and the version Lambda reads as `s3:VersionId`. As on AWS, `s3:GetObject` is not evaluated, although the error names it. Floci does not check the caller's own S3 permissions or the KMS key policy of an encrypted object.- **Each revision keeps its own copy of the code**, read at creation from the version the request names or the current one, under the Lambda `code-path`. As on AWS, a later write or delete in the bucket does not change what the revision runs. AWS moves a revision to `Failed` when it later finds its object version gone, which Floci does not do.+- **Revision cleanup:** when a revision turns `Active` and the function has more than 50, the oldest revisions that no endpoint routes to are deleted until 50 are left, `Failed` ones included, as on AWS. A new `Failed` revision deletes nothing.- **Execution role:** a role in another account is `403 AccessDeniedException` "Cross-account pass role is not allowed.". A role that does not exist in IAM, or whose trust policy does not let `lambda.amazonaws.com` assume it, is `400 ValidationException` "The execution role <arn> cannot be assumed by lambda.amazonaws.com. Verify its trust policy. If the role was just created, retry in a few seconds.". As on AWS, this check sets no `aws:SourceAccount` or `aws:SourceArn`, so a trust policy that requires either refuses the role. The network connector ARN is checked for shape only.- **Resource policies** are checked the way AWS checks them before storing: the document grammar, a `lambda:` action, a `Resource` that names the function, a valid principal, and no public `Allow`. A wildcard principal needs a positive condition (`StringEquals`, `StringLike`, `ArnLike`, `Bool`) on a trusted key such as `aws:PrincipalAccount` or `aws:PrincipalArn`, with no wildcard in the account it names. An `IamAuth` endpoint evaluates it on requests, as below.- **Function names** are unique across the regions of an account, as on AWS. A name that another region already has is `409 ConflictException` "A function named <name> already exists in the account. Function names must be unique across all regions in an account.".- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`, all with the same id, as on AWS.-- **Not implemented yet:** SigV4a on `MultiRegion` endpoints, the check that a policy's principal exists, and the automatic deletion of revisions past 50.+- **Not implemented yet:** SigV4a on `MultiRegion` endpoints and the check that a policy's principal exists.### `aws lambda-web deploy`diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.javaindex f0f0143d10..a2a3d15fb9 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java@@ -134,6 +134,7 @@ public class LambdaWebService implements Resettable {private static final String DOMAIN_SHARD = "001";private static final int DOMAIN_ID_LENGTH = 16;private static final int DEFAULT_PAGE_SIZE = 50;+ static final int REVISION_CLEANUP_TARGET = 50;private static final String LOWERCASE_ALNUM = "abcdefghijklmnopqrstuvwxyz0123456789";private final RegionResolver regionResolver;@@ -445,12 +446,43 @@ public class LambdaWebService implements Resettable {endpoint.updatedAt = now();}}+ List<String> cleanedUp = revision.failureReason == null ? cleanUpRevisions(fn, revision) : List.of();fn.updatedAt = now();persist(region, fn);+ String accountId = AwsArnUtils.parse(fn.functionArn).accountId();+ cleanedUp.forEach(id -> code.deleteRevision(accountId, region, functionName, id));return copy(revision, WebFunctionRevision.class);}}+ /**+ * AWS deletes the oldest revisions that no endpoint uses, Failed ones too, once one becomes Active+ * while the function has more than 50.+ */+ private static List<String> cleanUpRevisions(WebFunction fn, WebFunctionRevision activated) {+ List<WebFunctionRevision> unused = fn.revisions.values().stream()+ .filter(r -> r != activated && endpointsUsing(fn, r.revisionId).isEmpty())+ .sorted(Comparator.comparing((WebFunctionRevision r) -> r.createdAt))+ .toList();+ List<String> deleted = new ArrayList<>();+ for (WebFunctionRevision old : unused) {+ if (fn.revisions.size() <= REVISION_CLEANUP_TARGET) {+ break;+ }+ fn.revisions.remove(old.revisionId);+ deleted.add(old.revisionId);+ }+ return deleted;+ }++ private static List<String> endpointsUsing(WebFunction fn, String revisionId) {+ return fn.endpoints.values().stream()+ .filter(e -> e.revisionWeights.stream().anyMatch(w -> w.revisionId.equals(revisionId)))+ .map(e -> e.endpointName)+ .sorted()+ .toList();+ }+public WebFunctionRevision getRevision(String region, String functionNameOrArn, String revisionIdOrArn) {String functionName = resolveFunctionName(region, functionNameOrArn, "GetWebFunctionRevision");String revisionId = resolveRevisionId(region, revisionIdOrArn, "GetWebFunctionRevision");@@ -486,11 +518,7 @@ public class LambdaWebService implements Resettable {synchronized (lockFor(region, functionName)) {WebFunction fn = function(region, functionName);WebFunctionRevision revision = revision(fn, revisionId);- List<String> using = fn.endpoints.values().stream()- .filter(e -> e.revisionWeights.stream().anyMatch(w -> w.revisionId.equals(revision.revisionId)))- .map(e -> e.endpointName)- .sorted()- .toList();+ List<String> using = endpointsUsing(fn, revision.revisionId);if (!using.isEmpty()) {throw new AwsException("ConflictException", "The revision " + revision.revisionId+ " cannot be deleted because the endpoints " + usingdiff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.javaindex 2120dbf0fc..c7c3a5f942 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java@@ -751,4 +751,40 @@ class LambdaWebIntegrationTest {given().when().delete(BASE + "/web-functions/" + fn).then().statusCode(204);}++ @Test+ @Order(13)+ void anActiveRevisionPastFiftyDeletesTheOldestUnusedOne() {+ String fn = FN + "-many";+ String first = given().contentType("application/json")+ .body("""+ {"functionName": "%s",+ "revisionConfig": {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}},+ "endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",+ "authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}+ """.formatted(fn, BUILD, ROLE))+ .when().put(BASE + "/web-functions")+ .then().statusCode(202)+ .extract().path("revision.revisionId");+ String revision = """+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}}+ """.formatted(BUILD, ROLE);+ for (int i = 0; i < 50; i++) {+ given().contentType("application/json").body(revision)+ .when().post(BASE + "/web-functions/" + fn + "/revisions")+ .then().statusCode(202);+ }++ given().contentType("application/json").body("{}")+ .when().post(BASE + "/web-functions/" + fn + "/list-revisions")+ .then().statusCode(200)+ .body("revisions", hasSize(50))+ .body("nextToken", nullValue());+ given().when().get(BASE + "/web-functions/" + fn + "/revisions/" + first)+ .then().statusCode(404)+ .header("X-Amzn-Errortype", "ResourceNotFoundException")+ .body("message", equalTo("The revision " + first + " does not exist."));++ given().when().delete(BASE + "/web-functions/" + fn).then().statusCode(204);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.javaindex 6c927e7058..d8c3b8387a 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java@@ -29,9 +29,11 @@ import java.io.UncheckedIOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;+import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.Set;import java.util.stream.Stream;import static org.junit.jupiter.api.Assertions.assertArrayEquals;@@ -970,6 +972,47 @@ class LambdaWebServiceTest {message(() -> service.createFunction(REGION, createRequest("app"))));}+ @Test+ void anActiveRevisionPastFiftyDeletesTheOldestUnusedOnes() {+ S3Service s3 = mock(S3Service.class);+ LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);+ byte[] zip = LambdaWebZips.indexJs("");+ when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(zip));+ String pinned = service.createFunction(REGION, createRequest("app")).revisions.keySet().iterator().next();+ ObjectNode pin = endpointConfig("pin").put("autoDeploymentMode", "Disabled");+ pin.putArray("revisionWeights").addObject().put("revisionId", pinned).put("weight", 100);+ service.createEndpoint(REGION, "app", pin);+ when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(NOT_A_ZIP));+ String failed = service.createRevision(REGION, "app", revisionConfig(30)).revisionId;+ when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(zip));+ List<String> active = new ArrayList<>();+ for (int i = 0; i < 48; i++) {+ active.add(service.createRevision(REGION, "app", revisionConfig(30)).revisionId);+ }+ assertEquals(50, service.getFunction(REGION, "app").revisions.size());++ service.createRevision(REGION, "app", revisionConfig(30));+ Set<String> kept = service.getFunction(REGION, "app").revisions.keySet();+ assertEquals(50, kept.size());+ assertFalse(kept.contains(failed));+ assertTrue(kept.contains(pinned));++ when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(NOT_A_ZIP));+ service.createRevision(REGION, "app", revisionConfig(30));+ assertEquals(51, service.getFunction(REGION, "app").revisions.size(), "a Failed revision cleans up nothing");++ when(s3.openObject("code", "app.zip", null)).thenAnswer(invocation -> object(zip));+ service.createRevision(REGION, "app", revisionConfig(30));+ kept = service.getFunction(REGION, "app").revisions.keySet();+ assertEquals(50, kept.size());+ assertFalse(kept.contains(active.get(0)));+ assertFalse(kept.contains(active.get(1)));+ assertTrue(kept.contains(active.get(2)));+ LambdaWebCode code = new LambdaWebCode(storageDir.resolve("code"));+ assertFalse(Files.exists(code.file(ACCOUNT_ID, REGION, "app", active.get(0))));+ assertTrue(Files.exists(code.file(ACCOUNT_ID, REGION, "app", active.get(2))));+ }+private ObjectNode stateFilter(String state) {ObjectNode request = mapper.createObjectNode();request.putArray("filters").addObject().put("name", "state").putArray("values").add(state);