Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambda): do not publish a version when nothing has changed (#2941)
Davidc48b6b0b0a38
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.javaindex e4582eb6ec..7b4c833553 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java@@ -300,6 +300,14 @@ class CodeDeployTest {v1 = pv1.version();assertThat(v1).isNotBlank();+ // A second version needs a real change behind it. AWS does not publish a version when the+ // code and configuration have not moved since the last one, so two publishes in a row+ // return the same version. A blue/green deployment shifts between two different builds+ // anyway, so deploy one here rather than publishing the same bytes twice.+ lambda.updateFunctionCode(r -> r+ .functionName(DEPLOY_FUNCTION)+ .zipFile(SdkBytes.fromByteArray(LambdaUtils.handlerZip())));+PublishVersionResponse pv2 = lambda.publishVersion(r -> r.functionName(DEPLOY_FUNCTION));v2 = pv2.version();assertThat(v2).isNotBlank().isNotEqualTo(v1);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 7a19441b4f..3ec0659c0b 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@@ -44,6 +44,7 @@ import java.util.ArrayList;import java.util.Base64;import java.util.List;import java.util.Map;+import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.UUID;@@ -1340,6 +1341,46 @@ public class LambdaService implements ResourceProvider {* {@code concurrencyOpLocks}) so publishes of unrelated functions do not* serialize on the instance monitor for the storage round-trip.*/+ /**+ * The already-published version cut from {@code $LATEST}'s current revision, if there is one.+ *+ * <p>Versions published before {@code sourceRevisionId} was recorded carry null and never match,+ * so existing state keeps its previous behaviour rather than deduplicating against a revision+ * nobody wrote down.+ */+ private LambdaFunction latestPublishedFrom(String region, LambdaFunction fn, String description) {+ String current = fn.getRevisionId();+ if (current == null) {+ return null;+ }+ // A hot-reload function's code lives in a bind-mounted directory that changes without any+ // API call, so revisionId cannot witness it. Deduplicating would hand back a version whose+ // identity no longer describes what will actually run, so these always publish.+ if (fn.getHotReloadHostPath() != null) {+ return null;+ }+ // Description is supplied at publish time rather than carried on $LATEST, so a publish that+ // names a new one is a real publish even when nothing else moved. LambdaVersionIntegrationTest+ // asserts exactly that: two publishes differing only in Description produce versions 1 and 2.+ String effective = description != null ? description : fn.getDescription();+ // Only the most recent version counts. AWS compares against the last version, so a+ // description going A then B then A must publish again rather than matching the older A:+ // scanning every version would return version 1 and leave the caller with a version whose+ // place in the history is wrong.+ return newestVersion(region, fn.getFunctionName())+ .filter(v -> current.equals(v.getSourceRevisionId()))+ .filter(v -> Objects.equals(effective, v.getDescription()))+ .orElse(null);+ }++ /** The highest-numbered published version of a function, if any. */+ private java.util.Optional<LambdaFunction> newestVersion(String region, String functionName) {+ return functionStore.listVersions(region, functionName).stream()+ .filter(v -> v.getVersion() != null && !"$LATEST".equals(v.getVersion()))+ .filter(v -> v.getVersion().chars().allMatch(Character::isDigit))+ .max(java.util.Comparator.comparingLong(v -> Long.parseLong(v.getVersion())));+ }+private int nextVersionNumber(String counterKey, String legacyCounterKey) {synchronized (versionCounterLocks.computeIfAbsent(counterKey, k -> new Object())) {Integer current = versionCounters.get(counterKey);@@ -1379,6 +1420,13 @@ public class LambdaService implements ResourceProvider {/*** Publishes a version of {@code $LATEST}.*+ * <p>An unchanged publish does not create a version: "AWS Lambda doesn't publish a version if+ * the function's configuration and code haven't changed since the last version". Publishing was+ * unconditional, so repeated publishes accumulated identical versions. "Unchanged" is decided by+ * {@code $LATEST}'s {@code revisionId}, which is regenerated on every code and configuration+ * update, so a version records the revision it was cut from and a later publish that finds it+ * unmoved returns that version.+ ** <p>{@code CodeSha256} is a precondition: "only publish a version if the hash value matches the* value that's specified". It was never parsed out of the request, so a caller that raced* someone else's deploy published code it had not authorised, silently (issue #2822).@@ -1407,6 +1455,12 @@ public class LambdaService implements ResourceProvider {400);}+ LambdaFunction unchanged = latestPublishedFrom(region, fn, description);+ if (unchanged != null) {+ LOG.debugv("PublishVersion for {0} found nothing changed since version {1}; "+ + "returning it rather than creating a duplicate", functionName, unchanged.getVersion());+ return unchanged;+ }int version = nextVersionNumber(versionCounterKey(region, fn),legacyVersionCounterKey(region, functionName));LambdaFunction snapshot = new LambdaFunction();@@ -1436,6 +1490,7 @@ public class LambdaService implements ResourceProvider {snapshot.setFileSystemConfigs(new ArrayList<>(fn.getFileSystemConfigs()));snapshot.setLastModified(System.currentTimeMillis());snapshot.setRevisionId(UUID.randomUUID().toString());+ snapshot.setSourceRevisionId(fn.getRevisionId());// Everything that determines what actually runs. Without these the snapshot describes a// function with no code: a version-qualified invoke resolves to it, launches a containerdiff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.javaindex 11e0707b16..28772a62cf 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java@@ -39,6 +39,14 @@ public class LambdaFunction {private List<Map<String, Object>> policies = new ArrayList<>();private long lastModified;private String revisionId;+ /**+ * For a published version, the {@code revisionId} that {@code $LATEST} carried when this+ * version was cut. AWS does not publish a second version when nothing has changed since the+ * last one, and {@code $LATEST}'s revision is regenerated on every code and configuration+ * update, so matching it is exactly the "unchanged since" test (issue #2822). Null on+ * {@code $LATEST} itself, and on versions published before this was recorded.+ */+ private String sourceRevisionId;private String version = "$LATEST";private LambdaUrlConfig urlConfig;private Integer reservedConcurrentExecutions;@@ -147,6 +155,8 @@ public class LambdaFunction {public void setLastModified(long lastModified) { this.lastModified = lastModified; }public String getRevisionId() { return revisionId; }+ public String getSourceRevisionId() { return sourceRevisionId; }+ public void setSourceRevisionId(String sourceRevisionId) { this.sourceRevisionId = sourceRevisionId; }public void setRevisionId(String revisionId) { this.revisionId = revisionId; }public String getVersion() { return version; }diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishVersionDedupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishVersionDedupIntegrationTest.javanew file mode 100644index 0000000000..8f6dfedbaa--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishVersionDedupIntegrationTest.java@@ -0,0 +1,104 @@+package io.github.hectorvent.floci.services.lambda;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.Test;++import java.io.ByteArrayOutputStream;+import java.util.Base64;+import java.util.zip.ZipEntry;+import java.util.zip.ZipOutputStream;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;++/**+ * Issue #2822, the unchanged-publish half. "AWS Lambda doesn't publish a version if the function's+ * configuration and code haven't changed since the last version." Publishing was unconditional, so+ * repeated publishes accumulated identical versions.+ */+@QuarkusTest+class LambdaPublishVersionDedupIntegrationTest {++ private static String zipB64(String body) throws Exception {+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {+ zos.putNextEntry(new ZipEntry("handler.py"));+ zos.write(("def handler(e, c):\n return {'body': '" + body + "'}\n").getBytes("UTF-8"));+ zos.closeEntry();+ }+ return Base64.getEncoder().encodeToString(baos.toByteArray());+ }++ private static void createFunction(String name) throws Exception {+ given()+ .contentType("application/json")+ .body("""+ {"FunctionName": "%s", "Runtime": "python3.12",+ "Role": "arn:aws:iam::000000000000:role/r", "Handler": "handler.handler",+ "Code": {"ZipFile": "%s"}}+ """.formatted(name, zipB64("v1")))+ .when().post("/2015-03-31/functions")+ .then().statusCode(org.hamcrest.Matchers.anyOf(equalTo(200), equalTo(201)));+ }++ private static String publish(String name, String bodyJson) {+ return given().contentType("application/json").body(bodyJson)+ .when().post("/2015-03-31/functions/" + name + "/versions")+ .then().statusCode(201).extract().path("Version");+ }++ @Test+ void publishingRepeatedlyWithNothingChangedReturnsTheExistingVersion() throws Exception {+ String fn = "pv-dedup-" + Long.toString(System.nanoTime(), 36);+ createFunction(fn);++ String first = publish(fn, "{}");+ org.junit.jupiter.api.Assertions.assertEquals(first, publish(fn, "{}"),+ "an unchanged publish must return the existing version, not create a new one");+ org.junit.jupiter.api.Assertions.assertEquals(first, publish(fn, "{}"),+ "repeated unchanged publishes must keep returning the same version");++ given().when().get("/2015-03-31/functions/" + fn + "/versions")+ .then().statusCode(200)+ .body("Versions.size()", equalTo(2)); // $LATEST plus the single published version+ }++ @Test+ void aRealChangeStillProducesANewVersion() throws Exception {+ String fn = "pv-change-" + Long.toString(System.nanoTime(), 36);+ createFunction(fn);+ String first = publish(fn, "{}");++ given().contentType("application/json")+ .body("{\"ZipFile\": \"%s\"}".formatted(zipB64("v2")))+ .when().put("/2015-03-31/functions/" + fn + "/code").then().statusCode(200);+ String second = publish(fn, "{}");+ org.junit.jupiter.api.Assertions.assertNotEquals(first, second,+ "a code change must still produce a new version");++ // Configuration counts too, since a version snapshots configuration as well as code.+ given().contentType("application/json").body("{\"Timeout\": 42}")+ .when().put("/2015-03-31/functions/" + fn + "/configuration").then().statusCode(200);+ String third = publish(fn, "{}");+ org.junit.jupiter.api.Assertions.assertNotEquals(second, third,+ "a configuration change must still produce a new version");+ }++ @Test+ void aDescriptionReturningToAnEarlierValueStillPublishes() throws Exception {+ // Only the most recent version counts. AWS compares against the last version, so A then B+ // then A must publish a third time. Matching any historical version would hand back version+ // 1 and leave the caller holding a version whose place in the history is wrong.+ String fn = "pv-abab-" + Long.toString(System.nanoTime(), 36);+ createFunction(fn);++ String a1 = publish(fn, "{\"Description\": \"A\"}");+ String b = publish(fn, "{\"Description\": \"B\"}");+ String a2 = publish(fn, "{\"Description\": \"A\"}");++ org.junit.jupiter.api.Assertions.assertNotEquals(a1, b);+ org.junit.jupiter.api.Assertions.assertNotEquals(a1, a2,+ "returning to an earlier description must publish, not match the older version");+ org.junit.jupiter.api.Assertions.assertNotEquals(b, a2);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.javaindex 36cdb5604d..fc2db7f616 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java@@ -38,11 +38,14 @@ class LambdaServicePersistenceTest {LambdaService first = serviceWithStorage(store, storage);first.createFunction(REGION, baseRequest("versioned-fn"));- assertEquals("1", first.publishVersion(REGION, "versioned-fn", null).getVersion());- assertEquals("2", first.publishVersion(REGION, "versioned-fn", null).getVersion());+ // Distinct descriptions so each call is a real publish. PublishVersion no longer creates a+ // version when nothing has changed since the last one (#2822), and this test is about the+ // version counter surviving a restart, not about that de-duplication.+ assertEquals("1", first.publishVersion(REGION, "versioned-fn", "one").getVersion());+ assertEquals("2", first.publishVersion(REGION, "versioned-fn", "two").getVersion());LambdaService reloaded = serviceWithStorage(store, storage);- LambdaFunction third = reloaded.publishVersion(REGION, "versioned-fn", null);+ LambdaFunction third = reloaded.publishVersion(REGION, "versioned-fn", "three");assertEquals("3", third.getVersion());assertTrue(third.getFunctionArn().endsWith(":3"));}