From 404b42bdc0152de5bf5d8d01b8af431ff37a86c8 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 25 Apr 2026 19:38:03 -0500 Subject: [PATCH] feat(lambda): bind-mount hot-reload via S3Bucket=hot-reload (#601) * feat(lambda): add bind-mount hot-reload mode via S3Bucket=hot-reload Functions created with S3Bucket=hot-reload and S3Key=/absolute/path have their host directory bind-mounted into /var/task rather than packaged as a ZIP. Each invocation runs an ephemeral container so file changes on disk are picked up immediately without calling UpdateFunctionCode or re-uploading code. Feature is disabled by default; opt in with: FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true An optional path allowlist (FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS) restricts which host directories may be bind-mounted. * fix: missing hot reload enable env --- .github/workflows/compatibility.yml | 8 + .../com/floci/test/LambdaHotReloadTest.java | 141 ++++++++++++++++++ docker-compose.yml | 1 + docs/configuration/application-yml.md | 7 + docs/services/lambda.md | 81 ++++++++++ .../floci/config/EmulatorConfig.java | 25 ++++ .../floci/services/lambda/LambdaService.java | 51 ++++++- .../floci/services/lambda/WarmPool.java | 5 +- .../lambda/launcher/ContainerHandle.java | 8 + .../lambda/launcher/ContainerLauncher.java | 26 ++-- .../services/lambda/model/LambdaFunction.java | 9 ++ src/main/resources/application.yml | 2 + .../services/lambda/LambdaServiceTest.java | 110 ++++++++++++++ src/test/resources/application.yml | 2 + 14 files changed, 462 insertions(+), 14 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaHotReloadTest.java diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index 8bbcc08797..dc0461469b 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -103,6 +103,7 @@ jobs: -e FLOCI_BASE_URL=http://floci:4566 \ -e FLOCI_SERVICES_DOCKER_NETWORK=compat-net \ -e FLOCI_HOSTNAME=floci \ + -e FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true \ floci:test - name: Wait for floci to be ready @@ -137,6 +138,13 @@ jobs: EXTRA_ARGS="-v /var/run/docker.sock:/var/run/docker.sock --group-add $DOCKER_GID" fi + # sdk-test-java: mount a host-side directory so the Docker daemon can + # bind-mount hot-reload code paths that are written by the test container. + if [ "${{ matrix.test }}" = "sdk-test-java" ]; then + mkdir -p /tmp/floci-hot-reload + EXTRA_ARGS="$EXTRA_ARGS -v /tmp/floci-hot-reload:/tmp/floci-hot-reload -e HOT_RELOAD_BASE_DIR=/tmp/floci-hot-reload" + fi + docker run --rm --network compat-net \ -e FLOCI_ENDPOINT=http://floci:4566 \ -v "$(pwd)/test-results:/results" \ diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaHotReloadTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaHotReloadTest.java new file mode 100644 index 0000000000..320f246366 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaHotReloadTest.java @@ -0,0 +1,141 @@ +package com.floci.test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.*; +import software.amazon.awssdk.services.lambda.model.Runtime; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * End-to-end test for Lambda hot-reload (issue #553). + * + *

Creates a function via {@code S3Bucket=hot-reload, S3Key=/host/path}, verifies + * it returns an initial response, then mutates the handler on disk and verifies the + * next invocation picks up the change — without calling UpdateFunctionCode. + * + *

Requires Docker dispatch and that the host path is reachable by the Docker daemon. + * Skipped automatically when Lambda invocation is unavailable. + */ +@DisplayName("Lambda hot-reload (issue #553)") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class LambdaHotReloadTest { + + private static final String FUNCTION_NAME = "sdk-hot-reload-fn"; + private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static LambdaClient lambda; + private static Path codeDir; + + @BeforeAll + static void setup() throws IOException { + assumeTrue(TestFixtures.isLambdaDispatchAvailable(), + "Lambda dispatch unavailable — skipping hot-reload test"); + + lambda = TestFixtures.lambdaClient(); + + // HOT_RELOAD_BASE_DIR is set in CI to a host-mounted volume so the Docker + // daemon (on the host) can see the path. Unset means the test runs locally + // where the system tmpdir is already on the Docker host. + String baseDir = System.getenv("HOT_RELOAD_BASE_DIR"); + codeDir = baseDir != null + ? Files.createTempDirectory(Path.of(baseDir), "floci-hot-reload-") + : Files.createTempDirectory("floci-hot-reload-"); + + writeHandler(codeDir, "v1"); + + lambda.createFunction(CreateFunctionRequest.builder() + .functionName(FUNCTION_NAME) + .runtime(Runtime.NODEJS20_X) + .role(ROLE) + .handler("index.handler") + .timeout(30) + .code(FunctionCode.builder() + .s3Bucket("hot-reload") + .s3Key(codeDir.toAbsolutePath().toString()) + .build()) + .build()); + } + + @AfterAll + static void cleanup() { + if (lambda != null) { + try { lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(FUNCTION_NAME).build()); } catch (Exception ignored) {} + lambda.close(); + } + if (codeDir != null) { + try { Files.deleteIfExists(codeDir.resolve("index.js")); } catch (Exception ignored) {} + try { Files.deleteIfExists(codeDir); } catch (Exception ignored) {} + } + } + + @Test + @Order(1) + @DisplayName("Create hot-reload function succeeds with state Active") + void createHotReloadFunction() { + GetFunctionResponse fn = lambda.getFunction( + GetFunctionRequest.builder().functionName(FUNCTION_NAME).build()); + assertThat(fn.configuration().stateAsString()).isEqualTo("Active"); + assertThat(fn.configuration().functionName()).isEqualTo(FUNCTION_NAME); + } + + @Test + @Order(2) + @DisplayName("Invoke returns initial handler response (v1)") + void invokeReturnsInitialVersion() throws Exception { + InvokeResponse response = invoke(); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.functionError()).isNullOrEmpty(); + + JsonNode result = MAPPER.readTree(response.payload().asUtf8String()); + assertThat(result.path("version").asText()) + .as("First invocation should return v1") + .isEqualTo("v1"); + } + + @Test + @Order(3) + @DisplayName("Mutate handler on disk — next invocation returns updated response (v2) without redeployment") + void mutateHandlerOnDisk_invokeReturnsUpdatedVersion_withoutRedeploy() throws Exception { + writeHandler(codeDir, "v2"); + + InvokeResponse response = invoke(); + + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.functionError()).isNullOrEmpty(); + + JsonNode result = MAPPER.readTree(response.payload().asUtf8String()); + assertThat(result.path("version").asText()) + .as("After overwriting index.js on disk, next invocation must return v2 without UpdateFunctionCode") + .isEqualTo("v2"); + } + + // ── helpers ────────────────────────────────────────────────────────────── + + private static void writeHandler(Path dir, String version) throws IOException { + String code = """ + exports.handler = async () => ({ version: "%s" }); + """.formatted(version); + Files.writeString(dir.resolve("index.js"), code); + } + + private InvokeResponse invoke() { + return lambda.invoke(InvokeRequest.builder() + .functionName(FUNCTION_NAME) + .invocationType(InvocationType.REQUEST_RESPONSE) + .payload(SdkBytes.fromUtf8String("{}")) + .overrideConfiguration(c -> c.apiCallTimeout(Duration.ofSeconds(30))) + .build()); + } +} diff --git a/docker-compose.yml b/docker-compose.yml index 1766738032..7d9a20f78d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -19,6 +19,7 @@ services: FLOCI_STORAGE_HOST_PERSISTENT_PATH: ${PWD}/data FLOCI_HOSTNAME: floci FLOCI_BASE_URL: http://floci:4566 + FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED: "true" networks: floci_default: aliases: diff --git a/docs/configuration/application-yml.md b/docs/configuration/application-yml.md index 7d6b625ece..206bad21a4 100644 --- a/docs/configuration/application-yml.md +++ b/docs/configuration/application-yml.md @@ -117,6 +117,11 @@ floci: container-idle-timeout-seconds: 300 # Remove idle containers after this region-concurrency-limit: 1000 # Concurrent executions ceiling per region unreserved-concurrency-min: 100 # Minimum unreserved capacity PutFunctionConcurrency must leave + hot-reload: + enabled: false # true = enable bind-mount hot-reload via S3Bucket=hot-reload + # allowed-paths: # Optional allowlist of host paths that may be bind-mounted + # - /home/user/projects + # - /tmp apigateway: enabled: true @@ -254,6 +259,8 @@ All keys in this table are declared on `EmulatorConfig` and accept environment v | `FLOCI_SERVICES_SES_SMTP_USER` | *(unset)* | SMTP authentication username | | `FLOCI_SERVICES_SES_SMTP_PASS` | *(unset)* | SMTP authentication password | | `FLOCI_SERVICES_SES_SMTP_STARTTLS` | `DISABLED` | STARTTLS mode: `DISABLED`, `OPTIONAL`, or `REQUIRED` | +| `FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED` | `false` | Enable bind-mount hot-reload mode (`S3Bucket=hot-reload`) | +| `FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS` | *(unset)* | Comma-separated list of host paths allowed as bind-mount roots; unset = any absolute path | Per-queue SQS redrive policy (`maxReceiveCount`) is configured at queue creation time via `SetQueueAttributes` / `CreateQueue`, not as a global default. diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 22d2ece871..b58eda005d 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -79,6 +79,83 @@ aws lambda invoke --function-name my-function out.json !!! note "Standard Behavior" This mechanism requires no custom configuration or non-standard magic strings. It works with standard AWS SDKs and CLI tools, providing a "live" development feel while staying within the AWS API contract. +## Hot-Reload via Bind Mount + +For the tightest inner-loop development cycle, Floci supports a **bind-mount hot-reload** mode. Instead of packaging code into a ZIP and uploading it to S3, you point Floci directly at a directory on your host machine. The directory is bind-mounted into `/var/task` inside the container, so every invocation runs the files as they currently exist on disk — no upload, no redeploy. + +This is enabled by using the magic bucket name `hot-reload` when creating a function: + +```bash +aws lambda create-function \ + --function-name my-function \ + --runtime nodejs22.x \ + --role arn:aws:iam::000000000000:role/lambda-role \ + --handler index.handler \ + --code S3Bucket=hot-reload,S3Key=/absolute/path/to/your/code \ + --endpoint-url http://localhost:4566 +``` + +The `S3Key` must be an **absolute path** reachable by the Docker daemon. When Floci runs in Docker Compose, this is the path on the Docker host (the machine running Docker), not the path inside the Floci container. + +### How it works + +1. `CreateFunction` with `S3Bucket=hot-reload` marks the function as a hot-reload function; `S3Key` is stored as the host-side path. +2. On each invocation, Floci starts a **fresh ephemeral container** with the host path bind-mounted at `/var/task`. +3. The container executes the files as they exist at invocation time — editing a file and immediately invoking picks up the change without any API call. +4. After the invocation completes the container is stopped and removed, ensuring the next invocation always sees the current state of the directory. + +### Configuration + +Hot-reload must be enabled explicitly. By default it is disabled so that `S3Bucket=hot-reload` is treated as a regular S3 bucket name. + +```yaml +floci: + services: + lambda: + hot-reload: + enabled: true # Required — off by default + allowed-paths: # Optional allowlist; omit to allow any absolute path + - /home/user/projects + - /tmp +``` + +Via environment variables: + +```bash +FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true + +# Optional: restrict which host paths may be bind-mounted (comma-separated) +FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS=/home/user/projects,/tmp +``` + +**Docker Compose setup** — enable the feature and share the Docker socket: + +```yaml +services: + floci: + volumes: + - /var/run/docker.sock:/var/run/docker.sock + environment: + FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED: "true" +``` + +### Limitations + +- The `S3Key` path is interpreted by the **Docker daemon**, not by Floci. When Floci itself runs inside Docker, the path must exist on the Docker host machine, not inside the Floci container. +- Hot-reload containers are always ephemeral — there is no warm-container reuse. Each invocation pays a cold-start penalty. +- `UpdateFunctionCode` on a hot-reload function converts it back to a standard Zip function (the hot-reload bind-mount is removed). +- S3 reactive sync is skipped for hot-reload functions — edits are picked up directly from disk. + +### Difference from Reactive S3 Sync + +| | Reactive S3 Sync | Bind-Mount Hot-Reload | +|---|---|---| +| Trigger | Upload a new ZIP to S3 | Edit files on disk | +| Cold start | Only after upload | Every invocation | +| Requires upload step | Yes | No | +| Works without `hot-reload` enabled | Yes | No | +| Path on host required | No | Yes | + !!! note "Concurrency enforcement" Reserved concurrency is enforced: invocations beyond the reserved value return `TooManyRequestsException` (HTTP 429). Functions without a reserved @@ -130,6 +207,10 @@ floci: container-idle-timeout-seconds: 300 # Idle container cleanup region-concurrency-limit: 1000 # Concurrent executions ceiling per region unreserved-concurrency-min: 100 # Min unreserved capacity PutFunctionConcurrency must leave + hot-reload: + enabled: false # true = enable bind-mount hot-reload via S3Bucket=hot-reload + # allowed-paths: # Optional path allowlist (host paths that may be bind-mounted) + # - /home/user/projects ``` ### Docker socket requirement diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 132159af06..32391c8433 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -632,6 +632,31 @@ public interface EmulatorConfig { */ @WithDefault("100") int unreservedConcurrencyMin(); + + HotReload hotReload(); + + interface HotReload { + /** + * When true, the magic bucket name {@code hot-reload} triggers a bind-mount of the + * S3Key path (a Docker-host absolute path) into the Lambda container instead of + * extracting a ZIP. Changes on disk are visible on the next invocation without + * re-deploying. Disabled by default — when false, {@code hot-reload} is an + * ordinary (non-existent) bucket and returns NoSuchBucket as usual. + * + * Env var: FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED + */ + @WithDefault("false") + boolean enabled(); + + /** + * Optional allow-list of absolute path prefixes. When non-empty, the S3Key supplied + * to a hot-reload CreateFunction/UpdateFunctionCode must start with one of these + * prefixes. Empty = all absolute paths are accepted. + * + * Env var: FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS + */ + Optional> allowedPaths(); + } } interface Ec2ServiceConfig { 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 3c8e787465..dde5cae74e 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 @@ -88,13 +88,23 @@ public class LambdaService { CodeStore codeStore, ZipExtractor zipExtractor, RegionResolver regionResolver) { + this(functionStore, warmPool, codeStore, zipExtractor, null, regionResolver); + } + + /** Package-private constructor for testing with a supplied config (e.g. for hot-reload tests). */ + LambdaService(LambdaFunctionStore functionStore, + WarmPool warmPool, + CodeStore codeStore, + ZipExtractor zipExtractor, + EmulatorConfig config, + RegionResolver regionResolver) { this.functionStore = functionStore; this.executorService = null; this.concurrencyLimiter = new LambdaConcurrencyLimiter(); this.warmPool = warmPool; this.codeStore = codeStore; this.zipExtractor = zipExtractor; - this.config = null; + this.config = config; this.regionResolver = regionResolver; this.esmStore = null; this.aliasStore = null; @@ -291,7 +301,11 @@ public class LambdaService { String s3Bucket = (String) code.get("S3Bucket"); String s3Key = (String) code.get("S3Key"); if (s3Bucket != null && s3Key != null) { - extractZipCodeFromS3(fn, s3Bucket, s3Key); + if ("hot-reload".equals(s3Bucket)) { + applyHotReload(fn, s3Key); + } else { + extractZipCodeFromS3(fn, s3Bucket, s3Key); + } } } @@ -358,7 +372,11 @@ public class LambdaService { fn.setImageUri(imageUri); } if (s3Bucket != null && s3Key != null) { - extractZipCodeFromS3(fn, s3Bucket, s3Key); + if ("hot-reload".equals(s3Bucket)) { + applyHotReload(fn, s3Key); + } else { + extractZipCodeFromS3(fn, s3Bucket, s3Key); + } } fn.setLastModified(System.currentTimeMillis()); @@ -1090,6 +1108,30 @@ public class LambdaService { return modulePath; } + private void applyHotReload(LambdaFunction fn, String hostPath) { + if (config == null || !config.services().lambda().hotReload().enabled()) { + throw new AwsException("InvalidParameterValueException", + "Hot-reload is disabled. Set FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true to enable it.", 400); + } + if (hostPath == null || !hostPath.startsWith("/")) { + throw new AwsException("InvalidParameterValueException", + "Hot-reload S3Key must be an absolute path on the Docker host, got: " + hostPath, 400); + } + config.services().lambda().hotReload().allowedPaths().ifPresent(allowed -> { + if (allowed.stream().noneMatch(hostPath::startsWith)) { + throw new AwsException("InvalidParameterValueException", + "Path '" + hostPath + "' is not under an allowed hot-reload mount prefix.", 400); + } + }); + fn.setHotReloadHostPath(hostPath); + fn.setCodeLocalPath(null); + fn.setS3Bucket(null); + fn.setS3Key(null); + fn.setCodeSizeBytes(0); + fn.setCodeSha256(""); + LOG.infov("Hot-reload configured for function {0}: bind-mounting {1}", fn.getFunctionName(), hostPath); + } + // ──────────────────────────── Permissions (Policy) ──────────────────────────── public Map addPermission(String region, String functionName, Map request) { @@ -1228,6 +1270,9 @@ public class LambdaService { String region = regionResolver.getDefaultRegion(); List functions = functionStore.list(region); for (LambdaFunction fn : functions) { + if (fn.isHotReload()) { + continue; + } if (event.bucketName().equals(fn.getS3Bucket()) && event.key().equals(fn.getS3Key())) { LOG.infov("Reactive S3 Sync: updating function {0} from s3://{1}/{2}", fn.getFunctionName(), event.bucketName(), event.key()); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java index cae428680e..69f7f03ef2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java @@ -126,8 +126,9 @@ public class WarmPool { */ public void release(ContainerHandle handle) { boolean ephemeral = config != null && config.services().lambda().ephemeral(); - if (ephemeral) { - LOG.debugv("Ephemeral: stopping container {0} after invocation", handle.getContainerId()); + if (ephemeral || handle.isHotReload()) { + LOG.debugv("{0}: stopping container {1} after invocation", + handle.isHotReload() ? "Hot-reload" : "Ephemeral", handle.getContainerId()); stopQuietly(handle); return; } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java index c03b868cc3..abd458d7f7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java @@ -14,22 +14,30 @@ public class ContainerHandle { private final String functionName; private final RuntimeApiServer runtimeApiServer; private final long createdAt; + private final boolean hotReload; private volatile ContainerState state; private volatile long lastUsedMs; private Closeable logStream; public ContainerHandle(String containerId, String functionName, RuntimeApiServer runtimeApiServer, ContainerState state) { + this(containerId, functionName, runtimeApiServer, state, false); + } + + public ContainerHandle(String containerId, String functionName, + RuntimeApiServer runtimeApiServer, ContainerState state, boolean hotReload) { this.containerId = containerId; this.functionName = functionName; this.runtimeApiServer = runtimeApiServer; this.state = state; + this.hotReload = hotReload; this.createdAt = System.currentTimeMillis(); this.lastUsedMs = this.createdAt; } public String getContainerId() { return containerId; } public String getFunctionName() { return functionName; } + public boolean isHotReload() { return hotReload; } public RuntimeApiServer getRuntimeApiServer() { return runtimeApiServer; } public long getCreatedAt() { return createdAt; } public long getLastUsedMs() { return lastUsedMs; } 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 164e11fea1..b451111965 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 @@ -105,12 +105,15 @@ public class ContainerLauncher { LOG.infov("Launching container for function: {0}", fn.getFunctionName()); // For Zip functions, verify code exists before allocating any resources. - if (fn.getCodeLocalPath() != null) { - Path codePath = Path.of(fn.getCodeLocalPath()); - if (!Files.exists(codePath)) { - throw new RuntimeException("Code directory not found for function '" - + fn.getFunctionName() + "': " + fn.getCodeLocalPath() - + " (function may have been deleted or updated)"); + // Hot-reload functions use a bind-mount; the Docker daemon validates the path at start. + if (!fn.isHotReload()) { + if (fn.getCodeLocalPath() != null) { + Path codePath = Path.of(fn.getCodeLocalPath()); + if (!Files.exists(codePath)) { + throw new RuntimeException("Code directory not found for function '" + + fn.getFunctionName() + "': " + fn.getCodeLocalPath() + + " (function may have been deleted or updated)"); + } } } @@ -159,6 +162,10 @@ public class ContainerLauncher { specBuilder.withEmbeddedDns(); + if (fn.isHotReload()) { + 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()) { specBuilder.withCmd(fn.getHandler()); @@ -171,9 +178,10 @@ public class ContainerLauncher { String containerId = lifecycleManager.create(spec); LOG.infov("Created container {0} for function {1}", containerId, fn.getFunctionName()); - // Copy code into container via Docker API tar stream (works inside Docker too) + // Copy code into container via Docker API tar stream (works inside Docker too). + // Hot-reload functions skip the tar-copy — the bind-mount already wires the host path. DockerClient dockerClient = lifecycleManager.getDockerClient(); - if (fn.getCodeLocalPath() != null) { + if (!fn.isHotReload() && fn.getCodeLocalPath() != null) { Path codePath = Path.of(fn.getCodeLocalPath()); // 1. Always copy all code to /var/task (TASK_DIR) @@ -194,7 +202,7 @@ public class ContainerLauncher { // Now start the container with code in place lifecycleManager.startCreated(containerId, spec); - ContainerHandle handle = new ContainerHandle(containerId, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM); + 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(); 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.java index 9944074e66..1c3bd5b954 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 @@ -47,6 +47,9 @@ public class LambdaFunction { private Map vpcConfig; private String codeSha256; + /** Non-null only for hot-reload functions. Holds the Docker-host path bind-mounted into /var/task. */ + private String hotReloadHostPath; + @JsonIgnore private volatile ContainerState containerState = ContainerState.COLD; @@ -152,6 +155,12 @@ public class LambdaFunction { public String getCodeSha256() { return codeSha256; } public void setCodeSha256(String codeSha256) { this.codeSha256 = codeSha256; } + public String getHotReloadHostPath() { return hotReloadHostPath; } + public void setHotReloadHostPath(String hotReloadHostPath) { this.hotReloadHostPath = hotReloadHostPath; } + + @JsonIgnore + public boolean isHotReload() { return hotReloadHostPath != null; } + @JsonIgnore public ContainerState getContainerState() { return containerState; } @JsonIgnore diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 6b72b23e36..b99fd9e8be 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -111,6 +111,8 @@ floci: container-idle-timeout-seconds: 300 region-concurrency-limit: 1000 unreserved-concurrency-min: 100 + hot-reload: + enabled: false apigateway: enabled: true apigatewayv2: 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 b7dbaded4a..4043ab2b3e 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 @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.lambda; +import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; @@ -14,10 +15,12 @@ import java.nio.file.Path; import java.util.Base64; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; class LambdaServiceTest { @@ -467,6 +470,113 @@ class LambdaServiceTest { assertEquals(0, service.concurrencyLimiter().inflightCount(arn)); } + // ──────────────────────────── Hot-reload ──────────────────────────── + + private LambdaService serviceWithHotReload(boolean enabled, List allowedPaths) { + EmulatorConfig cfg = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig svc = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.LambdaServiceConfig lambdaCfg = mock(EmulatorConfig.LambdaServiceConfig.class); + EmulatorConfig.LambdaServiceConfig.HotReload hr = mock(EmulatorConfig.LambdaServiceConfig.HotReload.class); + + when(cfg.services()).thenReturn(svc); + when(svc.lambda()).thenReturn(lambdaCfg); + when(lambdaCfg.hotReload()).thenReturn(hr); + when(lambdaCfg.defaultTimeoutSeconds()).thenReturn(3); + when(lambdaCfg.defaultMemoryMb()).thenReturn(128); + when(hr.enabled()).thenReturn(enabled); + when(hr.allowedPaths()).thenReturn(allowedPaths == null ? Optional.empty() : Optional.of(allowedPaths)); + + LambdaFunctionStore store = new LambdaFunctionStore(new InMemoryStorage()); + WarmPool warmPool = new WarmPool(); + CodeStore codeStore = new CodeStore(Path.of("target/test-data/lambda-code")); + ZipExtractor zipExtractor = new ZipExtractor(); + RegionResolver regionResolver = new RegionResolver(REGION, "000000000000"); + return new LambdaService(store, warmPool, codeStore, zipExtractor, cfg, regionResolver); + } + + @Test + void hotReload_disabledByDefault_throwsInvalidParameter() { + // The package-private test constructor leaves config=null, which means disabled. + Map req = baseRequest("hr-disabled"); + req.put("Code", Map.of("S3Bucket", "hot-reload", "S3Key", "/tmp/my-fn")); + AwsException ex = assertThrows(AwsException.class, () -> service.createFunction(REGION, req)); + assertEquals("InvalidParameterValueException", ex.getErrorCode()); + } + + @Test + void hotReload_nonAbsolutePath_throwsInvalidParameter() { + LambdaService svc = serviceWithHotReload(true, null); + Map req = baseRequest("hr-relpath"); + req.put("Code", Map.of("S3Bucket", "hot-reload", "S3Key", "relative/path")); + AwsException ex = assertThrows(AwsException.class, () -> svc.createFunction(REGION, req)); + assertEquals("InvalidParameterValueException", ex.getErrorCode()); + assertTrue(ex.getMessage().contains("absolute")); + } + + @Test + void hotReload_allowListRejection_throwsInvalidParameter() { + LambdaService svc = serviceWithHotReload(true, List.of("/allowed/")); + Map req = baseRequest("hr-denied"); + req.put("Code", Map.of("S3Bucket", "hot-reload", "S3Key", "/not-allowed/my-fn")); + AwsException ex = assertThrows(AwsException.class, () -> svc.createFunction(REGION, req)); + assertEquals("InvalidParameterValueException", ex.getErrorCode()); + assertTrue(ex.getMessage().contains("allowed")); + } + + @Test + void hotReload_happyPath_setsHostPathAndClearsCodeLocalPath() { + LambdaService svc = serviceWithHotReload(true, null); + Map req = baseRequest("hr-fn"); + req.put("Code", Map.of("S3Bucket", "hot-reload", "S3Key", "/tmp/my-fn")); + LambdaFunction fn = svc.createFunction(REGION, req); + assertEquals("/tmp/my-fn", fn.getHotReloadHostPath()); + assertNull(fn.getCodeLocalPath()); + assertTrue(fn.isHotReload()); + assertEquals(0L, fn.getCodeSizeBytes()); + } + + @Test + void hotReload_allowListAccepted_setsHostPath() { + LambdaService svc = serviceWithHotReload(true, List.of("/allowed/")); + Map req = baseRequest("hr-allowed"); + req.put("Code", Map.of("S3Bucket", "hot-reload", "S3Key", "/allowed/my-fn")); + LambdaFunction fn = svc.createFunction(REGION, req); + assertEquals("/allowed/my-fn", fn.getHotReloadHostPath()); + } + + @Test + void hotReload_updateFunctionCode_setsNewHostPath() { + LambdaService svc = serviceWithHotReload(true, null); + svc.createFunction(REGION, baseRequest("hr-update")); + + LambdaFunction updated = svc.updateFunctionCode(REGION, "hr-update", + Map.of("S3Bucket", "hot-reload", "S3Key", "/tmp/v2")); + assertEquals("/tmp/v2", updated.getHotReloadHostPath()); + assertTrue(updated.isHotReload()); + } + + @Test + void hotReload_convertFromS3Backed_clearsBucketAndKey() { + // A function previously deployed from S3 that is later converted to hot-reload + // must have s3Bucket/s3Key cleared so the reactive S3 sync observer cannot fire. + LambdaService svc = serviceWithHotReload(true, null); + Map req = baseRequest("hr-convert"); + req.put("Code", Map.of("S3Bucket", "my-code-bucket", "S3Key", "fn.zip")); + // createFunction with a non-existent S3 bucket will fail inside extractZipCodeFromS3 + // because s3Service is null in the test constructor → ServiceUnavailableException. + // So we create without code and then simulate the S3 bucket/key being set directly. + LambdaFunction fn = svc.createFunction(REGION, baseRequest("hr-convert")); + fn.setS3Bucket("my-code-bucket"); + fn.setS3Key("fn.zip"); + + LambdaFunction updated = svc.updateFunctionCode(REGION, "hr-convert", + Map.of("S3Bucket", "hot-reload", "S3Key", "/tmp/converted")); + + assertNull(updated.getS3Bucket(), "s3Bucket must be cleared after hot-reload conversion"); + assertNull(updated.getS3Key(), "s3Key must be cleared after hot-reload conversion"); + assertEquals("/tmp/converted", updated.getHotReloadHostPath()); + } + /** * Test helper: a LambdaFunctionStore whose save() throws on demand so * tests can exercise the LambdaService rollback path. diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index cfb826722e..30c9e27fad 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -64,6 +64,8 @@ floci: enabled: true lambda: enabled: true + hot-reload: + enabled: true apigateway: enabled: true apigatewayv2: