feat(lambda): make reactive S3 sync toggleable and optionally async (#6548)

* feat(lambda): make reactive S3 sync toggleable and optionally async, reporting LastUpdateStatus while it runs

* fix(lambda): run async reactive S3 syncs as the uploader's account, keep InProgress continuous, and queue the latest source per function

* fix(lambda): clear a failed reactive sync's LastUpdateStatus on UpdateFunctionConfiguration, and test async syncs from a second account

* test(lambda): share LambdaCodeSourcesProfile for the async reactive sync test, reuse LambdaWebZips, and extract the failed-sync setup
This commit is contained in:
floverfelt authored and GitHub committed 2026-10-25 21:55:13 -04:00
1 parent bffffedb88
commit 89be5c1742
12 files changed
+475 -29

No files matched your search

@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
import io.github.hectorvent.floci.testing.LambdaCodeSourcesProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
/**
* With asynchronous reactive S3 sync, the re-deploy runs on a background thread with no request of
* its own, so it must read the object in the uploader's account rather than the default one.
*/
@QuarkusTest
@TestProfile(LambdaCodeSourcesProfile.class)
class LambdaAsyncReactiveSyncIntegrationTest {
private static final String ACCOUNT = "000000000021";
private static final String S3_AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260215/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc";
private static final String LAMBDA_AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260215/us-east-1/lambda/aws4_request, SignedHeaders=host, Signature=abc";
private static final String BUCKET = "async-reactive-sync-bucket";
private static final String KEY = "function.zip";
private static final String FN = "async-reactive-sync-fn";
@Test
void uploadFromANonDefaultAccountRedeploysTheFunctionInTheBackground() throws Exception {
byte[] v1 = LambdaWebZips.indexJs("exports.handler = async () => 'v1';");
byte[] v2 = LambdaWebZips.indexJs("exports.handler = async () => 'v2';");
given().header("Authorization", S3_AUTH).when().put("/" + BUCKET).then().statusCode(200);
given().header("Authorization", S3_AUTH).body(v1).when().put("/" + BUCKET + "/" + KEY).then().statusCode(200);
given()
.header("Authorization", LAMBDA_AUTH)
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Role": "arn:aws:iam::%s:role/role",
"Handler": "index.handler",
"Code": {
"S3Bucket": "%s",
"S3Key": "%s"
}
}
""".formatted(FN, ACCOUNT, BUCKET, KEY))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(201)
.body("CodeSha256", equalTo(sha256(v1)));
given().header("Authorization", S3_AUTH).body(v2).when().put("/" + BUCKET + "/" + KEY).then().statusCode(200);
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() ->
given()
.header("Authorization", LAMBDA_AUTH)
.when()
.get("/2015-03-31/functions/" + FN + "/configuration")
.then()
.statusCode(200)
.body("LastUpdateStatus", equalTo("Successful"))
.body("CodeSha256", equalTo(sha256(v2))));
}
private static String sha256(byte[] data) throws Exception {
return Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(data));
}
}
@@ -2354,13 +2354,18 @@ class LambdaServiceTest {
}
private static LambdaService s3BackedService(S3Service s3, WarmPool warmPool, ZipExtractor extractor) {
return s3BackedService(s3, warmPool, extractor, null);
}
private static LambdaService s3BackedService(S3Service s3, WarmPool warmPool, ZipExtractor extractor,
EmulatorConfig config) {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
LambdaFunctionStore functionStore = new LambdaFunctionStore(new InMemoryStorage<String, LambdaFunction>());
LambdaAliasStore aliasStore = new LambdaAliasStore(storageFactory);
return new LambdaService(functionStore, null, new LambdaConcurrencyLimiter(),
warmPool, new CodeStore(Path.of("target/test-data/lambda-code")), extractor, null,
warmPool, new CodeStore(Path.of("target/test-data/lambda-code")), extractor, config,
new RegionResolver(REGION, "000000000000"), null, aliasStore,
new LambdaTargetResolver(functionStore, aliasStore), s3, null, null, null, null,
storageFactory, null, null, null, null, new ObjectMapper());
@@ -2420,6 +2425,201 @@ class LambdaServiceTest {
}
}
@Test
void reactiveSyncDisabled_leavesTheFunctionOnItsDeployedCode() throws Exception {
S3Service s3 = mock(S3Service.class);
WarmPool warmPool = mock(WarmPool.class);
LambdaService syncingService = s3BackedService(s3, warmPool, new ZipExtractor(),
reactiveS3SyncConfig(false, false));
String name = "reactive-disabled-" + UUID.randomUUID();
when(s3.openObject("code-bucket", "function.zip", null)).thenReturn(heldObject(zipWithBody("v1")));
Map<String, Object> request = baseRequest(name);
request.put("Code", Map.of("S3Bucket", "code-bucket", "S3Key", "function.zip"));
LambdaFunction latest = syncingService.createFunction(REGION, request);
syncingService.onS3ObjectUpdated(new S3ObjectUpdatedEvent("code-bucket", "function.zip"));
verify(s3, times(1)).openObject("code-bucket", "function.zip", null);
verify(warmPool, never()).pushCodeUpdate(any());
assertEquals("v1", Files.readString(Path.of(latest.getCodeLocalPath()).resolve("index.js")).trim());
}
@Test
void asyncReactiveSync_returnsBeforeTheRedeployAndReportsInProgressUntilItFinishes() throws Exception {
S3Service s3 = mock(S3Service.class);
WarmPool warmPool = mock(WarmPool.class);
ZipExtractor extractor = spy(new ZipExtractor());
LambdaService syncingService = s3BackedService(s3, warmPool, extractor, reactiveS3SyncConfig(true, true));
String name = "reactive-async-" + UUID.randomUUID();
when(s3.openObject("code-bucket", "function.zip", null))
.thenReturn(heldObject(zipWithBody("v1")))
.thenReturn(heldObject(zipWithBody("v2")));
Map<String, Object> request = baseRequest(name);
request.put("Code", Map.of("S3Bucket", "code-bucket", "S3Key", "function.zip"));
LambdaFunction latest = syncingService.createFunction(REGION, request);
CountDownLatch release = new CountDownLatch(1);
doAnswer(inv -> {
assertTrue(release.await(5, TimeUnit.SECONDS));
return inv.callRealMethod();
}).when(extractor).extractTo(any(byte[].class), any(Path.class), anyInt(), any(Runnable.class));
try {
syncingService.onS3ObjectUpdated(new S3ObjectUpdatedEvent("code-bucket", "function.zip"));
assertEquals("InProgress", syncingService.lastUpdateStatus(latest));
verify(warmPool, never()).pushCodeUpdate(any());
} finally {
release.countDown();
}
verify(warmPool, timeout(5000)).pushCodeUpdate(latest);
awaitLastUpdateStatus(syncingService, latest, "Successful");
assertEquals("v2", Files.readString(Path.of(latest.getCodeLocalPath()).resolve("index.js")).trim());
}
@Test
void asyncReactiveSync_coalescesUploadsThatArriveWhileOneIsRunning() throws Exception {
S3Service s3 = mock(S3Service.class);
WarmPool warmPool = mock(WarmPool.class);
ZipExtractor extractor = spy(new ZipExtractor());
LambdaService syncingService = s3BackedService(s3, warmPool, extractor, reactiveS3SyncConfig(true, true));
String name = "reactive-coalesce-" + UUID.randomUUID();
when(s3.openObject("code-bucket", "function.zip", null))
.thenReturn(heldObject(zipWithBody("v1")))
.thenReturn(heldObject(zipWithBody("v2")))
.thenReturn(heldObject(zipWithBody("v5")));
Map<String, Object> request = baseRequest(name);
request.put("Code", Map.of("S3Bucket", "code-bucket", "S3Key", "function.zip"));
LambdaFunction latest = syncingService.createFunction(REGION, request);
CountDownLatch extracting = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(inv -> {
extracting.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return inv.callRealMethod();
}).when(extractor).extractTo(any(byte[].class), any(Path.class), anyInt(), any(Runnable.class));
try {
syncingService.onS3ObjectUpdated(new S3ObjectUpdatedEvent("code-bucket", "function.zip"));
assertTrue(extracting.await(5, TimeUnit.SECONDS));
for (int upload = 3; upload <= 5; upload++) {
syncingService.onS3ObjectUpdated(new S3ObjectUpdatedEvent("code-bucket", "function.zip"));
}
} finally {
release.countDown();
}
verify(warmPool, timeout(5000).times(2)).pushCodeUpdate(latest);
awaitLastUpdateStatus(syncingService, latest, "Successful");
// Create, the running sync, and one queued sync for the three uploads behind it.
verify(s3, times(3)).openObject("code-bucket", "function.zip", null);
assertEquals("v5", Files.readString(Path.of(latest.getCodeLocalPath()).resolve("index.js")).trim());
}
@Test
void asyncReactiveSync_deploysAnUploadToANewSourceWhileTheOldOneIsStillQueued() throws Exception {
S3Service s3 = mock(S3Service.class);
WarmPool warmPool = mock(WarmPool.class);
LambdaService syncingService = s3BackedService(s3, warmPool, new ZipExtractor(),
reactiveS3SyncConfig(true, true));
String name = "reactive-new-source-" + UUID.randomUUID();
when(s3.openObject("code-bucket", "old.zip", null)).thenReturn(heldObject(zipWithBody("v1")));
when(s3.openObject("code-bucket", "new.zip", null))
.thenReturn(heldObject(zipWithBody("v2")))
.thenReturn(heldObject(zipWithBody("v3")));
Map<String, Object> request = baseRequest(name);
request.put("Code", Map.of("S3Bucket", "code-bucket", "S3Key", "old.zip"));
LambdaFunction latest = syncingService.createFunction(REGION, request);
// Holding the function's lock keeps the old source's sync queued behind it.
synchronized (syncingService.lockForConcurrencyOp(latest.getFunctionArn())) {
syncingService.onS3ObjectUpdated(new S3ObjectUpdatedEvent("code-bucket", "old.zip"));
syncingService.updateFunctionCode(REGION, name, Map.of("S3Bucket", "code-bucket", "S3Key", "new.zip"));
syncingService.onS3ObjectUpdated(new S3ObjectUpdatedEvent("code-bucket", "new.zip"));
assertEquals("InProgress", syncingService.lastUpdateStatus(latest));
}
verify(warmPool, timeout(5000)).pushCodeUpdate(latest);
awaitLastUpdateStatus(syncingService, latest, "Successful");
verify(s3, times(1)).openObject("code-bucket", "old.zip", null);
verify(s3, times(2)).openObject("code-bucket", "new.zip", null);
assertEquals("v3", Files.readString(Path.of(latest.getCodeLocalPath()).resolve("index.js")).trim());
}
@Test
void failedReactiveSync_reportsFailedUntilTheNextCodeUpdate() throws Exception {
S3Service s3 = mock(S3Service.class);
WarmPool warmPool = mock(WarmPool.class);
LambdaService syncingService = s3BackedService(s3, warmPool, new ZipExtractor(),
reactiveS3SyncConfig(true, false));
LambdaFunction latest = functionWhoseLastSyncFailed(syncingService, s3);
assertEquals("Failed", syncingService.lastUpdateStatus(latest));
assertEquals("Reactive S3 sync from s3://code-bucket/function.zip failed: The specified key does not exist.",
syncingService.lastUpdateStatusReason(latest));
verify(warmPool, never()).pushCodeUpdate(any());
syncingService.updateFunctionCode(REGION, latest.getFunctionName(), Map.of("ZipFile", zipWithBody("v2")));
assertEquals("Successful", syncingService.lastUpdateStatus(latest));
assertNull(syncingService.lastUpdateStatusReason(latest));
}
@Test
void failedReactiveSync_isClearedByAConfigurationUpdate() throws Exception {
S3Service s3 = mock(S3Service.class);
LambdaService syncingService = s3BackedService(s3, mock(WarmPool.class), new ZipExtractor(),
reactiveS3SyncConfig(true, false));
LambdaFunction latest = functionWhoseLastSyncFailed(syncingService, s3);
syncingService.updateFunctionConfiguration(REGION, latest.getFunctionName(),
Map.of("Environment", Map.of("Variables", Map.of("STAGE", "ci"))));
assertEquals("Successful", syncingService.lastUpdateStatus(latest));
assertNull(syncingService.lastUpdateStatusReason(latest));
}
/**
* A function deployed from {@code s3://code-bucket/function.zip} whose sync after the object was
* overwritten failed because the object had gone. {@code s3} is the mock {@code service} reads.
*/
private LambdaFunction functionWhoseLastSyncFailed(LambdaService service, S3Service s3)
throws Exception {
when(s3.openObject("code-bucket", "function.zip", null))
.thenReturn(heldObject(zipWithBody("v1")))
.thenThrow(new AwsException("NoSuchKey", "The specified key does not exist.", 404));
Map<String, Object> request = baseRequest("reactive-failed-" + UUID.randomUUID());
request.put("Code", Map.of("S3Bucket", "code-bucket", "S3Key", "function.zip"));
LambdaFunction latest = service.createFunction(REGION, request);
service.onS3ObjectUpdated(new S3ObjectUpdatedEvent("code-bucket", "function.zip"));
return latest;
}
private static EmulatorConfig reactiveS3SyncConfig(boolean enabled, boolean async) {
EmulatorConfig cfg = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig svc = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.LambdaServiceConfig lambdaCfg = mock(EmulatorConfig.LambdaServiceConfig.class);
EmulatorConfig.LambdaServiceConfig.ReactiveS3Sync sync =
mock(EmulatorConfig.LambdaServiceConfig.ReactiveS3Sync.class);
when(cfg.services()).thenReturn(svc);
when(svc.lambda()).thenReturn(lambdaCfg);
when(lambdaCfg.reactiveS3Sync()).thenReturn(sync);
when(lambdaCfg.defaultTimeoutSeconds()).thenReturn(3);
when(lambdaCfg.defaultMemoryMb()).thenReturn(128);
when(lambdaCfg.zipMaxEntries()).thenReturn(ZipExtractor.DEFAULT_MAX_ENTRIES);
when(lambdaCfg.executor()).thenReturn("docker");
when(sync.enabled()).thenReturn(enabled);
when(sync.async()).thenReturn(async);
return cfg;
}
private static void awaitLastUpdateStatus(LambdaService service, LambdaFunction fn, String expected)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (!expected.equals(service.lastUpdateStatus(fn)) && System.nanoTime() < deadline) {
Thread.sleep(10);
}
assertEquals(expected, service.lastUpdateStatus(fn));
}
@Test
void deletingOneVersionPreservesAnotherVersionAndLatest() throws Exception {
String name = "shared-version-code";
@@ -10,7 +10,7 @@ import java.util.Arrays;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** Code packages for tests that create Web Function revisions. */
/** Code packages for tests that deploy function code, Web Function revisions among them. */
public final class LambdaWebZips {
private LambdaWebZips() {
@@ -6,10 +6,11 @@ import java.util.Map;
/**
* Sets where a Lambda function's code may come from, for the classes that test it: foreign-account
* layer ARNs are accepted (recorded verbatim, never mounted), and hot-reload mounts are limited to
* an allow-list under {@code /home/ci/code}. Each setting only changes the requests its own class
* makes, so the two classes share this profile, and Quarkus builds one application for both
* rather than one each.
* layer ARNs are accepted (recorded verbatim, never mounted), hot-reload mounts are limited to an
* allow-list under {@code /home/ci/code}, and a reactive S3 sync re-deploys a function in the
* background rather than inside the upload of its code. Each setting only changes the requests its
* own class makes, so the three classes share this profile, and Quarkus builds one application for
* all of them rather than one each.
*/
public class LambdaCodeSourcesProfile implements QuarkusTestProfile {
@@ -17,6 +18,7 @@ public class LambdaCodeSourcesProfile implements QuarkusTestProfile {
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.lambda.accept-external-layer-arns", "true",
"floci.services.lambda.hot-reload.allowed-paths", "/home/ci/code");
"floci.services.lambda.hot-reload.allowed-paths", "/home/ci/code",
"floci.services.lambda.reactive-s3-sync.async", "true");
}
}