diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaFunctionConfigTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaFunctionConfigTest.java index 10e6ea77d9..734660cc86 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaFunctionConfigTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaFunctionConfigTest.java @@ -275,4 +275,57 @@ class LambdaFunctionConfigTest { } catch (Exception ignored) {} } } + + @Test + @Order(7) + @DisplayName("DurableConfig round-trips via create, update and get") + void durableConfigRoundTrips() { + String durableFn = TestFixtures.uniqueName("fn-durable"); + try { + CreateFunctionResponse createResp = lambda.createFunction(CreateFunctionRequest.builder() + .functionName(durableFn) + .runtime(Runtime.NODEJS20_X) + .role(ROLE) + .handler("index.handler") + .code(FunctionCode.builder() + .zipFile(SdkBytes.fromByteArray(LambdaUtils.minimalZip())) + .build()) + .durableConfig(DurableConfig.builder().executionTimeout(3600).build()) + .build()); + + assertThat(createResp.durableConfig().executionTimeout()).isEqualTo(3600); + assertThat(createResp.durableConfig().retentionPeriodInDays()) + .as("RetentionPeriodInDays defaults to 14") + .isEqualTo(14); + assertThat(createResp.timeout()) + .as("Timeout of a durable function defaults to the 15 minute cap") + .isEqualTo(900); + + UpdateFunctionConfigurationResponse updateResp = lambda.updateFunctionConfiguration( + UpdateFunctionConfigurationRequest.builder() + .functionName(durableFn) + .durableConfig(DurableConfig.builder().retentionPeriodInDays(7).build()) + .build()); + assertThat(updateResp.durableConfig().executionTimeout()) + .as("a member left out of the update keeps its value") + .isEqualTo(3600); + assertThat(updateResp.durableConfig().retentionPeriodInDays()).isEqualTo(7); + + GetFunctionConfigurationResponse getResp = lambda.getFunctionConfiguration( + GetFunctionConfigurationRequest.builder().functionName(durableFn).build()); + assertThat(getResp.durableConfig().retentionPeriodInDays()).isEqualTo(7); + + GetFunctionConfigurationResponse plain = lambda.getFunctionConfiguration( + GetFunctionConfigurationRequest.builder().functionName(FN).build()); + assertThat(plain.durableConfig()) + .as("a function created without DurableConfig has none") + .isNull(); + } finally { + try { + lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(durableFn).build()); + } catch (Exception ignored) { + // Cleanup only. A failed delete must not hide the test result. + } + } + } } diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 6e6dfb7141..b9993435b1 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -675,9 +675,9 @@ No extra configuration or `cap_add` is needed because Docker containers have `CAP_NET_BIND_SERVICE` in their default capability set, so Floci (running as a non-root user) can bind UDP/53 without any changes to your Compose file. -### VpcConfig, SnapStart and LoggingConfig +### VpcConfig, SnapStart, LoggingConfig and DurableConfig -All three round-trip through `CreateFunction`, `UpdateFunctionConfiguration`, +All four round-trip through `CreateFunction`, `UpdateFunctionConfiguration`, `GetFunctionConfiguration`, `GetFunction`, `ListFunctions` and `PublishVersion`. The response shapes are **not** the request shapes, and Floci follows the AWS model @@ -688,6 +688,7 @@ rather than echoing the request back: | `VpcConfig` | `VpcConfig` | `VpcConfigResponse` | `VpcId`, resolved from the first subnet via EC2 | | `SnapStart` | `SnapStart` | `SnapStartResponse` | `OptimizationStatus` — `On` only for a published version with `ApplyOn=PublishedVersions`, `Off` for `$LATEST` | | `LoggingConfig` | `LoggingConfig` | `LoggingConfig` | — | +| `DurableConfig` | `DurableConfig` | `DurableConfig` | `RetentionPeriodInDays` defaults to 14; omitted for a function created without it | `SnapStart` and `LoggingConfig` are always present in a response, as on AWS: an unset function reads back `SnapStart={ApplyOn: None, OptimizationStatus: Off}` and @@ -699,6 +700,12 @@ is a permanent diff rather than a cosmetic omission. `LoggingConfig` is replaced wholesale on update, not merged — an update naming only `LogFormat` resets `LogGroup` to the default. +`DurableConfig` requires `ExecutionTimeout` on create. A durable function created without +a `Timeout` gets `min(ExecutionTimeout, 900)`. It always logs in JSON format, and +`LogFormat: Text` is rejected. On update the members are merged, and a function created +without `DurableConfig` cannot gain one. The durable execution itself (checkpoints, waits, +callbacks) is not emulated yet; the configuration only round-trips. + `LogGroup` is validated against AWS's documented constraint: 1-512 characters matching `[.\-_/#A-Za-z0-9]+`. `ApplicationLogLevel` and `SystemLogLevel` are accepted with any `LogFormat` but are only ever stored — and therefore only ever returned — when the diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java index 67b20a2162..fc24eece71 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java @@ -769,12 +769,26 @@ public class LambdaController { putSnapStart(node, fn); putLoggingConfig(node, fn); putRuntimeVersionConfig(node, fn); + putDurableConfig(node, fn); @SuppressWarnings("unchecked") Map result = objectMapper.convertValue(node, Map.class); return result; } + /** Only durable functions carry a DurableConfig; AWS omits the member for every other function. */ + private void putDurableConfig(ObjectNode node, LambdaFunction fn) { + if (!fn.isDurable()) { + return; + } + ObjectNode durable = node.putObject("DurableConfig"); + durable.put("ExecutionTimeout", fn.getDurableExecutionTimeout()); + durable.put("RetentionPeriodInDays", fn.getDurableRetentionPeriodInDays()); + if (fn.getDurableKmsKeyArn() != null) { + durable.put("KMSKeyArn", fn.getDurableKmsKeyArn()); + } + } + /** * VpcConfigResponse, not VpcConfig: the response shape adds VpcId, which the request shape * has no member for. Emitted only while the function is actually attached to a VPC — AWS 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 e8b9de91bc..a7feb187f9 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 @@ -89,6 +89,13 @@ public class LambdaService implements ResourceProvider { private static final int MAX_TAG_KEY_LENGTH = 128; private static final Pattern KMS_KEY_ARN_PATTERN = Pattern.compile( "^(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)?$"); + /** The DurableConfig member has its own pattern text, which AWS prints in the validation message. */ + private static final Pattern DURABLE_KMS_KEY_ARN_PATTERN = Pattern.compile( + "(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()"); + private static final int MAX_DURABLE_EXECUTION_TIMEOUT_SECONDS = 31622400; + private static final int MAX_DURABLE_RETENTION_DAYS = 90; + private static final int DEFAULT_DURABLE_RETENTION_DAYS = 14; + private static final int MAX_FUNCTION_TIMEOUT_SECONDS = 900; private static final Pattern LAYER_VERSION_ARN_PATTERN = Pattern.compile( "^((arn:(aws[a-zA-Z-]*)?:lambda:(eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}:\\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+)" + "|(arn:[a-zA-Z0-9-]+:lambda:::awslayer:[a-zA-Z0-9-_]+))$"); @@ -124,7 +131,7 @@ public class LambdaService implements ResourceProvider { */ private static final List CONFIG_STRUCTURE_MEMBERS = List.of( "Environment", "EphemeralStorage", "TracingConfig", "DeadLetterConfig", - "VpcConfig", "SnapStart", "LoggingConfig", "ImageConfig"); + "VpcConfig", "SnapStart", "LoggingConfig", "ImageConfig", "DurableConfig"); private final LambdaFunctionStore functionStore; private final LambdaExecutorService executorService; @@ -404,6 +411,7 @@ public class LambdaService implements ResourceProvider { Map snapStart = structureMember(request, "SnapStart"); Map loggingConfig = structureMember(request, "LoggingConfig"); Map imageConfig = structureMember(request, "ImageConfig"); + Map durableConfig = structureMember(request, "DurableConfig"); Map code = structureMember(request, "Code"); String functionName = (String) request.get("FunctionName"); @@ -413,7 +421,16 @@ public class LambdaService implements ResourceProvider { validateEnum(request.get("PackageType"), "packageType", List.of("Zip", "Image")); String packageType = request.getOrDefault("PackageType", "Zip").toString(); String description = (String) request.get("Description"); - int timeout = toInt(request.get("Timeout"), config != null ? config.services().lambda().defaultTimeoutSeconds() : 3); + DurableConfigRequest durable = durableConfigRequest(durableConfig); + int defaultTimeout = config != null ? config.services().lambda().defaultTimeoutSeconds() : 3; + if (durable != null) { + if (durable.executionTimeout() == null) { + throw new AwsException("InvalidParameterValueException", + "You cannot create a function with a durable configuration without an executionTimeout", 400); + } + defaultTimeout = Math.min(durable.executionTimeout(), MAX_FUNCTION_TIMEOUT_SECONDS); + } + int timeout = toInt(request.get("Timeout"), defaultTimeout); int memorySize = toInt(request.get("MemorySize"), config != null ? config.services().lambda().defaultMemoryMb() : 128); if (functionName == null || functionName.isBlank()) { @@ -511,6 +528,7 @@ public class LambdaService implements ResourceProvider { } applySnapStart(fn, snapStart); + applyDurableConfig(fn, durable); applyLoggingConfig(fn, loggingConfig); List fileSystemConfigs = @@ -772,6 +790,7 @@ public class LambdaService implements ResourceProvider { Map snapStart = structureMember(request, "SnapStart"); Map loggingConfig = structureMember(request, "LoggingConfig"); Map imageConfig = structureMember(request, "ImageConfig"); + Map durableConfig = structureMember(request, "DurableConfig"); // Validated before any field mutation below, not inline where Layers is applied further // down - fn is the live object backing this store entry (InMemoryStorage#get returns the @@ -798,8 +817,14 @@ public class LambdaService implements ResourceProvider { validateSnapStart(snapStart); } if (request.containsKey("LoggingConfig")) { - validateLoggingConfig(loggingConfig); + validateLoggingConfig(loggingConfig, fn.isDurable()); } + if (durableConfig != null && !fn.isDurable()) { + throw new AwsException("InvalidParameterValueException", + "You cannot add a durable configuration to a function that was originally created " + + "with no durable configuration", 400); + } + DurableConfigRequest durable = durableConfigRequest(durableConfig); if (request.containsKey("Role")) { validateRoleArn((String) request.get("Role")); } @@ -904,6 +929,10 @@ public class LambdaService implements ResourceProvider { applyLoggingConfig(fn, loggingConfig); } + if (durable != null) { + mergeDurableConfig(fn, durable); + } + if (request.containsKey("FileSystemConfigs")) { fn.setFileSystemConfigs(requestedFileSystemConfigs); } @@ -2249,6 +2278,9 @@ public class LambdaService implements ResourceProvider { snapshot.setTracingMode(fn.getTracingMode()); snapshot.setDeadLetterTargetArn(fn.getDeadLetterTargetArn()); snapshot.setKmsKeyArn(fn.getKmsKeyArn()); + snapshot.setDurableExecutionTimeout(fn.getDurableExecutionTimeout()); + snapshot.setDurableRetentionPeriodInDays(fn.getDurableRetentionPeriodInDays()); + snapshot.setDurableKmsKeyArn(fn.getDurableKmsKeyArn()); functionStore.save(region, snapshot); LOG.infov("Published version {0} for function {1}", version, functionName); @@ -2443,10 +2475,75 @@ public class LambdaService implements ResourceProvider { fn.setSnapStartApplyOn(applyOn instanceof String s && !s.isBlank() ? s : "None"); } - private static void validateLoggingConfig(Object value) { + /** The members of a request's DurableConfig after type, range and pattern validation; each may be absent. */ + private record DurableConfigRequest(Integer executionTimeout, Integer retentionPeriodInDays, String kmsKeyArn) { + } + + private static DurableConfigRequest durableConfigRequest(Map durableConfig) { + if (durableConfig == null) { + return null; + } + Integer executionTimeout = durableConfigInteger(durableConfig.get("ExecutionTimeout"), + "ExecutionTimeout", MAX_DURABLE_EXECUTION_TIMEOUT_SECONDS); + Integer retentionPeriodInDays = durableConfigInteger(durableConfig.get("RetentionPeriodInDays"), + "RetentionPeriodInDays", MAX_DURABLE_RETENTION_DAYS); + Object kmsKeyArn = durableConfig.get("KMSKeyArn"); + if (kmsKeyArn != null && !(kmsKeyArn instanceof String)) { + throw new AwsException("SerializationException", "DurableConfig.KMSKeyArn must be a string", 400); + } + validatePattern(kmsKeyArn, "durableConfig.kMSKeyArn", DURABLE_KMS_KEY_ARN_PATTERN); + return new DurableConfigRequest(executionTimeout, retentionPeriodInDays, (String) kmsKeyArn); + } + + private static Integer durableConfigInteger(Object value, String member, int maximum) { + if (value == null) { + return null; + } + if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long)) { + throw new AwsException("SerializationException", "DurableConfig." + member + " must be an integer", 400); + } + long number = ((Number) value).longValue(); + if (number < 1 || number > maximum) { + String field = "durableConfig." + Character.toLowerCase(member.charAt(0)) + member.substring(1); + String bound = number < 1 ? "greater than or equal to 1" : "less than or equal to " + maximum; + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + number + "' at '" + field + "' failed to satisfy " + + "constraint: Member must have value " + bound, 400); + } + return (int) number; + } + + private static void applyDurableConfig(LambdaFunction fn, DurableConfigRequest durable) { + if (durable == null) { + return; + } + fn.setDurableRetentionPeriodInDays(DEFAULT_DURABLE_RETENTION_DAYS); + mergeDurableConfig(fn, durable); + fn.setLogFormat("JSON"); + } + + /** UpdateFunctionConfiguration merges DurableConfig per member; a member left out keeps its stored value. */ + private static void mergeDurableConfig(LambdaFunction fn, DurableConfigRequest durable) { + if (durable.executionTimeout() != null) { + fn.setDurableExecutionTimeout(durable.executionTimeout()); + } + if (durable.retentionPeriodInDays() != null) { + fn.setDurableRetentionPeriodInDays(durable.retentionPeriodInDays()); + } + if (durable.kmsKeyArn() != null) { + fn.setDurableKmsKeyArn(durable.kmsKeyArn().isEmpty() ? null : durable.kmsKeyArn()); + } + } + + private static void validateLoggingConfig(Object value, boolean durable) { if (!(value instanceof Map logging)) { return; } + if (durable && "Text".equals(logging.get("LogFormat"))) { + throw new AwsException("InvalidParameterValueException", + "You cannot use plain text logs with a durable function. Only JSON format logs are supported", + 400); + } validateEnum(logging.get("LogFormat"), "loggingConfig.logFormat", List.of("JSON", "Text")); validateEnum(logging.get("ApplicationLogLevel"), "loggingConfig.applicationLogLevel", List.of("TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL")); @@ -2614,8 +2711,9 @@ public class LambdaService implements ResourceProvider { if (!(value instanceof Map logging)) { return; } - validateLoggingConfig(value); - String format = logging.get("LogFormat") instanceof String f && !f.isBlank() ? f : "Text"; + validateLoggingConfig(value, fn.isDurable()); + String defaultFormat = fn.isDurable() ? "JSON" : "Text"; + String format = logging.get("LogFormat") instanceof String f && !f.isBlank() ? f : defaultFormat; boolean json = "JSON".equals(format); fn.setLogFormat(format); fn.setApplicationLogLevel(json && logging.get("ApplicationLogLevel") instanceof String level 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 28772a62cf..2c3df4150f 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 @@ -69,6 +69,10 @@ public class LambdaFunction { private String logGroup; private List fileSystemConfigs = new ArrayList<>(); private String codeSha256; + /** Non-null only for durable functions: AWS requires ExecutionTimeout whenever DurableConfig is given. */ + private Integer durableExecutionTimeout; + private Integer durableRetentionPeriodInDays; + private String durableKmsKeyArn; /** Non-null only for hot-reload functions. Holds the Docker-host path bind-mounted into /var/task. */ private String hotReloadHostPath; @@ -215,6 +219,22 @@ public class LambdaFunction { public String getCodeSha256() { return codeSha256; } public void setCodeSha256(String codeSha256) { this.codeSha256 = codeSha256; } + public Integer getDurableExecutionTimeout() { return durableExecutionTimeout; } + public void setDurableExecutionTimeout(Integer durableExecutionTimeout) { + this.durableExecutionTimeout = durableExecutionTimeout; + } + + public Integer getDurableRetentionPeriodInDays() { return durableRetentionPeriodInDays; } + public void setDurableRetentionPeriodInDays(Integer durableRetentionPeriodInDays) { + this.durableRetentionPeriodInDays = durableRetentionPeriodInDays; + } + + public String getDurableKmsKeyArn() { return durableKmsKeyArn; } + public void setDurableKmsKeyArn(String durableKmsKeyArn) { this.durableKmsKeyArn = durableKmsKeyArn; } + + @JsonIgnore + public boolean isDurable() { return durableExecutionTimeout != null; } + public String getHotReloadHostPath() { return hotReloadHostPath; } public void setHotReloadHostPath(String hotReloadHostPath) { this.hotReloadHostPath = hotReloadHostPath; } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDurableConfigIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDurableConfigIntegrationTest.java new file mode 100644 index 0000000000..a492e2d126 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDurableConfigIntegrationTest.java @@ -0,0 +1,259 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; + +/** + * DurableConfig marks a function as a durable function. It is accepted by CreateFunction and + * UpdateFunctionConfiguration, snapshotted by PublishVersion, and returned by every read, while a + * plain function never carries the member. + */ +@QuarkusTest +class LambdaDurableConfigIntegrationTest { + + private static final String BASE_PATH = "/2015-03-31"; + private static final String KMS_KEY_ARN = + "arn:aws:kms:us-east-1:000000000000:key/11111111-1111-1111-1111-111111111111"; + private static final String TEXT_LOGS_MESSAGE = "You cannot use plain text logs with a durable function. " + + "Only JSON format logs are supported"; + + /** Posts CreateFunction for {@code name}; {@code members} are extra JSON members, already comma separated. */ + private static ValidatableResponse createFunction(String name, String members) { + String body = """ + { + "FunctionName": "%s", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler"%s + } + """.formatted(name, members.isEmpty() ? "" : ",\n" + members); + return given() + .contentType("application/json") + .body(body) + .when() + .post(BASE_PATH + "/functions") + .then(); + } + + private static ValidatableResponse createDurableFunction(String name, String durableConfig) { + return createFunction(name, "\"DurableConfig\": " + durableConfig); + } + + private static ValidatableResponse updateConfiguration(String name, String body) { + return given() + .contentType("application/json") + .body(body) + .when() + .put(BASE_PATH + "/functions/" + name + "/configuration") + .then(); + } + + private static ValidatableResponse getConfiguration(String name) { + return getConfiguration(name, ""); + } + + private static ValidatableResponse getConfiguration(String name, String query) { + return given() + .when() + .get(BASE_PATH + "/functions/" + name + "/configuration" + query) + .then(); + } + + @Test + void createDefaultsRetentionTimeoutAndJsonLogging() { + createDurableFunction("durable-defaults-fn", "{\"ExecutionTimeout\": 3600}") + .statusCode(201) + .body("DurableConfig.ExecutionTimeout", equalTo(3600)) + .body("DurableConfig.RetentionPeriodInDays", equalTo(14)) + .body("DurableConfig", not(hasKey("KMSKeyArn"))) + .body("Timeout", equalTo(900)) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.ApplicationLogLevel", equalTo("INFO")) + .body("LoggingConfig.SystemLogLevel", equalTo("INFO")); + + createDurableFunction("durable-short-timeout-fn", "{\"ExecutionTimeout\": 60}") + .statusCode(201) + .body("Timeout", equalTo(60)); + } + + @Test + void createKeepsExplicitMembers() { + createFunction("durable-explicit-fn", """ + "Timeout": 3, + "DurableConfig": { + "ExecutionTimeout": 60, + "RetentionPeriodInDays": 7, + "KMSKeyArn": "%s" + }""".formatted(KMS_KEY_ARN)) + .statusCode(201); + + getConfiguration("durable-explicit-fn") + .statusCode(200) + .body("Timeout", equalTo(3)) + .body("DurableConfig.ExecutionTimeout", equalTo(60)) + .body("DurableConfig.RetentionPeriodInDays", equalTo(7)) + .body("DurableConfig.KMSKeyArn", equalTo(KMS_KEY_ARN)); + } + + @Test + void emptyKmsKeyArnMeansNoKey() { + createDurableFunction("durable-no-key-fn", "{\"ExecutionTimeout\": 60, \"KMSKeyArn\": \"\"}") + .statusCode(201) + .body("DurableConfig", not(hasKey("KMSKeyArn"))); + } + + @Test + void durableFunctionLogsInJsonFormatOnly() { + createFunction("durable-text-logs-fn", """ + "LoggingConfig": {"LogFormat": "Text"}, + "DurableConfig": {"ExecutionTimeout": 60}""") + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", equalTo(TEXT_LOGS_MESSAGE)); + + createFunction("durable-partial-logs-fn", """ + "LoggingConfig": {"LogGroup": "/custom/durable"}, + "DurableConfig": {"ExecutionTimeout": 60}""") + .statusCode(201) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.LogGroup", equalTo("/custom/durable")); + + createFunction("durable-json-levels-fn", """ + "LoggingConfig": {"LogFormat": "JSON", "ApplicationLogLevel": "WARN"}, + "DurableConfig": {"ExecutionTimeout": 60}""") + .statusCode(201) + .body("LoggingConfig.ApplicationLogLevel", equalTo("WARN")) + .body("LoggingConfig.SystemLogLevel", equalTo("INFO")); + + updateConfiguration("durable-partial-logs-fn", "{\"LoggingConfig\": {\"LogFormat\": \"Text\"}}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", equalTo(TEXT_LOGS_MESSAGE)); + + updateConfiguration("durable-partial-logs-fn", "{\"LoggingConfig\": {\"LogGroup\": \"/custom/updated\"}}") + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.LogGroup", equalTo("/custom/updated")); + } + + @Test + void plainFunctionHasNoDurableConfig() { + createFunction("plain-no-durable-fn", "") + .statusCode(201) + .body("$", not(hasKey("DurableConfig"))) + .body("Timeout", equalTo(3)) + .body("LoggingConfig.LogFormat", equalTo("Text")); + + getConfiguration("plain-no-durable-fn") + .statusCode(200) + .body("$", not(hasKey("DurableConfig"))); + } + + @Test + void createWithoutExecutionTimeoutIsRejected() { + createDurableFunction("durable-invalid-fn", "{\"RetentionPeriodInDays\": 7}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", equalTo("You cannot create a function with a durable configuration " + + "without an executionTimeout")); + } + + @Test + void membersOutOfRangeAreValidationErrors() { + createDurableFunction("durable-invalid-fn", "{\"ExecutionTimeout\": 0}") + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value '0' at " + + "'durableConfig.executionTimeout' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1")); + + createDurableFunction("durable-invalid-fn", "{\"ExecutionTimeout\": 60, \"RetentionPeriodInDays\": 91}") + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value '91' at " + + "'durableConfig.retentionPeriodInDays' failed to satisfy constraint: " + + "Member must have value less than or equal to 90")); + } + + @Test + void nonIntegerMembersAreSerializationErrors() { + createDurableFunction("durable-invalid-fn", "{\"ExecutionTimeout\": \"60\"}") + .statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("DurableConfig.ExecutionTimeout must be an integer")); + } + + @Test + void kmsKeyArnMustMatchThePattern() { + createDurableFunction("durable-invalid-fn", "{\"ExecutionTimeout\": 60, \"KMSKeyArn\": \"not-an-arn\"}") + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'not-an-arn' at " + + "'durableConfig.kMSKeyArn' failed to satisfy constraint: Member must satisfy regular " + + "expression pattern: (arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()")); + } + + @Test + void updateMergesMembersAndAPublishedVersionKeepsItsSnapshot() { + createDurableFunction("durable-update-fn", "{\"ExecutionTimeout\": 3600, \"RetentionPeriodInDays\": 7}") + .statusCode(201); + + given() + .contentType("application/json") + .body("{}") + .when() + .post(BASE_PATH + "/functions/durable-update-fn/versions") + .then() + .statusCode(201) + .body("Version", equalTo("1")) + .body("DurableConfig.ExecutionTimeout", equalTo(3600)) + .body("DurableConfig.RetentionPeriodInDays", equalTo(7)); + + updateDurableConfig("durable-update-fn", "{\"ExecutionTimeout\": 7200}") + .statusCode(200) + .body("DurableConfig.ExecutionTimeout", equalTo(7200)) + .body("DurableConfig.RetentionPeriodInDays", equalTo(7)); + + updateDurableConfig("durable-update-fn", "{\"RetentionPeriodInDays\": 3, \"KMSKeyArn\": \"" + KMS_KEY_ARN + "\"}") + .statusCode(200) + .body("DurableConfig.ExecutionTimeout", equalTo(7200)) + .body("DurableConfig.RetentionPeriodInDays", equalTo(3)) + .body("DurableConfig.KMSKeyArn", equalTo(KMS_KEY_ARN)); + + updateDurableConfig("durable-update-fn", "{}") + .statusCode(200) + .body("DurableConfig.ExecutionTimeout", equalTo(7200)) + .body("DurableConfig.RetentionPeriodInDays", equalTo(3)); + + getConfiguration("durable-update-fn", "?Qualifier=1") + .statusCode(200) + .body("DurableConfig.ExecutionTimeout", equalTo(3600)) + .body("DurableConfig.RetentionPeriodInDays", equalTo(7)) + .body("DurableConfig", not(hasKey("KMSKeyArn"))); + } + + @Test + void updateCannotAddDurableConfigToAPlainFunction() { + createFunction("plain-stays-plain-fn", "").statusCode(201); + + updateDurableConfig("plain-stays-plain-fn", "{\"ExecutionTimeout\": 60}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", equalTo("You cannot add a durable configuration to a function that was " + + "originally created with no durable configuration")); + + getConfiguration("plain-stays-plain-fn") + .statusCode(200) + .body("$", not(hasKey("DurableConfig"))); + } + + private static ValidatableResponse updateDurableConfig(String name, String durableConfig) { + return updateConfiguration(name, "{\"DurableConfig\": " + durableConfig + "}"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java index fc2db7f616..c16bbfd149 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.lambda; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; @@ -14,6 +15,7 @@ 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.assertEquals; @@ -50,6 +52,27 @@ class LambdaServicePersistenceTest { assertTrue(third.getFunctionArn().endsWith(":3")); } + @Test + void durableConfigSurvivesRestartAndJsonRoundTrip() throws Exception { + SharedStorageFactory storage = new SharedStorageFactory(); + LambdaFunctionStore store = new LambdaFunctionStore(storage); + + LambdaService first = serviceWithStorage(store, storage); + Map request = baseRequest("durable-fn"); + request.put("DurableConfig", Map.of("ExecutionTimeout", 3600)); + first.createFunction(REGION, request); + + LambdaService reloaded = serviceWithStorage(store, storage); + LambdaFunction fn = reloaded.getFunction(REGION, "durable-fn"); + ObjectMapper mapper = new ObjectMapper(); + LambdaFunction copy = mapper.readValue(mapper.writeValueAsString(fn), LambdaFunction.class); + for (LambdaFunction function : List.of(fn, copy)) { + assertTrue(function.isDurable()); + assertEquals(3600, function.getDurableExecutionTimeout()); + assertEquals(14, function.getDurableRetentionPeriodInDays()); + } + } + @Test void eventInvokeConfigSurvivesRestartIncludingUpdates() { SharedStorageFactory storage = new SharedStorageFactory(); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java index 15a6a37268..cc2a0ba58b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java @@ -18,7 +18,7 @@ class LambdaStructureSerializationIntegrationTest { private static final String QUEUE_ARN = "arn:aws:sqs:us-east-1:000000000000:structure-queue"; private static final List FUNCTION_STRUCTURE_MEMBERS = List.of( "Environment", "EphemeralStorage", "TracingConfig", "DeadLetterConfig", - "VpcConfig", "SnapStart", "LoggingConfig", "ImageConfig"); + "VpcConfig", "SnapStart", "LoggingConfig", "ImageConfig", "DurableConfig"); @Test void createFunctionRejectsScalarStructureMembers() {