Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambda): support ImageConfig Command and EntryPoint for Image (#630)
Yoríe3368e014c63
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.javaindex 5c46eef777..f302f45640 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java@@ -508,6 +508,17 @@ public class LambdaController {node.put("CodeSha256", fn.getCodeSha256() != null ? fn.getCodeSha256() : "");node.put("PackageType", fn.getPackageType());if (fn.getImageUri() != null) node.put("ImageUri", fn.getImageUri());+ if ("Image".equals(fn.getPackageType())) {+ ObjectNode imageConfig = node.putObject("ImageConfigResponse").putObject("ImageConfig");+ if (fn.getImageConfigCommand() != null && !fn.getImageConfigCommand().isEmpty()) {+ ArrayNode cmdNode = imageConfig.putArray("Command");+ fn.getImageConfigCommand().forEach(cmdNode::add);+ }+ if (fn.getImageConfigEntryPoint() != null && !fn.getImageConfigEntryPoint().isEmpty()) {+ ArrayNode epNode = imageConfig.putArray("EntryPoint");+ fn.getImageConfigEntryPoint().forEach(epNode::add);+ }+ }node.put("LastModified", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(Instant.ofEpochMilli(fn.getLastModified()).atOffset(ZoneOffset.UTC)));node.put("RevisionId", fn.getRevisionId());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 dde5cae74e..b8e2b774cf 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@@ -284,6 +284,18 @@ public class LambdaService {fn.setVpcConfig(vpc);}+ // ImageConfig (PackageType=Image overrides)+ if (request.get("ImageConfig") instanceof Map<?, ?> ic) {+ @SuppressWarnings("unchecked")+ Map<String, Object> imageConfig = (Map<String, Object>) ic;+ if (imageConfig.get("Command") instanceof List<?> cmd) {+ fn.setImageConfigCommand(cmd.stream().map(Object::toString).toList());+ }+ if (imageConfig.get("EntryPoint") instanceof List<?> ep) {+ fn.setImageConfigEntryPoint(ep.stream().map(Object::toString).toList());+ }+ }+// Handle code deployment@SuppressWarnings("unchecked")Map<String, Object> code = (Map<String, Object>) request.get("Code");@@ -479,6 +491,25 @@ public class LambdaService {}}+ if (request.containsKey("ImageConfig")) {+ if (request.get("ImageConfig") instanceof Map<?, ?> ic) {+ @SuppressWarnings("unchecked")+ Map<String, Object> imageConfig = (Map<String, Object>) ic;+ if (imageConfig.containsKey("Command")) {+ @SuppressWarnings("unchecked")+ List<String> cmd = imageConfig.get("Command") instanceof List<?>+ ? ((List<?>) imageConfig.get("Command")).stream().map(Object::toString).toList() : null;+ fn.setImageConfigCommand(cmd);+ }+ if (imageConfig.containsKey("EntryPoint")) {+ @SuppressWarnings("unchecked")+ List<String> ep = imageConfig.get("EntryPoint") instanceof List<?>+ ? ((List<?>) imageConfig.get("EntryPoint")).stream().map(Object::toString).toList() : null;+ fn.setImageConfigEntryPoint(ep);+ }+ }+ }+fn.setLastModified(System.currentTimeMillis());fn.setRevisionId(UUID.randomUUID().toString());diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.javaindex b6d4695c00..e1535cfe21 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java@@ -169,8 +169,15 @@ public class ContainerLauncher {specBuilder.withBind(fn.getHotReloadHostPath(), TASK_DIR);}- // For Image package type without an explicit handler, omit CMD so the image's own CMD is used- if (fn.getHandler() != null && !fn.getHandler().isBlank()) {+ // For Image package type use ImageConfig.Command if set, otherwise fall back to Handler (Zip-style)+ if ("Image".equals(fn.getPackageType())) {+ if (fn.getImageConfigEntryPoint() != null && !fn.getImageConfigEntryPoint().isEmpty()) {+ specBuilder.withEntrypoint(fn.getImageConfigEntryPoint());+ }+ if (fn.getImageConfigCommand() != null && !fn.getImageConfigCommand().isEmpty()) {+ specBuilder.withCmd(fn.getImageConfigCommand());+ }+ } else if (fn.getHandler() != null && !fn.getHandler().isBlank()) {specBuilder.withCmd(fn.getHandler());}diff --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 1c3bd5b954..e315c24449 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@@ -27,6 +27,8 @@ public class LambdaFunction {private long codeSizeBytes;private String packageType = "Zip";private String imageUri;+ private List<String> imageConfigCommand;+ private List<String> imageConfigEntryPoint;private String codeLocalPath;private String s3Bucket;private String s3Key;@@ -98,6 +100,12 @@ public class LambdaFunction {public String getImageUri() { return imageUri; }public void setImageUri(String imageUri) { this.imageUri = imageUri; }+ public List<String> getImageConfigCommand() { return imageConfigCommand; }+ public void setImageConfigCommand(List<String> imageConfigCommand) { this.imageConfigCommand = imageConfigCommand; }++ public List<String> getImageConfigEntryPoint() { return imageConfigEntryPoint; }+ public void setImageConfigEntryPoint(List<String> imageConfigEntryPoint) { this.imageConfigEntryPoint = imageConfigEntryPoint; }+public String getCodeLocalPath() { return codeLocalPath; }public void setCodeLocalPath(String codeLocalPath) { this.codeLocalPath = codeLocalPath; }diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.javanew file mode 100644index 0000000000..9bca37fd64--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java@@ -0,0 +1,298 @@+package io.github.hectorvent.floci.services.lambda;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;+import io.github.hectorvent.floci.services.lambda.launcher.ContainerLauncher;+import io.github.hectorvent.floci.services.lambda.launcher.ImageResolver;+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;+import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;+import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory;+import io.github.hectorvent.floci.services.lambda.zip.CodeStore;+import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;+import com.github.dockerjava.api.DockerClient;+import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Nested;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import java.nio.file.Path;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;++import static org.junit.jupiter.api.Assertions.*;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.*;++class LambdaImageConfigTest {++ private static final String REGION = "us-east-1";++ private LambdaService service;++ @BeforeEach+ void setUp() {+ LambdaFunctionStore store = new LambdaFunctionStore(new InMemoryStorage<String, LambdaFunction>());+ WarmPool warmPool = new WarmPool();+ CodeStore codeStore = new CodeStore(Path.of("target/test-data/lambda-code"));+ RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");+ service = new LambdaService(store, warmPool, codeStore, new ZipExtractor(), regionResolver);+ }++ // -------------------------------------------------------------------------+ // LambdaService — createFunction+ // -------------------------------------------------------------------------++ @Nested+ class CreateFunction {++ @Test+ void storesImageConfigCommand() {+ Map<String, Object> req = imageRequest("fn-cmd");+ req.put("ImageConfig", Map.of("Command", List.of("app.handler")));++ LambdaFunction fn = service.createFunction(REGION, req);++ assertEquals(List.of("app.handler"), fn.getImageConfigCommand());+ assertNull(fn.getImageConfigEntryPoint());+ }++ @Test+ void storesImageConfigEntryPoint() {+ Map<String, Object> req = imageRequest("fn-ep");+ req.put("ImageConfig", Map.of("EntryPoint", List.of("/lambda-entrypoint.sh")));++ LambdaFunction fn = service.createFunction(REGION, req);++ assertEquals(List.of("/lambda-entrypoint.sh"), fn.getImageConfigEntryPoint());+ assertNull(fn.getImageConfigCommand());+ }++ @Test+ void storesCommandAndEntryPointTogether() {+ Map<String, Object> req = imageRequest("fn-both");+ req.put("ImageConfig", Map.of(+ "Command", List.of("app.handler"),+ "EntryPoint", List.of("/entry.sh")+ ));++ LambdaFunction fn = service.createFunction(REGION, req);++ assertEquals(List.of("app.handler"), fn.getImageConfigCommand());+ assertEquals(List.of("/entry.sh"), fn.getImageConfigEntryPoint());+ }++ @Test+ void noImageConfigLeavesFieldsNull() {+ LambdaFunction fn = service.createFunction(REGION, imageRequest("fn-none"));++ assertNull(fn.getImageConfigCommand());+ assertNull(fn.getImageConfigEntryPoint());+ }+ }++ // -------------------------------------------------------------------------+ // LambdaService — updateFunctionConfiguration+ // -------------------------------------------------------------------------++ @Nested+ class UpdateFunctionConfiguration {++ @Test+ void updatesImageConfigCommand() {+ service.createFunction(REGION, imageRequest("fn-upd-cmd"));++ Map<String, Object> update = new HashMap<>();+ update.put("ImageConfig", Map.of("Command", List.of("new.handler")));+ LambdaFunction fn = service.updateFunctionConfiguration(REGION, "fn-upd-cmd", update);++ assertEquals(List.of("new.handler"), fn.getImageConfigCommand());+ }++ @Test+ void updatesImageConfigEntryPoint() {+ service.createFunction(REGION, imageRequest("fn-upd-ep"));++ Map<String, Object> update = new HashMap<>();+ update.put("ImageConfig", Map.of("EntryPoint", List.of("/new-entry.sh")));+ LambdaFunction fn = service.updateFunctionConfiguration(REGION, "fn-upd-ep", update);++ assertEquals(List.of("/new-entry.sh"), fn.getImageConfigEntryPoint());+ }++ @Test+ void clearsCommandWhenEmptyListProvided() {+ Map<String, Object> req = imageRequest("fn-clear-cmd");+ req.put("ImageConfig", Map.of("Command", List.of("old.handler")));+ service.createFunction(REGION, req);++ Map<String, Object> update = new HashMap<>();+ update.put("ImageConfig", Map.of("Command", List.of()));+ LambdaFunction fn = service.updateFunctionConfiguration(REGION, "fn-clear-cmd", update);++ assertTrue(fn.getImageConfigCommand() == null || fn.getImageConfigCommand().isEmpty());+ }+ }++ // -------------------------------------------------------------------------+ // ContainerLauncher — ContainerSpec built for Image functions+ // -------------------------------------------------------------------------++ @Nested+ @ExtendWith(MockitoExtension.class)+ class ContainerLauncherImageConfig {++ @Mock ContainerLifecycleManager lifecycleManager;+ @Mock ContainerLogStreamer logStreamer;+ @Mock ImageResolver imageResolver;+ @Mock RuntimeApiServerFactory runtimeApiServerFactory;+ @Mock DockerHostResolver dockerHostResolver;+ @Mock EmulatorConfig config;+ @Mock EcrRegistryManager ecrRegistryManager;+ @Mock EmbeddedDnsServer embeddedDnsServer;+ @Mock RuntimeApiServer runtimeApiServer;+ @Mock DockerClient dockerClient;++ ContainerLauncher launcher;++ @BeforeEach+ void setUpLauncher() {+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);+ EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);++ when(config.services()).thenReturn(services);+ when(services.lambda()).thenReturn(lambda);+ when(lambda.dockerNetwork()).thenReturn(Optional.empty());+ when(config.docker()).thenReturn(docker);+ when(docker.logMaxSize()).thenReturn("10m");+ when(docker.logMaxFile()).thenReturn("3");+ when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());++ ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer);+ launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,+ runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager);++ when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);+ when(runtimeApiServer.getPort()).thenReturn(9000);+ when(dockerHostResolver.resolve()).thenReturn("127.0.0.1");+ when(lifecycleManager.create(any())).thenReturn("container-123");+ when(lifecycleManager.startCreated(eq("container-123"), any()))+ .thenReturn(new ContainerLifecycleManager.ContainerInfo("container-123", Map.of()));+ when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);++ lenient().when(dockerClient.copyArchiveToContainerCmd(any())).thenAnswer(inv -> {+ CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class);+ final java.io.InputStream[] captured = {null};+ when(cmd.withRemotePath(any())).thenReturn(cmd);+ when(cmd.withTarInputStream(any())).thenAnswer(streamInv -> {+ captured[0] = streamInv.getArgument(0);+ return cmd;+ });+ doAnswer(execInv -> {+ if (captured[0] != null) {+ try { captured[0].transferTo(java.io.OutputStream.nullOutputStream()); }+ catch (Exception ignored) {}+ }+ return null;+ }).when(cmd).exec();+ return cmd;+ });+ }++ @Test+ void usesImageConfigCommandAsCmdForImageFunction() throws Exception {+ LambdaFunction fn = imageFn("img-cmd-fn");+ fn.setImageConfigCommand(List.of("app.handler"));++ launcher.launch(fn);++ ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);+ verify(lifecycleManager).create(specCaptor.capture());++ ContainerSpec spec = specCaptor.getValue();+ assertEquals(List.of("app.handler"), spec.cmd());+ assertNull(spec.entrypoint());+ }++ @Test+ void usesImageConfigEntryPointForImageFunction() throws Exception {+ LambdaFunction fn = imageFn("img-ep-fn");+ fn.setImageConfigEntryPoint(List.of("/lambda-entrypoint.sh"));++ launcher.launch(fn);++ ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);+ verify(lifecycleManager).create(specCaptor.capture());++ ContainerSpec spec = specCaptor.getValue();+ assertEquals(List.of("/lambda-entrypoint.sh"), spec.entrypoint());+ }++ @Test+ void doesNotSetCmdWhenNoImageConfigCommand() throws Exception {+ LambdaFunction fn = imageFn("img-no-cmd-fn");++ launcher.launch(fn);++ ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);+ verify(lifecycleManager).create(specCaptor.capture());++ ContainerSpec spec = specCaptor.getValue();+ assertNull(spec.cmd(), "CMD should not be set when ImageConfig.Command is absent");+ assertNull(spec.entrypoint());+ }++ @Test+ void zipFunctionStillUsesHandlerAsCmd() throws Exception {+ LambdaFunction fn = new LambdaFunction();+ fn.setFunctionName("zip-fn");+ fn.setRuntime("nodejs20.x");+ fn.setHandler("index.handler");+ fn.setPackageType("Zip");+ when(imageResolver.resolve("nodejs20.x")).thenReturn("public.ecr.aws/lambda/nodejs:20");++ launcher.launch(fn);++ ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);+ verify(lifecycleManager).create(specCaptor.capture());++ assertEquals(List.of("index.handler"), specCaptor.getValue().cmd());+ }++ private LambdaFunction imageFn(String name) {+ LambdaFunction fn = new LambdaFunction();+ fn.setFunctionName(name);+ fn.setPackageType("Image");+ fn.setImageUri("localhost/my-image:latest");+ return fn;+ }+ }++ // -------------------------------------------------------------------------+ // Helpers+ // -------------------------------------------------------------------------++ private Map<String, Object> imageRequest(String name) {+ Map<String, Object> req = new HashMap<>();+ req.put("FunctionName", name);+ req.put("PackageType", "Image");+ req.put("Role", "arn:aws:iam::000000000000:role/test-role");+ req.put("Code", Map.of("ImageUri", "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:latest"));+ return req;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.javaindex 3a04b6963c..a41a1d3ff7 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.java@@ -278,4 +278,78 @@ class LambdaIntegrationTest {// cleanupgiven().delete(BASE_PATH + "/functions/large-zip-fn");}++ // ── ImageConfig ───────────────────────────────────────────────────────────++ @Test+ @Order(20)+ void createImageFunctionWithImageConfig() {+ given()+ .contentType("application/json")+ .body("""+ {+ "FunctionName": "image-fn",+ "PackageType": "Image",+ "Role": "arn:aws:iam::000000000000:role/lambda-role",+ "Code": {+ "ImageUri": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:latest"+ },+ "ImageConfig": {+ "Command": ["app.handler"],+ "EntryPoint": ["/lambda-entrypoint.sh"]+ }+ }+ """)+ .when()+ .post(BASE_PATH + "/functions")+ .then()+ .statusCode(201)+ .body("FunctionName", equalTo("image-fn"))+ .body("PackageType", equalTo("Image"))+ .body("ImageConfigResponse.ImageConfig.Command", hasItem("app.handler"))+ .body("ImageConfigResponse.ImageConfig.EntryPoint", hasItem("/lambda-entrypoint.sh"));+ }++ @Test+ @Order(21)+ void getFunctionReturnsImageConfig() {+ given()+ .when()+ .get(BASE_PATH + "/functions/image-fn")+ .then()+ .statusCode(200)+ .body("Configuration.ImageConfigResponse.ImageConfig.Command",+ hasItem("app.handler"))+ .body("Configuration.ImageConfigResponse.ImageConfig.EntryPoint",+ hasItem("/lambda-entrypoint.sh"));+ }++ @Test+ @Order(22)+ void updateImageFunctionConfig() {+ given()+ .contentType("application/json")+ .body("""+ {+ "ImageConfig": {+ "Command": ["new.handler"]+ }+ }+ """)+ .when()+ .put(BASE_PATH + "/functions/image-fn/configuration")+ .then()+ .statusCode(200)+ .body("ImageConfigResponse.ImageConfig.Command", hasItem("new.handler"));+ }++ @Test+ @Order(23)+ void deleteImageFunction() {+ given()+ .when()+ .delete(BASE_PATH + "/functions/image-fn")+ .then()+ .statusCode(204);+ }}