Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambdaweb): apply a revision's NODE_OPTIONS as AWS does (#6290)
TATSUNO “Taz” Yasuhiroe7ca14b03bdd
diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdindex 9ab91f9006..a5a437c10b 100644--- a/docs/services/lambda-web-functions.md+++ b/docs/services/lambda-web-functions.md@@ -68,7 +68,7 @@ The `Host` must match the domain exactly, as on AWS: another case or another porA CloudFront distribution of this Floci can use the endpoint as a custom origin, named by its `domainName` without the port as on AWS. Under an `always-amz-auth` origin access control, CloudFront signs the requests to an `IamAuth` endpoint, and the function's resource policy has to allow `cloudfront.amazonaws.com` when IAM enforcement is on. See [CloudFront](cloudfront.md).-An execution environment is a `public.ecr.aws/lambda/nodejs:24` container that a request starts when every environment of the endpoint is full. The code is the revision's S3 object unpacked into `/var/task`. Node starts `/var/runtime/index.js` with the flags AWS uses, as on AWS, and that runtime imports `index.js` or the file `AWS_LAMBDA_NODEJS_ENTRYPOINT` names. So `require.main` is not the app's module, as on AWS. The app sees `AWS_LAMBDA_HTTP_ENDPOINT=0.0.0.0:3000`, `AWS_LAMBDA_INITIALIZATION_TYPE=native-http`, `AWS_EXECUTION_ENV`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE=2048`, `AWS_LAMBDA_LOG_LEVEL`, `AWS_ACCOUNT_ID`, `AWS_REGION`, credentials and `AWS_ENDPOINT_URL` for Floci, `NODE_PATH`, and its own variables. The server has 9 seconds to listen. An environment that sees no request for `floci.services.lambda.container-idle-timeout-seconds` is stopped with `SIGTERM` and one second, as on scale to zero. Node runs under Docker's init, so a server without a `SIGTERM` handler stops at once, as on AWS. A process that exits between requests is replaced by a fresh environment on the next request.+An execution environment is a `public.ecr.aws/lambda/nodejs:24` container that a request starts when every environment of the endpoint is full. The code is the revision's S3 object unpacked into `/var/task`. Node starts `/var/runtime/index.js` with the flags AWS uses, as on AWS, and that runtime imports `index.js` or the file `AWS_LAMBDA_NODEJS_ENTRYPOINT` names. So `require.main` is not the app's module, as on AWS. A `--max-old-space-size` or `--max-semi-space-size` in `NODE_OPTIONS` takes the place of both default heap flags, as on AWS. Other flags there do not replace a default flag, so `--max-http-header-size` in `NODE_OPTIONS` has no effect, and a flag Node does not allow in `NODE_OPTIONS` fails the start with `502 Runtime.ExitError`, as on AWS. The app sees `AWS_LAMBDA_HTTP_ENDPOINT=0.0.0.0:3000`, `AWS_LAMBDA_INITIALIZATION_TYPE=native-http`, `AWS_EXECUTION_ENV`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE=2048`, `AWS_LAMBDA_LOG_LEVEL`, `AWS_ACCOUNT_ID`, `AWS_REGION`, credentials and `AWS_ENDPOINT_URL` for Floci, `NODE_PATH`, and its own variables. The server has 9 seconds to listen. An environment that sees no request for `floci.services.lambda.container-idle-timeout-seconds` is stopped with `SIGTERM` and one second, as on scale to zero. Node runs under Docker's init, so a server without a `SIGTERM` handler stops at once, as on AWS. A process that exits between requests is replaced by a fresh environment on the next request.Each endpoint scales on its own, as on AWS. An environment takes up to the revision's `maxConcurrencyPerEnvironment` requests at once, the least busy one first, so requests rotate over the environments. A request that finds every environment full starts another one, or waits for one that is starting and has room. When the endpoint already runs `maxEnvironments`, an idle environment of another revision makes room, and without one the request is refused with `429` and `Platform.EndpointMaxEnvThrottle`. A `rateLimit` admits a burst of up to `rateLimit` requests that refills at `rateLimit` per second, and refuses the rest with `429` and `Platform.EndpointRequestThrottle`. AWS adjusts the concurrency of each environment under `maxConcurrencyPerEnvironment` from the measured load, so a burst there can spread over more environments than in Floci, and the account quotas are not applied.diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.javaindex dea4e10696..a70f7b39e6 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java@@ -47,6 +47,7 @@ import java.time.Instant;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;import java.util.ArrayList;+import java.util.Arrays;import java.util.Comparator;import java.util.EnumMap;import java.util.List;@@ -85,7 +86,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {static final Duration LISTEN_TIMEOUT = Duration.ofSeconds(9);static final Duration SUMMARY_PERIOD = Duration.ofSeconds(60);static final List<String> NODE_FLAGS = List.of("--expose-gc", "--max-http-header-size", "135168",- "--no-experimental-require-module", "--max-semi-space-size=102", "--max-old-space-size=1024");+ "--no-experimental-require-module");+ static final List<String> HEAP_FLAGS = List.of("--max-semi-space-size=102", "--max-old-space-size=1024");private static final Logger LOG = Logger.getLogger(LambdaWebEnvironmentManager.class);private static final DateTimeFormatter LOG_STREAM_DATE =DateTimeFormatter.ofPattern("yyyy/MM/dd").withZone(ZoneOffset.UTC);@@ -546,7 +548,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {fn.functionName + "-" + revision.revisionId + "-" + shortId);Map<String, String> userEnv = revision.serviceConfig.environmentVariables == null? Map.of() : revision.serviceConfig.environmentVariables;- List<String> cmd = new ArrayList<>(NODE_FLAGS);+ List<String> cmd = nodeFlags(userEnv.get("NODE_OPTIONS"));cmd.add(RUNTIME_DIR + "/index.js");Optional<SessionCreds> roleCredentials = executionRoleCredentials.forRole(revision.serviceConfig.executionRoleArn, accountId, fn.functionName);@@ -657,6 +659,21 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {}}+ /** AWS swaps both of its heap flags for the ones {@code NODE_OPTIONS} names, and keeps its other flags. */+ static List<String> nodeFlags(String nodeOptions) {+ List<String> heap = nodeOptions == null ? List.of()+ : Arrays.stream(nodeOptions.split("\\s+")).filter(LambdaWebEnvironmentManager::isHeapFlag).toList();+ List<String> flags = new ArrayList<>(NODE_FLAGS);+ flags.addAll(heap.isEmpty() ? HEAP_FLAGS : heap);+ return flags;+ }++ /** AWS reads {@code _} as {@code -}, as V8 does, but not a flag in quotes. */+ private static boolean isHeapFlag(String option) {+ String name = option.split("=", 2)[0].replace('_', '-');+ return name.equals("--max-old-space-size") || name.equals("--max-semi-space-size");+ }+private List<String> environment(String accountId, String region, WebFunctionRevision revision,Map<String, String> userEnv, Optional<SessionCreds> roleCredentials) {List<String> env = new ArrayList<>();diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.javaindex f6dea4ad43..b6ad25b311 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java@@ -46,6 +46,7 @@ import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;import static org.hamcrest.Matchers.endsWith;import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.hasKey;@@ -112,7 +113,8 @@ class LambdaWebDataPlaneDockerIntegrationTest {res.end(JSON.stringify({method: req.method, url: req.url, headers: req.headers, bodyLength: body.length,env: {endpoint: process.env.AWS_LAMBDA_HTTP_ENDPOINT, init: process.env.AWS_LAMBDA_INITIALIZATION_TYPE,exec: process.env.AWS_EXECUTION_ENV, account: process.env.AWS_ACCOUNT_ID,- region: process.env.AWS_REGION, custom: process.env.CUSTOM}}));+ region: process.env.AWS_REGION, custom: process.env.CUSTOM},+ execArgv: process.execArgv}));});}).listen(Number(port), host);""";@@ -523,6 +525,11 @@ class LambdaWebDataPlaneDockerIntegrationTest {private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment, String systemLogLevel,String mode, String authType) throws IOException {+ return createFunction(timeoutSeconds, maxConcurrencyPerEnvironment, systemLogLevel, mode, authType, null);+ }++ private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment, String systemLogLevel,+ String mode, String authType, String nodeOptions) throws IOException {functionName = "dp-docker-" + Long.toString(System.nanoTime(), 36);s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, functionName + ".zip", zip(APP), "application/zip", Map.of());@@ -534,12 +541,14 @@ class LambdaWebDataPlaneDockerIntegrationTest {"runtimeConfig": {"runtime": "nodejs24.x"}},"serviceConfig": {"executionRoleArn": "%s", "timeoutSeconds": %d,"maxConcurrencyPerEnvironment": %d,- "environmentVariables": {"CUSTOM": "yes", "MODE": "%s"},+ "environmentVariables": {"CUSTOM": "yes", "MODE": "%s"%s},"telemetryConfig": {"loggingConfig": {"systemLogLevel": "%s"}}}},"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion","authType": "%s", "autoDeploymentMode": "LatestRevision"}}""".formatted(functionName, BUCKET, functionName, ROLE, timeoutSeconds,- maxConcurrencyPerEnvironment, mode, systemLogLevel, authType))+ maxConcurrencyPerEnvironment, mode,+ nodeOptions == null ? "" : ", \"NODE_OPTIONS\": \"" + nodeOptions + "\"",+ systemLogLevel, authType)).when().put(BASE + "/web-functions").then().statusCode(202).extract().path("endpoint.domainName");@@ -650,6 +659,17 @@ class LambdaWebDataPlaneDockerIntegrationTest {.toList(), events.toString());}+ @Test+ @Timeout(180)+ void heapFlagsInNodeOptionsReplaceTheDefaultOnes() throws Exception {+ String domain = createFunction(30, 64, "INFO", "serve", "ApplicationManaged",+ "--expose-gc --max-old-space-size=1536");++ given().header("Host", domain).when().get("/").then().statusCode(200)+ .body("execArgv", contains("--expose-gc", "--max-http-header-size", "135168",+ "--no-experimental-require-module", "--max-old-space-size=1536"));+ }+@Test@Timeout(180)void anAppThatExitsWithAnErrorAtStartGetsTheExitErrorPage() throws Exception {diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.javaindex 897ac54ca9..e32eb4e528 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.java@@ -4,14 +4,61 @@ import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManagerimport org.junit.jupiter.api.Test;import java.time.Duration;+import java.util.ArrayList;+import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;+import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;class LambdaWebEnvironmentManagerTest {+ private static final List<String> BASE = List.of("--expose-gc", "--max-http-header-size", "135168",+ "--no-experimental-require-module");+ private static final List<String> DEFAULT_HEAP = List.of("--max-semi-space-size=102", "--max-old-space-size=1024");++ @Test+ void heapFlagsInNodeOptionsReplaceBothDefaultHeapFlags() {+ assertEquals(flags(DEFAULT_HEAP), LambdaWebEnvironmentManager.nodeFlags(null));+ assertEquals(flags(List.of("--max-old-space-size=1536")),+ LambdaWebEnvironmentManager.nodeFlags("--max-old-space-size=1536"));+ assertEquals(flags(List.of("--max-semi-space-size=64")),+ LambdaWebEnvironmentManager.nodeFlags("--max-semi-space-size=64"));+ assertEquals(flags(List.of("--max-old-space-size=1536", "--max-semi-space-size=64")),+ LambdaWebEnvironmentManager.nodeFlags("--max-old-space-size=1536 --max-semi-space-size=64"));+ assertEquals(flags(List.of("--max-old-space-size=1536", "--max-old-space-size=1200")),+ LambdaWebEnvironmentManager.nodeFlags("--max-old-space-size=1536 --max-old-space-size=1200"));+ assertEquals(flags(List.of("--max_old_space_size=1536")),+ LambdaWebEnvironmentManager.nodeFlags("--max_old_space_size=1536"));+ assertEquals(flags(List.of("--max-old_space-size=1536")),+ LambdaWebEnvironmentManager.nodeFlags("--max-old_space-size=1536"));+ assertEquals(flags(List.of("--max-old-space-size=1536")),+ LambdaWebEnvironmentManager.nodeFlags("--expose-gc --max-old-space-size=1536 --title=y"));+ assertEquals(flags(List.of("--max-semi-space-size=32")),+ LambdaWebEnvironmentManager.nodeFlags("--expose-gc --max-semi-space-size=32"));+ assertEquals(flags(List.of("--max-old-space-size")),+ LambdaWebEnvironmentManager.nodeFlags("--max-old-space-size 1536"));+ assertEquals(flags(List.of("--max-old-space-size=\"1536\"")),+ LambdaWebEnvironmentManager.nodeFlags("--max-old-space-size=\"1536\""));+ }++ @Test+ void otherFlagsInNodeOptionsKeepTheDefaults() {+ List<String> defaults = flags(DEFAULT_HEAP);+ assertEquals(defaults, LambdaWebEnvironmentManager.nodeFlags("--expose-gc"));+ assertEquals(defaults, LambdaWebEnvironmentManager.nodeFlags("--max-http-header-size=1000"));+ assertEquals(defaults, LambdaWebEnvironmentManager.nodeFlags("--require ./pre.js"));+ assertEquals(defaults, LambdaWebEnvironmentManager.nodeFlags("\"--max-old-space-size=1536\""));+ }++ private static List<String> flags(List<String> heap) {+ List<String> flags = new ArrayList<>(BASE);+ flags.addAll(heap);+ return flags;+ }+@Testvoid onlyAnExitSeenBeforeTheRequestStartedAllowsARetry() {Environment environment = new Environment("pool", "rev-1", "000000000000");