perf(lambda): stream S3 code to disk instead of holding it in memory (#6126)

* perf(lambda): stream S3 code to disk instead of holding it in memory

CreateFunction, UpdateFunctionCode, the reactive S3 sync and PublishLayerVersion read a package from S3 through openObject. When S3 keeps bodies on disk, the package is staged in the code store with its SHA-256 worked out on the way, unpacked from that file, and put into the tasks bucket from it. When S3 keeps bodies in memory, the bytes it already holds are used as before, so the tasks bucket copy still shares them.

* perf(lambda): reject an oversized S3 package before staging it

A package whose declared size is over the 250 MiB compressed limit is not copied to disk. Extraction rejects it with the message a staged copy gets.

* test(lambda): share the S3-backed service setup and the zip helper
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-21 09:23:02 -04:00
1 parent fbf3bfff84
commit 83647aa05d
9 files changed
+399 -96

No files matched your search

@@ -21,6 +21,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -2290,26 +2291,53 @@ class LambdaServiceTest {
}
@Test
void reactiveSyncHoldsThePublicationLockThroughExtraction() throws Exception {
void anS3PackageOverTheCompressedLimitGetsTheExtractionError() {
S3Service s3 = mock(S3Service.class);
WarmPool warmPool = mock(WarmPool.class);
ZipExtractor extractor = spy(new ZipExtractor());
LambdaService s3Backed = s3BackedService(s3, mock(WarmPool.class), new ZipExtractor());
long size = 250L * 1024 * 1024 + 1;
when(s3.openObject("code-bucket", "function.zip", null)).thenReturn(new S3Service.ObjectRead(
new S3Object("code-bucket", "function.zip", size, "application/zip", "\"etag\""),
new ByteArrayInputStream(new byte[0])));
Map<String, Object> request = baseRequest("oversized-" + UUID.randomUUID());
request.put("Code", Map.of("S3Bucket", "code-bucket", "S3Key", "function.zip"));
AwsException e = assertThrows(AwsException.class, () -> s3Backed.createFunction(REGION, request));
assertEquals("InvalidParameterValueException", e.getErrorCode());
assertEquals("Failed to extract deployment package: ZIP archive exceeds the 262144000 byte compressed limit: "
+ size, e.getMessage());
}
private static LambdaService s3BackedService(S3Service s3, WarmPool warmPool, ZipExtractor extractor) {
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);
LambdaService syncingService = new LambdaService(functionStore, null, new LambdaConcurrencyLimiter(),
return new LambdaService(functionStore, null, new LambdaConcurrencyLimiter(),
warmPool, new CodeStore(Path.of("target/test-data/lambda-code")), extractor, null,
new RegionResolver(REGION, "000000000000"), null, aliasStore,
new LambdaTargetResolver(functionStore, aliasStore), s3, null, null, null, null,
storageFactory, null, null, null, null, new ObjectMapper());
}
/** What S3 in memory mode returns: the body is already in the heap. */
private static S3Service.ObjectRead heldObject(String zipBase64) {
byte[] data = Base64.getDecoder().decode(zipBase64);
return new S3Service.ObjectRead(new S3Object("code-bucket", "function.zip", data, "application/zip"),
new ByteArrayInputStream(data));
}
@Test
void reactiveSyncHoldsThePublicationLockThroughExtraction() throws Exception {
S3Service s3 = mock(S3Service.class);
WarmPool warmPool = mock(WarmPool.class);
ZipExtractor extractor = spy(new ZipExtractor());
LambdaService syncingService = s3BackedService(s3, warmPool, extractor);
String name = "reactive-snapshot-" + UUID.randomUUID();
when(s3.getObject("code-bucket", "function.zip"))
.thenReturn(new S3Object("code-bucket", "function.zip",
Base64.getDecoder().decode(zipWithBody("v1")), "application/zip"))
.thenReturn(new S3Object("code-bucket", "function.zip",
Base64.getDecoder().decode(zipWithBody("v2")), "application/zip"));
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);
@@ -0,0 +1,113 @@
package io.github.hectorvent.floci.services.lambda.zip;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class DeploymentPackageTest {
@TempDir
Path dir;
@Test
void aBodyS3HoldsInMemoryIsKeptAsItIs() throws IOException {
byte[] zip = ZipExtractorTest.zipWith("index.js", "v1");
S3Service s3 = mock(S3Service.class);
Path staging = dir.resolve("staging");
try (DeploymentPackage pkg = DeploymentPackage.read(object(zip, zip), staging)) {
assertEquals(zip.length, pkg.size());
assertEquals(Base64.getEncoder().encodeToString(Digests.sha256(zip)), pkg.sha256());
pkg.putObject(s3, "tasks", "code.zip", "application/zip");
}
assertFalse(Files.exists(staging));
verify(s3).putObject("tasks", "code.zip", zip, "application/zip", Map.of());
}
@Test
void aBodyOnDiskIsStagedAndRemovedOnClose() throws IOException {
byte[] zip = ZipExtractorTest.zipWith("index.js", "v1");
S3Service s3 = mock(S3Service.class);
ByteArrayOutputStream stored = new ByteArrayOutputStream();
doAnswer(inv -> {
inv.<InputStream>getArgument(2).transferTo(stored);
return null;
}).when(s3).putObjectFromStream(eq("tasks"), eq("code.zip"), any(InputStream.class), eq("application/zip"),
eq(Map.of()));
Path staging = dir.resolve("staging");
Path target = dir.resolve("code");
try (DeploymentPackage pkg = DeploymentPackage.read(object(null, zip), staging)) {
assertEquals(zip.length, pkg.size());
assertEquals(Base64.getEncoder().encodeToString(Digests.sha256(zip)), pkg.sha256());
assertEquals(1, entries(staging).size());
pkg.extractTo(new ZipExtractor(), target, ZipExtractor.DEFAULT_MAX_ENTRIES, null);
pkg.putObject(s3, "tasks", "code.zip", "application/zip");
}
assertEquals("v1", Files.readString(target.resolve("index.js")));
assertArrayEquals(zip, stored.toByteArray());
assertEquals(List.of(), entries(staging));
}
@Test
void aBodyOverTheCompressedLimitIsRejectedUnread() throws IOException {
long size = ZipExtractor.S3_MAX_COMPRESSED_BYTES + 1;
InputStream unread = new InputStream() {
@Override
public int read() {
throw new AssertionError("the body was read");
}
};
S3Service.ObjectRead object = new S3Service.ObjectRead(
new S3Object("code", "app.zip", size, "application/zip", "\"etag\""), unread);
Path staging = dir.resolve("staging");
try (DeploymentPackage pkg = DeploymentPackage.read(object, staging)) {
IOException e = assertThrows(IOException.class, () -> pkg.extractTo(new ZipExtractor(),
dir.resolve("code"), ZipExtractor.DEFAULT_MAX_ENTRIES, () -> fail("installed")));
assertEquals("ZIP archive exceeds the 262144000 byte compressed limit: 262144001", e.getMessage());
}
assertFalse(Files.exists(staging));
assertFalse(Files.exists(dir.resolve("code")));
}
private static S3Service.ObjectRead object(byte[] held, byte[] body) {
S3Object metadata = held != null
? new S3Object("code", "app.zip", held, "application/zip")
: new S3Object("code", "app.zip", body.length, "application/zip", S3Object.computeETag(body));
return new S3Service.ObjectRead(metadata, new ByteArrayInputStream(body));
}
private static List<Path> entries(Path dir) throws IOException {
try (Stream<Path> entries = Files.list(dir)) {
return entries.toList();
}
}
}
@@ -36,7 +36,7 @@ class ZipExtractorTest {
}
/** Build a ZIP whose entry names use the given separator, as PowerShell does. */
private static byte[] zipWith(String entryName, String content) throws IOException {
static byte[] zipWith(String entryName, String content) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry(entryName));
@@ -24,6 +24,7 @@ import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
@@ -571,6 +572,26 @@ class S3ServiceTest {
assertEquals(stored.getETag(), head.getETag());
}
@Test
void putObjectFromStreamStoresWhatAByteArrayPutStores() {
s3Service.createBucket("test-bucket", "us-east-1");
byte[] body = "payload".getBytes(StandardCharsets.UTF_8);
S3Object bytes = s3Service.putObject("test-bucket", "bytes", body, "application/zip", Map.of());
s3Service.putObjectFromStream("test-bucket", "streamed", new ByteArrayInputStream(body), "application/zip",
Map.of());
S3Object head = s3Service.headObject("test-bucket", "streamed");
assertEquals(bytes.getETag(), head.getETag());
assertEquals(bytes.getSize(), head.getSize());
assertEquals("application/zip", head.getContentType());
assertEquals(Map.of(), head.getMetadata());
assertEquals(bytes.getStorageClass(), head.getStorageClass());
assertEquals(bytes.getChecksum().getChecksumCRC64NVME(), head.getChecksum().getChecksumCRC64NVME());
assertEquals(ChecksumType.FULL_OBJECT, head.getChecksum().getChecksumType());
assertArrayEquals(body, s3Service.getObject("test-bucket", "streamed").getData());
}
@Test
void getObjectAttributesReturnsRequestedFields() {
s3Service.createBucket("test-bucket", "us-east-1");