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