Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

TATSUNO “Taz” Yasuhiro83647aa05d13
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java
index 9fd76b910d..9caf50f15e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java
@@ -4,15 +4,14 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
-import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.FileTrees;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
+import io.github.hectorvent.floci.services.lambda.zip.DeploymentPackage;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import io.github.hectorvent.floci.services.s3.S3Service;
-import io.github.hectorvent.floci.services.s3.model.S3Object;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -137,61 +136,62 @@ public class LambdaLayerService {
? (List<String>) request.get("CompatibleArchitectures") : null;
// Resolve the zip content
- byte[] zipBytes = resolveLayerContent(content);
- if (content.get("ZipFile") != null
- && zipBytes.length > ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES) {
- throw new AwsException("RequestEntityTooLargeException",
- "Request must be smaller than 52428800 bytes.", 413);
- }
+ try (DeploymentPackage zip = resolveLayerContent(content, layersRoot())) {
+ if (content.get("ZipFile") != null
+ && zip.size() > ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES) {
+ throw new AwsException("RequestEntityTooLargeException",
+ "Request must be smaller than 52428800 bytes.", 413);
+ }
- String accountId = regionResolver.getAccountId();
+ String accountId = regionResolver.getAccountId();
- // Determine the next version number
- long nextVersion = layerStore.getLatestVersion(region, layerName) + 1;
+ // Determine the next version number
+ long nextVersion = layerStore.getLatestVersion(region, layerName) + 1;
- // Extract the layer zip to disk
- Path layerPath = getLayerCodePath(accountId, region, layerName, nextVersion);
- try {
- zipExtractor.extractTo(zipBytes, layerPath, configuredZipMaxEntries());
- } catch (IOException e) {
- throw new AwsException("InvalidParameterValueException",
- "Failed to extract layer archive: " + e.getMessage(), 400);
- }
-
- // Compute SHA-256
- String codeSha256 = computeSha256(zipBytes);
-
- // Build the layer version
- String layerArn = AwsArnUtils.Arn.of("lambda", region, accountId, "layer:" + layerName).toString();
- String layerVersionArn = layerArn + ":" + nextVersion;
-
- LambdaLayerVersion layerVersion = new LambdaLayerVersion();
- layerVersion.setLayerName(layerName);
- layerVersion.setLayerArn(layerArn);
- layerVersion.setLayerVersionArn(layerVersionArn);
- layerVersion.setVersion(nextVersion);
- layerVersion.setDescription(description);
- layerVersion.setLicenseInfo(licenseInfo);
- layerVersion.setCompatibleRuntimes(compatibleRuntimes != null ? new ArrayList<>(compatibleRuntimes) : null);
- layerVersion.setCompatibleArchitectures(compatibleArchitectures != null ? new ArrayList<>(compatibleArchitectures) : null);
- layerVersion.setCreatedDate(DateTimeFormatter.ISO_INSTANT.format(Instant.now().atOffset(ZoneOffset.UTC)));
- layerVersion.setCodeSizeBytes(zipBytes.length);
- layerVersion.setCodeSha256(codeSha256);
- layerVersion.setCodeLocalPath(layerPath.toAbsolutePath().normalize().toString());
-
- // Store the archive before persisting the version so a load-bearing store failure
- // (kubernetes executor) fails the publish instead of leaving a version pods cannot use.
- boolean stored = storeLayerArchive(region, accountId, layerName, nextVersion, zipBytes);
- if (!stored && LambdaService.requiresStoredTasksObject(config)) {
- throw new AwsException("ServiceException",
- "Could not store the layer archive for '" + layerName + "' v" + nextVersion
- + " in Floci's S3, which the kubernetes Lambda executor needs. The "
- + "layer version was not published.", 500);
- }
- layerVersion.setArchiveStored(stored);
- layerStore.save(region, layerVersion);
- LOG.infov("Published layer version: {0} v{1} in region {2}", layerName, nextVersion, region);
- return layerVersion;
+ // Extract the layer zip to disk
+ Path layerPath = getLayerCodePath(accountId, region, layerName, nextVersion);
+ try {
+ zip.extractTo(zipExtractor, layerPath, configuredZipMaxEntries(), null);
+ } catch (IOException e) {
+ throw new AwsException("InvalidParameterValueException",
+ "Failed to extract layer archive: " + e.getMessage(), 400);
+ }
+
+ // Compute SHA-256
+ String codeSha256 = zip.sha256();
+
+ // Build the layer version
+ String layerArn = AwsArnUtils.Arn.of("lambda", region, accountId, "layer:" + layerName).toString();
+ String layerVersionArn = layerArn + ":" + nextVersion;
+
+ LambdaLayerVersion layerVersion = new LambdaLayerVersion();
+ layerVersion.setLayerName(layerName);
+ layerVersion.setLayerArn(layerArn);
+ layerVersion.setLayerVersionArn(layerVersionArn);
+ layerVersion.setVersion(nextVersion);
+ layerVersion.setDescription(description);
+ layerVersion.setLicenseInfo(licenseInfo);
+ layerVersion.setCompatibleRuntimes(compatibleRuntimes != null ? new ArrayList<>(compatibleRuntimes) : null);
+ layerVersion.setCompatibleArchitectures(compatibleArchitectures != null ? new ArrayList<>(compatibleArchitectures) : null);
+ layerVersion.setCreatedDate(DateTimeFormatter.ISO_INSTANT.format(Instant.now().atOffset(ZoneOffset.UTC)));
+ layerVersion.setCodeSizeBytes(zip.size());
+ layerVersion.setCodeSha256(codeSha256);
+ layerVersion.setCodeLocalPath(layerPath.toAbsolutePath().normalize().toString());
+
+ // Store the archive before persisting the version so a load-bearing store failure
+ // (kubernetes executor) fails the publish instead of leaving a version pods cannot use.
+ boolean stored = storeLayerArchive(region, accountId, layerName, nextVersion, zip);
+ if (!stored && LambdaService.requiresStoredTasksObject(config)) {
+ throw new AwsException("ServiceException",
+ "Could not store the layer archive for '" + layerName + "' v" + nextVersion
+ + " in Floci's S3, which the kubernetes Lambda executor needs. The "
+ + "layer version was not published.", 500);
+ }
+ layerVersion.setArchiveStored(stored);
+ layerStore.save(region, layerVersion);
+ LOG.infov("Published layer version: {0} v{1} in region {2}", layerName, nextVersion, region);
+ return layerVersion;
+ }
}
private int configuredZipMaxEntries() {
@@ -210,9 +210,9 @@ public class LambdaLayerService {
* Best-effort unless the active Lambda executor requires stored tasks-bucket objects.
*/
private boolean storeLayerArchive(String region, String accountId, String layerName,
- long version, byte[] zipBytes) {
+ long version, DeploymentPackage zip) {
return LambdaService.putTasksObjectQuietly(s3Service, region,
- LambdaService.layerObjectKey(accountId, layerName, version), zipBytes,
+ LambdaService.layerObjectKey(accountId, layerName, version), zip,
"layer archive for " + layerName + " v" + version);
}
@@ -551,10 +551,10 @@ public class LambdaLayerService {
|| AwsArnUtils.isForeignAccount(arn, regionResolver.getAccountId());
}
- private byte[] resolveLayerContent(Map<String, Object> content) {
+ private DeploymentPackage resolveLayerContent(Map<String, Object> content, Path stagingDir) {
String zipFileBase64 = (String) content.get("ZipFile");
if (zipFileBase64 != null) {
- return Base64.getDecoder().decode(zipFileBase64);
+ return DeploymentPackage.of(Base64.getDecoder().decode(zipFileBase64));
}
String s3Bucket = (String) content.get("S3Bucket");
@@ -564,8 +564,7 @@ public class LambdaLayerService {
throw new AwsException("ServiceUnavailableException", "S3 service not available", 503);
}
try {
- S3Object obj = s3Service.getObject(s3Bucket, s3Key);
- return obj.getData();
+ return DeploymentPackage.read(s3Service.openObject(s3Bucket, s3Key, null), stagingDir);
} catch (Exception e) {
throw new AwsException("InvalidParameterValueException",
"Unable to fetch layer content from s3://" + s3Bucket + "/" + s3Key + ": " + e.getMessage(), 400);
@@ -576,6 +575,10 @@ public class LambdaLayerService {
"Layer content must include either ZipFile or S3Bucket/S3Key", 400);
}
+ private Path layersRoot() {
+ return Path.of(config.services().lambda().codePath()).resolve("layers");
+ }
+
private Path getLayerCodePath(String accountId, String region, String layerName, long version) {
return Path.of(config.services().lambda().codePath())
.resolve("layers")
@@ -591,10 +594,6 @@ public class LambdaLayerService {
return sanitized.isEmpty() || sanitized.chars().allMatch(c -> c == '.') ? "_" : sanitized;
}
- private String computeSha256(byte[] data) {
- return Base64.getEncoder().encodeToString(Digests.sha256(data));
- }
-
private void deleteDirectory(Path dir) {
try {
FileTrees.delete(dir);
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.java
index eb5bcf3ead..714d92a14a 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
@@ -11,7 +11,6 @@ import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
-import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
@@ -37,9 +36,9 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.model.LambdaUrlConfig;
import io.github.hectorvent.floci.services.lambda.model.ScalingConfig;
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
+import io.github.hectorvent.floci.services.lambda.zip.DeploymentPackage;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import io.github.hectorvent.floci.services.s3.S3Service;
-import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.s3.model.S3ObjectUpdatedEvent;
import io.github.hectorvent.floci.services.sqs.SqsService;
import jakarta.annotation.PostConstruct;
@@ -3434,25 +3433,25 @@ public class LambdaService implements ResourceProvider {
throw new AwsException("RequestEntityTooLargeException",
"Request must be smaller than 52428800 bytes.", 413);
}
- extractZipCodeBytes(fn, zipBytes, region);
+ extractZipCodePackage(fn, DeploymentPackage.of(zipBytes), region);
}
- private void extractZipCodeBytes(LambdaFunction fn, byte[] zipBytes, String region) {
+ private void extractZipCodePackage(LambdaFunction fn, DeploymentPackage zip, String region) {
Path codePath = codeStore.getCodePath(ownerAccount(fn), region, fn.getFunctionName());
try {
- zipExtractor.extractTo(zipBytes, codePath, configuredZipMaxEntries(),
- () -> storeDeploymentPackage(fn, zipBytes, region));
+ zip.extractTo(zipExtractor, codePath, configuredZipMaxEntries(),
+ () -> storeDeploymentPackage(fn, zip, region));
// Publish the new code identity under the same per-function lock publishVersion holds.
// PublishVersion's CodeSha256 precondition is a check-then-act: it compares the hash and
// then snapshots the code. Mutating these fields without the lock lets an overlapping
// deploy move $LATEST between those two steps, so a version would carry code whose hash
// the caller never authorised even though the check passed. UpdateFunctionCode and reactive
// sync hold this monitor across extraction; a new function is saved after extraction.
- String newSha256 = Base64.getEncoder().encodeToString(Digests.sha256(zipBytes));
+ String newSha256 = zip.sha256();
synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
fn.setCodeLocalPath(codePath.toAbsolutePath().normalize().toString());
fn.setHotReloadHostPath(null);
- fn.setCodeSizeBytes(zipBytes.length);
+ fn.setCodeSizeBytes(zip.size());
if (newSha256 != null) {
fn.setCodeSha256(newSha256);
}
@@ -3487,8 +3486,8 @@ public class LambdaService implements ResourceProvider {
return configured;
}
- private void storeDeploymentPackage(LambdaFunction fn, byte[] zipBytes, String region) {
- boolean stored = putTasksObjectQuietly(s3Service, region, codeObjectKey(fn), zipBytes,
+ private void storeDeploymentPackage(LambdaFunction fn, DeploymentPackage zip, String region) {
+ boolean stored = putTasksObjectQuietly(s3Service, region, codeObjectKey(fn), zip,
"deployment package for " + fn.getFunctionName());
if (!stored && requiresStoredTasksObject(config)) {
throw new AwsException("ServiceException",
@@ -3504,7 +3503,7 @@ public class LambdaService implements ResourceProvider {
* executor depends on it can fail loudly instead of silently succeeding.
*/
static boolean putTasksObjectQuietly(S3Service s3Service, String region, String key,
- byte[] zipBytes, String what) {
+ DeploymentPackage zip, String what) {
if (s3Service == null) {
return false;
}
@@ -3518,7 +3517,7 @@ public class LambdaService implements ResourceProvider {
throw e;
}
}
- s3Service.putObject(bucket, key, zipBytes, "application/zip", java.util.Map.of());
+ zip.putObject(s3Service, bucket, key, "application/zip");
return true;
} catch (Exception e) {
LOG.warnv("Could not store {0}: {1}", what, e.getMessage());
@@ -3541,18 +3540,27 @@ public class LambdaService implements ResourceProvider {
throw new AwsException("ServiceUnavailableException", "S3 service not available", 503);
}
- S3Object obj;
+ DeploymentPackage zip;
try {
- obj = s3Service.getObject(s3Bucket, s3Key);
+ zip = readS3Package(fn, s3Bucket, s3Key, region);
} catch (Exception e) {
throw new AwsException("InvalidParameterValueException",
"Unable to fetch code from s3://" + s3Bucket + "/" + s3Key + ": " + e.getMessage(), 400);
}
- extractZipCodeBytes(fn, obj.getData(), region);
+ try (zip) {
+ extractZipCodePackage(fn, zip, region);
+ }
fn.setS3Bucket(s3Bucket);
fn.setS3Key(s3Key);
}
+ /** Staged beside the function's code directory, where the extractor stages too. */
+ private DeploymentPackage readS3Package(LambdaFunction fn, String s3Bucket, String s3Key, String region)
+ throws IOException {
+ return DeploymentPackage.read(s3Service.openObject(s3Bucket, s3Key, null),
+ codeStore.getCodePath(ownerAccount(fn), region, fn.getFunctionName()).getParent());
+ }
+
private void applyHotReload(LambdaFunction fn, String hostPath) {
if (config == null || !config.services().lambda().hotReload().enabled()) {
throw new AwsException("InvalidParameterValueException",
@@ -4151,8 +4159,9 @@ public class LambdaService implements ResourceProvider {
LOG.infov("Reactive S3 Sync: updating function {0} from s3://{1}/{2}",
fn.getFunctionName(), event.bucketName(), event.key());
try {
- S3Object obj = s3Service.getObject(event.bucketName(), event.key());
- extractZipCodeBytes(fn, obj.getData(), region);
+ try (DeploymentPackage zip = readS3Package(fn, event.bucketName(), event.key(), region)) {
+ extractZipCodePackage(fn, zip, region);
+ }
fn.setLastModified(Instant.now().toEpochMilli());
fn.setRevisionId(UUID.randomUUID().toString());
functionStore.saveForAccount(ownerAccount(fn), region, fn);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/zip/DeploymentPackage.java b/src/main/java/io/github/hectorvent/floci/services/lambda/zip/DeploymentPackage.java
new file mode 100644
index 0000000000..61fa835370
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/zip/DeploymentPackage.java
@@ -0,0 +1,123 @@
+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 org.jboss.logging.Logger;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.DigestOutputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+import java.util.Map;
+
+/**
+ * A .zip package on its way to a function or layer: the bytes when they are already in memory,
+ * or a copy staged on disk so a package read from S3 is never held in the heap.
+ */
+public final class DeploymentPackage implements AutoCloseable {
+
+ private static final Logger LOG = Logger.getLogger(DeploymentPackage.class);
+
+ private final byte[] bytes;
+ private final Path file;
+ private final long size;
+ private final String sha256;
+
+ private DeploymentPackage(byte[] bytes, Path file, long size, String sha256) {
+ this.bytes = bytes;
+ this.file = file;
+ this.size = size;
+ this.sha256 = sha256;
+ }
+
+ public static DeploymentPackage of(byte[] bytes) {
+ return new DeploymentPackage(bytes, null, bytes.length,
+ Base64.getEncoder().encodeToString(Digests.sha256(bytes)));
+ }
+
+ /**
+ * Takes over {@code object} and closes it. S3 in memory mode already holds the bytes, and a
+ * tasks bucket copy put from them shares them, so they are kept as they are. Otherwise the body
+ * is staged in {@code stagingDir}, unless it is over the compressed limit extraction enforces.
+ */
+ public static DeploymentPackage read(S3Service.ObjectRead object, Path stagingDir) throws IOException {
+ try (object) {
+ byte[] held = object.object().getData();
+ if (held != null) {
+ return of(held);
+ }
+ long declared = object.object().getSize();
+ if (ZipExtractor.S3_MAX_COMPRESSED_BYTES < declared) {
+ return new DeploymentPackage(null, null, declared, null);
+ }
+ Files.createDirectories(stagingDir);
+ Path staged = Files.createTempFile(stagingDir, ".floci-staging-", ".zip");
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ long size;
+ try (OutputStream out = new DigestOutputStream(Files.newOutputStream(staged), digest)) {
+ size = object.body().transferTo(out);
+ }
+ return new DeploymentPackage(null, staged, size, Base64.getEncoder().encodeToString(digest.digest()));
+ } catch (IOException | RuntimeException e) {
+ Files.deleteIfExists(staged);
+ throw e;
+ } catch (NoSuchAlgorithmException e) {
+ Files.deleteIfExists(staged);
+ throw new IllegalStateException("SHA-256 is not available", e);
+ }
+ }
+ }
+
+ public long size() {
+ return size;
+ }
+
+ /** The base64 SHA-256 of the package, as Lambda reports it in {@code CodeSha256}. */
+ public String sha256() {
+ return sha256;
+ }
+
+ public void extractTo(ZipExtractor extractor, Path targetDir, int maxEntries, Runnable beforeInstall)
+ throws IOException {
+ if (file != null) {
+ extractor.extractTo(file, targetDir, maxEntries, beforeInstall);
+ } else if (bytes != null) {
+ extractor.extractTo(bytes, targetDir, maxEntries, beforeInstall);
+ } else {
+ // Over the compressed limit, so never staged: rejected with the message a staged copy would get.
+ ZipExtractor.checkLimits(maxEntries, size);
+ throw new IllegalStateException("A package of " + size + " bytes passed the compressed limit");
+ }
+ }
+
+ public void putObject(S3Service s3Service, String bucket, String key, String contentType) {
+ if (file == null) {
+ s3Service.putObject(bucket, key, bytes, contentType, Map.of());
+ return;
+ }
+ try (InputStream in = Files.newInputStream(file)) {
+ s3Service.putObjectFromStream(bucket, key, in, contentType, Map.of());
+ } catch (IOException e) {
+ throw new UncheckedIOException("Could not read the staged package " + file, e);
+ }
+ }
+
+ @Override
+ public void close() {
+ if (file == null) {
+ return;
+ }
+ try {
+ Files.deleteIfExists(file);
+ } catch (IOException e) {
+ LOG.warnv("Could not delete the staged package {0}: {1}", file, e.getMessage());
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractor.java b/src/main/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractor.java
index 1877ec1f15..8037938bda 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractor.java
@@ -29,7 +29,7 @@ public class ZipExtractor {
private static final char BACKSLASH = '\\';
public static final long DIRECT_UPLOAD_MAX_COMPRESSED_BYTES = 50L * 1024 * 1024;
- private static final long S3_MAX_COMPRESSED_BYTES = 250L * 1024 * 1024;
+ static final long S3_MAX_COMPRESSED_BYTES = 250L * 1024 * 1024;
static final long MAX_EXPANDED_BYTES = 250L * 1024 * 1024;
static final long MAX_ENTRY_BYTES = 250L * 1024 * 1024;
public static final int DEFAULT_MAX_ENTRIES = 100_000;
@@ -66,13 +66,17 @@ public class ZipExtractor {
/** For an archive already on disk, which is opened in place instead of read into the heap and staged. */
public void extractTo(Path zipFile, Path targetDir, int maxEntries) throws IOException {
+ extractTo(zipFile, targetDir, maxEntries, null);
+ }
+
+ public void extractTo(Path zipFile, Path targetDir, int maxEntries, Runnable beforeInstall) throws IOException {
checkLimits(maxEntries, Files.size(zipFile));
Path absTarget = targetDir.toAbsolutePath().normalize();
Files.createDirectories(absTarget.getParent());
- extract(zipFile, absTarget, maxEntries, null);
+ extract(zipFile, absTarget, maxEntries, beforeInstall);
}
- private static void checkLimits(int maxEntries, long compressedBytes) throws IOException {
+ static void checkLimits(int maxEntries, long compressedBytes) throws IOException {
if (maxEntries < 1) {
throw new IOException("ZIP archive entry limit must be at least 1: " + maxEntries);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
index 98727fdcee..7df106c47b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
@@ -680,6 +680,12 @@ public class S3Service implements Resettable, ResourceProvider {
return createObject(bucketName, key, data, contentType, metadata, options, "ObjectCreated:Put");
}
+ /** Like {@link #putObject(String, String, byte[], String, Map)}, with the body read from a stream. */
+ public S3Object putObjectFromStream(String bucketName, String key, InputStream body,
+ String contentType, Map<String, String> metadata) {
+ return putObject(bucketName, key, body, UploadChecksums.NONE, contentType, metadata, new PutObjectOptions());
+ }
+
/**
* Stores an object streamed from {@code body}, checked against {@code checksums}, without holding
* it in memory in the disk-backed modes. Everything the request alone decides is checked before
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
index 6f270f31a8..afeb489e1c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/zip/DeploymentPackageTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/zip/DeploymentPackageTest.java
new file mode 100644
index 0000000000..c7b8a28a68
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/zip/DeploymentPackageTest.java
@@ -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();
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractorTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractorTest.java
index 8db173e82a..7339cd6a4a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/zip/ZipExtractorTest.java
@@ -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));
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java
index f346d7e240..58f0d2eaed 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java
@@ -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");