From 3960b6e20eab35c0ba3f6d3b5d0d0484ee15e793 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 29 Apr 2026 00:02:07 -0500 Subject: [PATCH] fix(lambda): inject log group/stream and Floci endpoint env vars into Lambda containers (#640) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(lambda): inject log, endpoint, and hostname env vars into Lambda containers Three missing environment variables prevented Lambda functions from running correctly with newer runtimes and from reaching back into Floci: and AWS_LAMBDA_LOG_STREAM_NAME to be set before the runtime initialises. Floci computed both values but only used them for log streaming — they were never added to the container's env list, causing a hard PlatformError on boot. their container. FLOCI_HOSTNAME, FLOCI_ENDPOINT, and AWS_ENDPOINT_URL are now injected so any AWS SDK client instantiated inside the function uses Floci automatically, without requiring code changes. When the embedded DNS server is active (Floci running in Docker), FLOCI_HOSTNAME is set to the configured hostname (e.g. "floci") rather than a raw IP, because the DNS server is already wired into each Lambda container as its resolver and will resolve that name correctly. In local dev mode (no embedded DNS), the Docker-reachable host address is used as a fallback. Closes #628 Closes #629 * feat(lambda): implement PutFunctionEventInvokeConfig and sibling endpoints (#632) Adds the five event-invoke-config REST endpoints that Terraform's aws_lambda_function_event_invoke_config resource requires: - PUT /2019-09-25/functions/{name}/event-invoke-config — replaces config - POST — partial update (merge) - GET — retrieve config, 404 if absent - DELETE — remove config, 404 if absent - GET .../event-invoke-config/list — list all qualifiers New files: FunctionEventInvokeConfig model (with @RegisterForReflection and correct AWS JSON field names), LambdaEventInvokeController, and LambdaEventInvokeConfigTest (10 unit tests). Storage is an in-memory ConcurrentHashMap keyed by region:functionArn:qualifier. Also fixes the ContainerLauncherTest and LambdaImageConfigTest setUp methods that were missing config.baseUrl() stubs required by the FLOCI_HOSTNAME/FLOCI_ENDPOINT env-var injection added in the branch. --- .../lambda/LambdaEventInvokeController.java | 125 +++++++++++++++ .../floci/services/lambda/LambdaService.java | 104 ++++++++++++ .../lambda/launcher/ContainerLauncher.java | 39 +++-- .../model/FunctionEventInvokeConfig.java | 84 ++++++++++ .../lambda/LambdaEventInvokeConfigTest.java | 148 ++++++++++++++++++ .../lambda/LambdaImageConfigTest.java | 4 +- .../launcher/ContainerLauncherTest.java | 4 +- 7 files changed, 496 insertions(+), 12 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeConfigTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeController.java new file mode 100644 index 0000000000..710b797246 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeController.java @@ -0,0 +1,125 @@ +package io.github.hectorvent.floci.services.lambda; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.List; +import java.util.Map; + +/** + * Lambda function event invoke configuration endpoints. + * + * PutFunctionEventInvokeConfig: PUT /2019-09-25/functions/{FunctionName}/event-invoke-config + * UpdateFunctionEventInvokeConfig: POST /2019-09-25/functions/{FunctionName}/event-invoke-config + * GetFunctionEventInvokeConfig: GET /2019-09-25/functions/{FunctionName}/event-invoke-config + * DeleteFunctionEventInvokeConfig: DELETE /2019-09-25/functions/{FunctionName}/event-invoke-config + * ListFunctionEventInvokeConfigs: GET /2019-09-25/functions/{FunctionName}/event-invoke-config/list + */ +@Path("/") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LambdaEventInvokeController { + + private final LambdaService lambdaService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public LambdaEventInvokeController(LambdaService lambdaService, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.lambdaService = lambdaService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @PUT + @Path("/2019-09-25/functions/{functionName}/event-invoke-config") + public Response putFunctionEventInvokeConfig(@Context HttpHeaders headers, + @PathParam("functionName") String functionName, + @QueryParam("Qualifier") String qualifier, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + FunctionEventInvokeConfig cfg = lambdaService.putEventInvokeConfig(region, functionName, qualifier, request); + return Response.ok(cfg).build(); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("InvalidParameterValueException", e.getMessage(), 400); + } + } + + @POST + @Path("/2019-09-25/functions/{functionName}/event-invoke-config") + public Response updateFunctionEventInvokeConfig(@Context HttpHeaders headers, + @PathParam("functionName") String functionName, + @QueryParam("Qualifier") String qualifier, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + FunctionEventInvokeConfig cfg = lambdaService.updateEventInvokeConfig(region, functionName, qualifier, request); + return Response.ok(cfg).build(); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("InvalidParameterValueException", e.getMessage(), 400); + } + } + + @GET + @Path("/2019-09-25/functions/{functionName}/event-invoke-config") + public Response getFunctionEventInvokeConfig(@Context HttpHeaders headers, + @PathParam("functionName") String functionName, + @QueryParam("Qualifier") String qualifier) { + String region = regionResolver.resolveRegion(headers); + FunctionEventInvokeConfig cfg = lambdaService.getEventInvokeConfig(region, functionName, qualifier); + return Response.ok(cfg).build(); + } + + @DELETE + @Path("/2019-09-25/functions/{functionName}/event-invoke-config") + public Response deleteFunctionEventInvokeConfig(@Context HttpHeaders headers, + @PathParam("functionName") String functionName, + @QueryParam("Qualifier") String qualifier) { + String region = regionResolver.resolveRegion(headers); + lambdaService.deleteEventInvokeConfig(region, functionName, qualifier); + return Response.noContent().build(); + } + + @GET + @Path("/2019-09-25/functions/{functionName}/event-invoke-config/list") + public Response listFunctionEventInvokeConfigs(@Context HttpHeaders headers, + @PathParam("functionName") String functionName) { + String region = regionResolver.resolveRegion(headers); + List configs = lambdaService.listEventInvokeConfigs(region, functionName); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("FunctionEventInvokeConfigs"); + for (FunctionEventInvokeConfig cfg : configs) { + items.addPOJO(cfg); + } + return Response.ok(root).build(); + } +} 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 b8e2b774cf..af8de1c46f 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 @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; +import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import io.github.hectorvent.floci.services.lambda.model.LambdaAlias; @@ -61,6 +62,7 @@ public class LambdaService { private final KinesisEventSourcePoller kinesisPoller; private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller; private final ConcurrentHashMap versionCounters = new ConcurrentHashMap<>(); + private final ConcurrentHashMap eventInvokeConfigs = new ConcurrentHashMap<>(); /** * Per-function locks covering PutFunctionConcurrency, * DeleteFunctionConcurrency, and deleteFunction itself. Serializing the @@ -1290,6 +1292,108 @@ public class LambdaService { } } + // ------------------------------------------------------------------------- + // EventInvokeConfig + // ------------------------------------------------------------------------- + + public FunctionEventInvokeConfig putEventInvokeConfig(String region, String functionName, + String qualifier, Map request) { + LambdaFunction fn = getFunction(region, functionName); + String key = eventInvokeKey(region, fn.getFunctionArn(), qualifier); + FunctionEventInvokeConfig cfg = new FunctionEventInvokeConfig(); + cfg.setFunctionArn(qualifiedArn(fn.getFunctionArn(), qualifier)); + cfg.setLastModified(System.currentTimeMillis()); + applyEventInvokeRequest(cfg, request, true); + eventInvokeConfigs.put(key, cfg); + return cfg; + } + + public FunctionEventInvokeConfig updateEventInvokeConfig(String region, String functionName, + String qualifier, Map request) { + LambdaFunction fn = getFunction(region, functionName); + String key = eventInvokeKey(region, fn.getFunctionArn(), qualifier); + FunctionEventInvokeConfig existing = eventInvokeConfigs.get(key); + if (existing == null) { + throw new AwsException("ResourceNotFoundException", + "The function " + fn.getFunctionArn() + " doesn't have an EventInvokeConfig", 404); + } + applyEventInvokeRequest(existing, request, false); + existing.setLastModified(System.currentTimeMillis()); + return existing; + } + + public FunctionEventInvokeConfig getEventInvokeConfig(String region, String functionName, String qualifier) { + LambdaFunction fn = getFunction(region, functionName); + String key = eventInvokeKey(region, fn.getFunctionArn(), qualifier); + FunctionEventInvokeConfig cfg = eventInvokeConfigs.get(key); + if (cfg == null) { + throw new AwsException("ResourceNotFoundException", + "The function " + fn.getFunctionArn() + " doesn't have an EventInvokeConfig", 404); + } + return cfg; + } + + public void deleteEventInvokeConfig(String region, String functionName, String qualifier) { + LambdaFunction fn = getFunction(region, functionName); + String key = eventInvokeKey(region, fn.getFunctionArn(), qualifier); + if (eventInvokeConfigs.remove(key) == null) { + throw new AwsException("ResourceNotFoundException", + "The function " + fn.getFunctionArn() + " doesn't have an EventInvokeConfig", 404); + } + } + + public List listEventInvokeConfigs(String region, String functionName) { + LambdaFunction fn = getFunction(region, functionName); + String prefix = region + ":" + fn.getFunctionArn() + ":"; + List result = new ArrayList<>(); + for (Map.Entry entry : eventInvokeConfigs.entrySet()) { + if (entry.getKey().startsWith(prefix)) { + result.add(entry.getValue()); + } + } + return result; + } + + private String eventInvokeKey(String region, String functionArn, String qualifier) { + return region + ":" + functionArn + ":" + (qualifier != null ? qualifier : "$LATEST"); + } + + private String qualifiedArn(String functionArn, String qualifier) { + if (qualifier == null || qualifier.isBlank() || "$LATEST".equals(qualifier)) { + return functionArn + ":$LATEST"; + } + return functionArn + ":" + qualifier; + } + + @SuppressWarnings("unchecked") + private void applyEventInvokeRequest(FunctionEventInvokeConfig cfg, Map request, boolean replace) { + if (replace || request.containsKey("MaximumRetryAttempts")) { + Object raw = request.get("MaximumRetryAttempts"); + cfg.setMaximumRetryAttempts(raw instanceof Number ? ((Number) raw).intValue() : null); + } + if (replace || request.containsKey("MaximumEventAgeInSeconds")) { + Object raw = request.get("MaximumEventAgeInSeconds"); + cfg.setMaximumEventAgeInSeconds(raw instanceof Number ? ((Number) raw).intValue() : null); + } + if (replace || request.containsKey("DestinationConfig")) { + Map destMap = (Map) request.get("DestinationConfig"); + if (destMap != null) { + FunctionEventInvokeConfig.DestinationConfig dest = new FunctionEventInvokeConfig.DestinationConfig(); + Map onSuccess = (Map) destMap.get("OnSuccess"); + if (onSuccess != null) { + dest.setOnSuccess(new FunctionEventInvokeConfig.Destination((String) onSuccess.get("Destination"))); + } + Map onFailure = (Map) destMap.get("OnFailure"); + if (onFailure != null) { + dest.setOnFailure(new FunctionEventInvokeConfig.Destination((String) onFailure.get("Destination"))); + } + cfg.setDestinationConfig(dest); + } else if (replace) { + cfg.setDestinationConfig(null); + } + } + } + /** * Observes S3 object updates and triggers reactive sync for any Lambda * functions linked to the updated object. 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.java index e1535cfe21..8d46f3c5cf 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 @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.lambda.launcher; import io.github.hectorvent.floci.config.EmulatorConfig; +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; @@ -54,6 +55,7 @@ public class ContainerLauncher { private final DockerHostResolver dockerHostResolver; private final EmulatorConfig config; private final EcrRegistryManager ecrRegistryManager; + private final EmbeddedDnsServer embeddedDnsServer; /** Matches an AWS-shaped ECR image URI: {@code .dkr.ecr..amazonaws.com/[:tag]}. */ private static final java.util.regex.Pattern AWS_ECR_URI = @@ -67,7 +69,8 @@ public class ContainerLauncher { RuntimeApiServerFactory runtimeApiServerFactory, DockerHostResolver dockerHostResolver, EmulatorConfig config, - EcrRegistryManager ecrRegistryManager) { + EcrRegistryManager ecrRegistryManager, + EmbeddedDnsServer embeddedDnsServer) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.logStreamer = logStreamer; @@ -76,6 +79,7 @@ public class ContainerLauncher { this.dockerHostResolver = dockerHostResolver; this.config = config; this.ecrRegistryManager = ecrRegistryManager; + this.embeddedDnsServer = embeddedDnsServer; } /** @@ -132,6 +136,24 @@ public class ContainerLauncher { String hostAddress = dockerHostResolver.resolve(); String runtimeApiEndpoint = hostAddress + ":" + runtimeApiServer.getPort(); + // Give the container a human-readable name (needed for log stream name below) + String shortId = java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 8); + String containerName = "floci-" + fn.getFunctionName() + "-" + shortId; + + // CloudWatch log coordinates — computed here so they can be injected as env vars + String cwLogGroup = "/aws/lambda/" + fn.getFunctionName(); + String cwLogStream = LOG_STREAM_DATE_FMT.format(LocalDate.now()) + "/[$LATEST]" + shortId; + + // Floci endpoint reachable from inside the container. + // When the embedded DNS server is active, Lambda containers already have it wired as their + // resolver and can reach Floci by the configured hostname (or the default DNS suffix). + // Fall back to the raw Docker host IP when the embedded DNS is not running (local dev mode). + int flociPort = java.net.URI.create(config.baseUrl()).getPort(); + String flociHostname = embeddedDnsServer.getServerIp().isPresent() + ? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX) + : hostAddress; + String flociEndpoint = "http://" + flociHostname + ":" + flociPort; + // Build env vars List env = new ArrayList<>(); env.add("AWS_LAMBDA_RUNTIME_API=" + runtimeApiEndpoint); @@ -139,6 +161,8 @@ public class ContainerLauncher { env.add("AWS_LAMBDA_FUNCTION_MEMORY_SIZE=" + fn.getMemorySize()); env.add("AWS_LAMBDA_FUNCTION_TIMEOUT=" + fn.getTimeout()); env.add("AWS_LAMBDA_FUNCTION_VERSION=$LATEST"); + env.add("AWS_LAMBDA_LOG_GROUP_NAME=" + cwLogGroup); + env.add("AWS_LAMBDA_LOG_STREAM_NAME=" + cwLogStream); if (fn.getHandler() != null && !fn.getHandler().isBlank()) { env.add("_HANDLER=" + fn.getHandler()); } @@ -147,14 +171,13 @@ public class ContainerLauncher { env.add("AWS_ACCESS_KEY_ID=test"); env.add("AWS_SECRET_ACCESS_KEY=test"); env.add("AWS_SESSION_TOKEN=test"); + env.add("FLOCI_HOSTNAME=" + flociHostname); + env.add("FLOCI_ENDPOINT=" + flociEndpoint); + env.add("AWS_ENDPOINT_URL=" + flociEndpoint); if (fn.getEnvironment() != null) { fn.getEnvironment().forEach((k, v) -> env.add(k + "=" + v)); } - // Give the container a human-readable name - String shortId = java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 8); - String containerName = "floci-" + fn.getFunctionName() + "-" + shortId; - ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image) .withName(containerName) .withEnv(env) @@ -214,12 +237,8 @@ public class ContainerLauncher { ContainerHandle handle = new ContainerHandle(containerId, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM, fn.isHotReload()); - // Determine CloudWatch Logs destination for this container instance - String cwLogGroup = "/aws/lambda/" + fn.getFunctionName(); - String region = extractRegionFromArn(fn.getFunctionArn()); - String cwLogStream = LOG_STREAM_DATE_FMT.format(LocalDate.now()) + "/[$LATEST]" + shortId; - // Attach log streaming + String region = extractRegionFromArn(fn.getFunctionArn()); Closeable logHandle = logStreamer.attach( containerId, cwLogGroup, cwLogStream, region, "lambda:" + fn.getFunctionName()); handle.setLogStream(logHandle); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.java new file mode 100644 index 0000000000..7ebc1bc93a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.java @@ -0,0 +1,84 @@ +package io.github.hectorvent.floci.services.lambda.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class FunctionEventInvokeConfig { + + @JsonProperty("FunctionArn") + private String functionArn; + + @JsonIgnore + private long lastModifiedMillis; + + @JsonProperty("MaximumRetryAttempts") + private Integer maximumRetryAttempts; + + @JsonProperty("MaximumEventAgeInSeconds") + private Integer maximumEventAgeInSeconds; + + @JsonProperty("DestinationConfig") + private DestinationConfig destinationConfig; + + public FunctionEventInvokeConfig() {} + + @JsonProperty("LastModified") + public double getLastModifiedSeconds() { + return lastModifiedMillis / 1000.0; + } + + public String getFunctionArn() { return functionArn; } + public void setFunctionArn(String functionArn) { this.functionArn = functionArn; } + + @JsonIgnore + public long getLastModified() { return lastModifiedMillis; } + public void setLastModified(long lastModifiedMillis) { this.lastModifiedMillis = lastModifiedMillis; } + + public Integer getMaximumRetryAttempts() { return maximumRetryAttempts; } + public void setMaximumRetryAttempts(Integer maximumRetryAttempts) { this.maximumRetryAttempts = maximumRetryAttempts; } + + public Integer getMaximumEventAgeInSeconds() { return maximumEventAgeInSeconds; } + public void setMaximumEventAgeInSeconds(Integer maximumEventAgeInSeconds) { this.maximumEventAgeInSeconds = maximumEventAgeInSeconds; } + + public DestinationConfig getDestinationConfig() { return destinationConfig; } + public void setDestinationConfig(DestinationConfig destinationConfig) { this.destinationConfig = destinationConfig; } + + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public static class DestinationConfig { + @JsonProperty("OnSuccess") + private Destination onSuccess; + + @JsonProperty("OnFailure") + private Destination onFailure; + + public DestinationConfig() {} + + public Destination getOnSuccess() { return onSuccess; } + public void setOnSuccess(Destination onSuccess) { this.onSuccess = onSuccess; } + + public Destination getOnFailure() { return onFailure; } + public void setOnFailure(Destination onFailure) { this.onFailure = onFailure; } + } + + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public static class Destination { + @JsonProperty("Destination") + private String destination; + + public Destination() {} + public Destination(String destination) { this.destination = destination; } + + public String getDestination() { return destination; } + public void setDestination(String destination) { this.destination = destination; } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeConfigTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeConfigTest.java new file mode 100644 index 0000000000..e6fe3c383c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEventInvokeConfigTest.java @@ -0,0 +1,148 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig; +import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; +import io.github.hectorvent.floci.services.lambda.zip.CodeStore; +import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class LambdaEventInvokeConfigTest { + + private static final String REGION = "us-east-1"; + + private LambdaService service; + + @BeforeEach + void setUp() { + LambdaFunctionStore store = new LambdaFunctionStore(new InMemoryStorage()); + 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); + + service.createFunction(REGION, Map.of( + "FunctionName", "test-fn", + "PackageType", "Image", + "Role", "arn:aws:iam::000000000000:role/test-role", + "Code", Map.of("ImageUri", "public.ecr.aws/lambda/nodejs:20") + )); + } + + @Test + void putCreatesConfig() { + Map req = new HashMap<>(); + req.put("MaximumRetryAttempts", 1); + req.put("MaximumEventAgeInSeconds", 3600); + + FunctionEventInvokeConfig cfg = service.putEventInvokeConfig(REGION, "test-fn", null, req); + + assertEquals(1, cfg.getMaximumRetryAttempts()); + assertEquals(3600, cfg.getMaximumEventAgeInSeconds()); + assertTrue(cfg.getFunctionArn().endsWith(":$LATEST")); + assertTrue(cfg.getLastModifiedSeconds() > 0); + } + + @Test + void putReplacesExistingConfig() { + service.putEventInvokeConfig(REGION, "test-fn", null, Map.of("MaximumRetryAttempts", 2)); + + Map req2 = new HashMap<>(); + req2.put("MaximumRetryAttempts", 0); + FunctionEventInvokeConfig cfg = service.putEventInvokeConfig(REGION, "test-fn", null, req2); + + assertEquals(0, cfg.getMaximumRetryAttempts()); + assertNull(cfg.getMaximumEventAgeInSeconds()); + } + + @Test + void getReturnsStoredConfig() { + service.putEventInvokeConfig(REGION, "test-fn", null, Map.of("MaximumRetryAttempts", 1)); + + FunctionEventInvokeConfig cfg = service.getEventInvokeConfig(REGION, "test-fn", null); + + assertEquals(1, cfg.getMaximumRetryAttempts()); + } + + @Test + void getThrows404WhenNotFound() { + AwsException ex = assertThrows(AwsException.class, + () -> service.getEventInvokeConfig(REGION, "test-fn", null)); + assertEquals(404, ex.getHttpStatus()); + } + + @Test + void updateMergesPartialFields() { + service.putEventInvokeConfig(REGION, "test-fn", null, Map.of( + "MaximumRetryAttempts", 2, + "MaximumEventAgeInSeconds", 7200)); + + Map partial = new HashMap<>(); + partial.put("MaximumRetryAttempts", 0); + service.updateEventInvokeConfig(REGION, "test-fn", null, partial); + + FunctionEventInvokeConfig cfg = service.getEventInvokeConfig(REGION, "test-fn", null); + assertEquals(0, cfg.getMaximumRetryAttempts()); + assertEquals(7200, cfg.getMaximumEventAgeInSeconds()); + } + + @Test + void updateThrows404WhenNotFound() { + AwsException ex = assertThrows(AwsException.class, + () -> service.updateEventInvokeConfig(REGION, "test-fn", null, Map.of())); + assertEquals(404, ex.getHttpStatus()); + } + + @Test + void deleteRemovesConfig() { + service.putEventInvokeConfig(REGION, "test-fn", null, Map.of("MaximumRetryAttempts", 1)); + service.deleteEventInvokeConfig(REGION, "test-fn", null); + + assertThrows(AwsException.class, + () -> service.getEventInvokeConfig(REGION, "test-fn", null)); + } + + @Test + void deleteThrows404WhenNotFound() { + AwsException ex = assertThrows(AwsException.class, + () -> service.deleteEventInvokeConfig(REGION, "test-fn", null)); + assertEquals(404, ex.getHttpStatus()); + } + + @Test + void listReturnsAllConfigsForFunction() { + service.putEventInvokeConfig(REGION, "test-fn", null, Map.of("MaximumRetryAttempts", 1)); + service.putEventInvokeConfig(REGION, "test-fn", "1", Map.of("MaximumRetryAttempts", 0)); + + List configs = service.listEventInvokeConfigs(REGION, "test-fn"); + + assertEquals(2, configs.size()); + } + + @Test + void putWithDestinationConfig() { + Map req = new HashMap<>(); + req.put("DestinationConfig", Map.of( + "OnSuccess", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:my-queue"), + "OnFailure", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:dlq") + )); + + FunctionEventInvokeConfig cfg = service.putEventInvokeConfig(REGION, "test-fn", null, req); + + assertNotNull(cfg.getDestinationConfig()); + assertEquals("arn:aws:sqs:us-east-1:000000000000:my-queue", + cfg.getDestinationConfig().getOnSuccess().getDestination()); + assertEquals("arn:aws:sqs:us-east-1:000000000000:dlq", + cfg.getDestinationConfig().getOnFailure().getDestination()); + } +} 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.java index 9bca37fd64..7b6e6a7946 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java @@ -181,11 +181,13 @@ class LambdaImageConfigTest { when(config.docker()).thenReturn(docker); when(docker.logMaxSize()).thenReturn("10m"); when(docker.logMaxFile()).thenReturn("3"); + when(config.baseUrl()).thenReturn("http://localhost:4566"); + lenient().when(config.hostname()).thenReturn(Optional.empty()); when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty()); ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer); launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver, - runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager); + runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, embeddedDnsServer); when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer); when(runtimeApiServer.getPort()).thenReturn(9000); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java index fa8ebdf9f1..06bc0fa340 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java @@ -67,12 +67,14 @@ class ContainerLauncherTest { when(config.docker()).thenReturn(docker); when(docker.logMaxSize()).thenReturn("10m"); when(docker.logMaxFile()).thenReturn("3"); + when(config.baseUrl()).thenReturn("http://localhost:4566"); + lenient().when(config.hostname()).thenReturn(Optional.empty()); when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty()); ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer); launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver, - runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager); + runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, embeddedDnsServer); when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer); when(runtimeApiServer.getPort()).thenReturn(9000);