feat(lambdaweb): fail a revision whose code is not a zip (#6141)

* feat(lambdaweb): fail a revision whose code is not a zip

A revision whose code is not a zip is Failed, as on AWS, and cannot be
deployed. The endpoint CreateWebFunction makes on such a revision is
Failed too and answers 409 Platform.EndpointNotActive. An empty object
is a 500 InternalServerException with an empty body, as on AWS.

* fix(lambdaweb): remove a code copy that cannot be read and name the {} body

* test(lambdaweb): upload a real zip in the compatibility tests
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-21 22:56:15 -04:00
1 parent 7c202a8966
commit 62972c91bf
21 files changed
+466 -33

No files matched your search

@@ -1,8 +1,10 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
@@ -37,7 +39,7 @@ class CloudFormationLambdaWebIntegrationTest {
@Test
void stackProvisionsFunctionRevisionAndEndpoint() {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-web-" + suffix;
String stackName = "cfn-web-stack-" + suffix;
@@ -99,6 +101,50 @@ class CloudFormationLambdaWebIntegrationTest {
.then().statusCode(404));
}
@Test
void aRevisionOnCodeThatIsNotAZipFailsItsResource() {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
s3Service.putObject(BUCKET, "notzip.zip", "this is not a zip\n".getBytes(StandardCharsets.UTF_8),
"application/zip", Map.of());
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-web-bad-" + suffix;
String stackName = "cfn-web-bad-stack-" + suffix;
String notZip = template(functionName, 30).replace("\"app.zip\"", "\"notzip.zip\"");
cloudFormation(stackName, "CreateStack", notZip);
await().untilAsserted(() -> describeStacks(stackName, "ROLLBACK_COMPLETE"));
stackEvents(stackName).body(containsString(
"<ResourceStatusReason>Failed to read zip file: zip: not a valid zip file</ResourceStatusReason>"));
given().when().get("/2025-03-07/web-functions/" + functionName).then().statusCode(404);
cloudFormation(stackName, "DeleteStack", null);
// A replacement on such code fails the update, and the rollback deletes it.
String updatedStack = stackName + "-update";
cloudFormation(updatedStack, "CreateStack", template(functionName, 30));
String revisionId = outputs(describeStacks(updatedStack, "CREATE_COMPLETE")).get("RevId");
cloudFormation(updatedStack, "UpdateStack", notZip);
await().untilAsserted(() -> describeStacks(updatedStack, "UPDATE_ROLLBACK_COMPLETE"));
given().contentType("application/json").body("{}")
.when().post("/2025-03-07/web-functions/" + functionName + "/list-revisions")
.then().statusCode(200)
.body("revisions", hasSize(1))
.body("revisions[0].revisionId", equalTo(revisionId));
cloudFormation(updatedStack, "DeleteStack", null);
await().untilAsserted(() -> given().when().get("/2025-03-07/web-functions/" + functionName)
.then().statusCode(404));
}
private static ValidatableResponse stackEvents(String stackName) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
}
/** A revision whose code object does not exist, created after the endpoint, so the update fails there. */
private static final String BAD_REVISION = """
"Bad": {
@@ -271,6 +271,20 @@ class LambdaWebCfnProvisionerTest {
assertEquals("The revision is active.", r.getAttributes().get("StateReason"));
}
@Test
void aFailedRevisionFailsTheResourceAndIsDeleted() {
WebFunctionRevision failed = revision("rev-aaaaa");
failed.failureReason = "Failed to read zip file: zip: not a valid zip file";
when(service.createRevision(eq(REGION), eq("app"), any())).thenReturn(failed);
StackResource r = resource(LambdaWebCfnProvisioner.REVISION);
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, revisionProps(), ctx(null)));
assertEquals("Failed to read zip file: zip: not a valid zip file", e.getMessage());
verify(service).deleteRevision(REGION, FN_ARN, failed.revisionArn);
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void unchangedRevisionIsKeptOnUpdate() {
WebFunctionRevision existing = revision("rev-aaaaa");
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
@@ -11,7 +12,6 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -83,7 +83,7 @@ class CloudFrontWebFunctionOriginServingTest {
static String createFunction(S3Service s3Service, PartitionCleanup cleanup, String functionName, String authType) {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
String domain = given().contentType("application/json")
.body("""
{"functionName": "%s",
@@ -94,6 +94,38 @@ class LambdaWebDataPlaneIntegrationTest {
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
@Test
void anEndpointCreatedOnAFailedRevisionIsNotActive() {
String functionName = "dp-failed-" + Long.toString(System.nanoTime(), 36);
String domain = createFunction(functionName, "ApplicationManaged",
"this is not a zip\n".getBytes(StandardCharsets.UTF_8));
Response response = given().header("Host", domain).when().get("/");
response.then().statusLine("HTTP/1.1 409 Conflict")
.header("content-type", "text/html")
.header("connection", "keep-alive")
.header("lambda-web-error-type", "Platform.EndpointNotActive")
.header("lambda-web-request-id", matchesPattern(REQUEST_ID))
.header("content-length", "225")
.body(equalTo(LambdaWebErrorPages.html(LambdaWebErrorPages.ENDPOINT_NOT_ACTIVE,
response.header("lambda-web-request-id"))));
given().header("Host", domain).when().head("/")
.then().statusCode(409)
.header("lambda-web-error-type", "Platform.EndpointNotActive")
.header("content-length", "225")
.body(equalTo(""));
Map<String, String> endpoint = Map.of("FunctionName", functionName, "EndpointName", "dev");
metrics.awaitPublished(Duration.ofSeconds(5));
assertEquals(2, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "HTTPResponseStatusClass4XX",
endpoint, "Sum"));
assertEquals(0, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "ExecutedRequests", endpoint, "Sum"));
given().when().delete(BASE + "/web-functions/" + functionName + "/endpoints/dev").then().statusCode(204);
given().header("Host", domain).when().get("/")
.then().statusCode(404).header("lambda-web-error-type", "Platform.InvalidEndpoint");
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
private static String readUntil(InputStream in, String end) throws IOException {
StringBuilder read = new StringBuilder();
while (!read.toString().endsWith(end)) {
@@ -246,8 +278,12 @@ class LambdaWebDataPlaneIntegrationTest {
}
private String createFunction(String functionName, String authType) {
return createFunction(functionName, authType, LambdaWebZips.indexJs(""));
}
private String createFunction(String functionName, String authType, byte[] code) {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, "app.zip", code, "application/zip", Map.of());
return given().contentType("application/json")
.body("""
{"functionName": "%s",
@@ -18,6 +18,7 @@ class LambdaWebErrorPagesTest {
assertEquals(230, length(LambdaWebErrorPages.FORBIDDEN));
assertEquals(225, length(LambdaWebErrorPages.INVALID_ENDPOINT));
assertEquals(264, length(LambdaWebErrorPages.UNSUPPORTED_HTTP_VERSION));
assertEquals(225, length(LambdaWebErrorPages.ENDPOINT_NOT_ACTIVE));
assertEquals(274, length(LambdaWebErrorPages.ENDPOINT_DISABLED));
assertEquals(249, length(LambdaWebErrorPages.REQUEST_TIMEOUT));
assertEquals(236, length(LambdaWebErrorPages.ORIGIN_REQUEST_ERROR));
@@ -52,7 +52,7 @@ class LambdaWebIntegrationTest {
@BeforeAll
void seedCode() {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, KEY, "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
s3Service.putObject(BUCKET, KEY, LambdaWebZips.indexJs(""), "application/zip", Map.of());
}
@Test
@@ -584,4 +584,83 @@ class LambdaWebIntegrationTest {
.then().statusCode(200)
.body("accountUsage.functionCount", equalTo(0));
}
@Test
@Order(11)
void codeThatIsNotAZipFailsTheRevisionAndItsEndpoint() {
String fn = FN + "-failed";
s3Service.putObject(BUCKET, "notzip.zip", "this is not a zip\n".getBytes(StandardCharsets.UTF_8),
"application/zip", Map.of());
s3Service.putObject(BUCKET, "empty.zip", new byte[0], "application/zip", Map.of());
String notZip = """
{"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "notzip.zip"}},
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "%s"}}
""".formatted(BUCKET, ROLE);
String failed = given().contentType("application/json")
.body("""
{"functionName": "%s", "revisionConfig": %s,
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
"authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}
""".formatted(fn, notZip))
.when().put(BASE + "/web-functions")
.then().statusCode(202)
.body("revision.state", equalTo("Pending"))
.body("endpoint.state", equalTo("Pending"))
.extract().path("revision.revisionId");
String reason = "Failed to read zip file: zip: not a valid zip file";
given().when().get(BASE + "/web-functions/" + fn).then().statusCode(200).body("state", equalTo("Active"));
given().when().get(BASE + "/web-functions/" + fn + "/revisions/" + failed)
.then().statusCode(200)
.body("state", equalTo("Failed"))
.body("stateReason", equalTo(reason));
given().when().get(BASE + "/web-functions/" + fn + "/endpoints/dev")
.then().statusCode(200)
.body("state", equalTo("Failed"))
.body("stateReason", equalTo("The endpoint activation failed in [us-east-1]. The endpoint is not"
+ " invokable in any region. For details, see the stateReason for those regions in"
+ " regionalEndpoints. To retry, delete the endpoint and create it again."))
.body("updateStatus", nullValue())
.body("revisionWeights[0].revisionId", equalTo(failed))
.body("regionalEndpoints.us-east-1.state", equalTo("Failed"))
.body("regionalEndpoints.us-east-1.stateReason",
equalTo("The endpoint activation failed because of an internal error."))
.body("regionalEndpoints.us-east-1.updateStatus", nullValue());
String failedFilter = "{\"filters\": [{\"name\": \"state\", \"values\": [\"Failed\"]}]}";
given().contentType("application/json").body(failedFilter)
.when().post(BASE + "/web-functions/" + fn + "/list-revisions")
.then().statusCode(200)
.body("revisions", hasSize(1))
.body("revisions[0].state", equalTo("Failed"))
.body("revisions[0].stateReason", equalTo(reason));
given().contentType("application/json").body(failedFilter)
.when().post(BASE + "/web-functions/" + fn + "/list-endpoints")
.then().statusCode(200)
.body("endpoints", hasSize(1))
.body("endpoints[0].state", equalTo("Failed"));
given().contentType("application/json").body("{\"description\": \"retry\"}")
.when().patch(BASE + "/web-functions/" + fn + "/endpoints/dev")
.then().statusCode(409)
.header("X-Amzn-Errortype", "ConflictException")
.body("message", equalTo("The endpoint dev is in Failed state. The operation is allowed only when"
+ " the endpoint is in Active state."));
given().contentType("application/json").body(notZip)
.when().post(BASE + "/web-functions/" + fn + "/revisions")
.then().statusCode(202)
.body("state", equalTo("Pending"));
// An empty object is an internal error with the body {}, as on AWS.
given().contentType("application/json").body(notZip.replace("notzip.zip", "empty.zip"))
.when().post(BASE + "/web-functions/" + fn + "/revisions")
.then().statusCode(500)
.header("X-Amzn-Errortype", "InternalServerException")
.body(equalTo("{}"));
given().contentType("application/json").body("{}")
.when().post(BASE + "/web-functions/" + fn + "/list-revisions")
.then().statusCode(200)
.body("revisions", hasSize(2));
given().when().delete(BASE + "/web-functions/" + fn).then().statusCode(204);
}
}
@@ -23,15 +23,19 @@ import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
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.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -46,6 +50,7 @@ class LambdaWebServiceTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String ARN = "arn:aws:lambda:us-east-1:000000000000:web-function/app";
private static final String ROLE = "arn:aws:iam::000000000000:role/web";
private static final byte[] NOT_A_ZIP = "this is not a zip\n".getBytes(StandardCharsets.UTF_8);
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
@@ -603,13 +608,15 @@ class LambdaWebServiceTest {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
LambdaWebCode code = new LambdaWebCode(storageDir.resolve("code"));
when(s3.openObject("code", "app.zip", null)).thenReturn(object("first"));
byte[] v1 = LambdaWebZips.indexJs("v1");
byte[] v2 = LambdaWebZips.indexJs("v2");
when(s3.openObject("code", "app.zip", null)).thenReturn(object(v1));
String first = service.createFunction(REGION, createRequest("app")).revisions.keySet().iterator().next();
when(s3.openObject("code", "app.zip", null)).thenReturn(object("second"));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(v2));
String second = service.createRevision(REGION, "app", revisionConfig(30)).revisionId;
assertEquals("first", Files.readString(code.file(ACCOUNT_ID, REGION, "app", first)));
assertEquals("second", Files.readString(code.file(ACCOUNT_ID, REGION, "app", second)));
assertArrayEquals(v1, Files.readAllBytes(code.file(ACCOUNT_ID, REGION, "app", first)));
assertArrayEquals(v2, Files.readAllBytes(code.file(ACCOUNT_ID, REGION, "app", second)));
service.deleteRevision(REGION, "app", first);
assertFalse(Files.exists(code.file(ACCOUNT_ID, REGION, "app", first)));
service.deleteFunction(REGION, "app");
@@ -619,7 +626,8 @@ class LambdaWebServiceTest {
@Test
void aStartKeepsOnlyTheCopiesOfStoredRevisions() throws IOException {
S3Service s3 = mock(S3Service.class);
when(s3.openObject("code", "app.zip", null)).thenReturn(object("code"));
byte[] zip = LambdaWebZips.indexJs("code");
when(s3.openObject("code", "app.zip", null)).thenReturn(object(zip));
FileStorageFactory storage = new FileStorageFactory(storageDir);
String revisionId = service(storage, "http://localhost:4566", s3).createFunction(REGION, createRequest("app"))
.revisions.keySet().iterator().next();
@@ -627,7 +635,7 @@ class LambdaWebServiceTest {
code.store(ACCOUNT_ID, REGION, "app", "rev-stray", new ByteArrayInputStream(new byte[] {1}));
service(new FileStorageFactory(storageDir), "http://localhost:4566", s3);
assertEquals("code", Files.readString(code.file(ACCOUNT_ID, REGION, "app", revisionId)));
assertArrayEquals(zip, Files.readAllBytes(code.file(ACCOUNT_ID, REGION, "app", revisionId)));
assertFalse(Files.exists(code.file(ACCOUNT_ID, REGION, "app", "rev-stray")));
service(new MemoryStorageFactory(), "http://localhost:4566", s3);
@@ -644,6 +652,16 @@ class LambdaWebServiceTest {
assertEquals(2, Files.readAllBytes(code.file(ACCOUNT_ID, "_", "app", "rev-aaaaa"))[0]);
}
@Test
void aCopyThatCannotBeReadIsRemoved() throws IOException {
LambdaWebCode code = new LambdaWebCode(storageDir.resolve("code"));
Path copy = code.file(ACCOUNT_ID, REGION, "app", "rev-aaaaa");
Files.createDirectories(copy);
assertThrows(UncheckedIOException.class, () -> code.opensAsZip(ACCOUNT_ID, REGION, "app", "rev-aaaaa"));
assertFalse(Files.exists(copy));
}
@Test
void aVersionThatCannotBeReadIsNamedInTheError() {
S3Service s3 = mock(S3Service.class);
@@ -667,8 +685,110 @@ class LambdaWebServiceTest {
message(() -> service.createFunction(REGION, createRequest("app"))));
}
private static S3Service.ObjectRead object(String data) {
byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
@Test
void aRevisionWhoseCodeIsNotAZipIsFailedAndCannotBeDeployed() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaWebZips.indexJs("v1")));
String good = service.createFunction(REGION, createRequest("app")).revisions.keySet().iterator().next();
when(s3.openObject("code", "app.zip", null)).thenReturn(object(NOT_A_ZIP));
WebFunctionRevision bad = service.createRevision(REGION, "app", revisionConfig(30));
assertEquals("Failed to read zip file: zip: not a valid zip file", bad.failureReason);
assertFalse(Files.exists(new LambdaWebCode(storageDir.resolve("code")).file(ACCOUNT_ID, REGION, "app",
bad.revisionId)));
assertEquals(good, service.getEndpoint(REGION, "app", "dev").revisionWeights.get(0).revisionId,
"a LatestRevision endpoint stays on its revision");
assertEquals(List.of(bad.revisionId), service.listRevisions(REGION, "app", stateFilter("Failed")).items()
.stream().map(r -> r.revisionId).toList());
String refusal = "The revision " + bad.revisionId + " is in Failed state and cannot be deployed."
+ " Only revisions in Active state can be deployed.";
ObjectNode toBad = mapper.createObjectNode().put("autoDeploymentMode", "Disabled");
toBad.putArray("revisionWeights").addObject().put("revisionId", bad.revisionId).put("weight", 100);
AwsException update = error(() -> service.updateEndpoint(REGION, "app", "dev", toBad));
assertEquals("ConflictException", update.getErrorCode());
assertEquals(409, update.getHttpStatus());
assertEquals(refusal, update.getMessage());
assertEquals(good, service.getEndpoint(REGION, "app", "dev").revisionWeights.get(0).revisionId);
ObjectNode weighted = endpointConfig("web").put("autoDeploymentMode", "Disabled");
weighted.set("revisionWeights", toBad.get("revisionWeights"));
assertEquals(refusal, message(() -> service.createEndpoint(REGION, "app", weighted)));
String latestRefusal = "The latest revision " + bad.revisionId + " is in Failed state and cannot be deployed."
+ " Only revisions in Active state can be deployed. Create a new revision.";
ObjectNode disabled = mapper.createObjectNode().put("autoDeploymentMode", "Disabled");
disabled.putArray("revisionWeights").addObject().put("revisionId", good).put("weight", 100);
service.updateEndpoint(REGION, "app", "dev", disabled);
assertEquals(latestRefusal, message(() -> service.updateEndpoint(REGION, "app", "dev",
mapper.createObjectNode().put("autoDeploymentMode", "LatestRevision"))));
assertEquals(latestRefusal, message(() -> service.createEndpoint(REGION, "app", endpointConfig("auto"))));
service.deleteRevision(REGION, "app", bad.revisionId);
assertEquals(List.of(good), List.copyOf(service.getFunction(REGION, "app").revisions.keySet()));
}
@Test
void aFunctionCreatedOnCodeThatIsNotAZipHasAFailedEndpoint() {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(NOT_A_ZIP));
service.createFunction(REGION, createRequest("app"));
WebFunctionEndpoint dev = service.getEndpoint(REGION, "app", "dev");
assertTrue(dev.failed);
String bad = dev.revisionWeights.get(0).revisionId;
assertNotNull(service.getRevision(REGION, "app", bad).failureReason);
AwsException update = error(() -> service.updateEndpoint(REGION, "app", "dev",
mapper.createObjectNode().put("description", "retry")));
assertEquals("ConflictException", update.getErrorCode());
assertEquals("The endpoint dev is in Failed state. The operation is allowed only when the endpoint is in"
+ " Active state.", update.getMessage());
// A good revision still moves the endpoint's weights, and the endpoint stays Failed, as on AWS.
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaWebZips.indexJs("v2")));
String good = service.createRevision(REGION, "app", revisionConfig(30)).revisionId;
dev = service.getEndpoint(REGION, "app", "dev");
assertEquals(good, dev.revisionWeights.get(0).revisionId);
assertTrue(dev.failed);
assertEquals(1, service.listEndpoints(REGION, "app", stateFilter("Failed")).items().size());
assertTrue(service.listEndpoints(REGION, "app", stateFilter("Active")).items().isEmpty());
service.deleteRevision(REGION, "app", bad);
service.deleteEndpoint(REGION, "app", "dev");
}
@Test
void anEmptyObjectIsAnInternalErrorThatCreatesNoRevision() throws IOException {
S3Service s3 = mock(S3Service.class);
LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", s3);
when(s3.openObject("code", "app.zip", null)).thenReturn(object(new byte[0]));
AwsException create = error(() -> service.createFunction(REGION, createRequest("app")));
assertInstanceOf(LambdaWebInternalServerException.class, create);
assertEquals("InternalServerException", create.getErrorCode());
assertEquals(500, create.getHttpStatus());
assertEquals("The function arn:aws:lambda:us-east-1:000000000000:web-function/app does not exist.",
message(() -> service.getFunction(REGION, "app")));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(LambdaWebZips.indexJs("v1")));
service.createFunction(REGION, createRequest("app"));
when(s3.openObject("code", "app.zip", null)).thenReturn(object(new byte[0]));
assertInstanceOf(LambdaWebInternalServerException.class,
error(() -> service.createRevision(REGION, "app", revisionConfig(30))));
assertEquals(1, service.getFunction(REGION, "app").revisions.size());
try (Stream<Path> copies = Files.walk(storageDir.resolve("code"))) {
assertEquals(1, copies.filter(Files::isRegularFile).count());
}
}
private ObjectNode stateFilter(String state) {
ObjectNode request = mapper.createObjectNode();
request.putArray("filters").addObject().put("name", "state").putArray("values").add(state);
return request;
}
private static S3Service.ObjectRead object(byte[] bytes) {
return new S3Service.ObjectRead(new S3Object("code", "app.zip", bytes, "application/zip"),
new ByteArrayInputStream(bytes));
}
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.lambdaweb;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** Code packages for tests that create Web Function revisions. */
public final class LambdaWebZips {
private LambdaWebZips() {
}
public static byte[] indexJs(String source) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(source.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bytes.toByteArray();
}
}