Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambda): persist version counters and event-invoke configs across restart (#1730)
Hector Venturaf8e8984c16b4
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.javaindex aa62063b0e..136abdfed4 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@@ -1,9 +1,12 @@package io.github.hectorvent.floci.services.lambda;+import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.StorageBackedMap;+import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;import io.github.hectorvent.floci.services.lambda.model.InvocationType;@@ -61,8 +64,9 @@ public class LambdaService {private final SqsEventSourcePoller poller;private final KinesisEventSourcePoller kinesisPoller;private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;- private final ConcurrentHashMap<String, Integer> versionCounters = new ConcurrentHashMap<>();- private final ConcurrentHashMap<String, FunctionEventInvokeConfig> eventInvokeConfigs = new ConcurrentHashMap<>();+ private final StorageFactory storageFactory;+ private Map<String, Integer> versionCounters = new ConcurrentHashMap<>();+ private Map<String, FunctionEventInvokeConfig> eventInvokeConfigs = new ConcurrentHashMap<>();/*** Per-function locks covering PutFunctionConcurrency,* DeleteFunctionConcurrency, and deleteFunction itself. Serializing the@@ -77,6 +81,7 @@ public class LambdaService {* emulator workload.*/private final ConcurrentHashMap<String, Object> concurrencyOpLocks = new ConcurrentHashMap<>();+ private final ConcurrentHashMap<String, Object> versionCounterLocks = new ConcurrentHashMap<>();/*** Package-private constructor for testing without CDI. Config defaults@@ -100,6 +105,17 @@ public class LambdaService {ZipExtractor zipExtractor,EmulatorConfig config,RegionResolver regionResolver) {+ this(functionStore, warmPool, codeStore, zipExtractor, config, regionResolver, null);+ }++ /** Package-private constructor for persistence tests: supplies a real storage factory. */+ LambdaService(LambdaFunctionStore functionStore,+ WarmPool warmPool,+ CodeStore codeStore,+ ZipExtractor zipExtractor,+ EmulatorConfig config,+ RegionResolver regionResolver,+ StorageFactory storageFactory) {this.functionStore = functionStore;this.executorService = null;this.concurrencyLimiter = new LambdaConcurrencyLimiter();@@ -115,6 +131,7 @@ public class LambdaService {this.poller = null;this.kinesisPoller = null;this.dynamodbStreamsPoller = null;+ this.storageFactory = storageFactory;}@Inject@@ -132,7 +149,8 @@ public class LambdaService {SqsService sqsService,SqsEventSourcePoller poller,KinesisEventSourcePoller kinesisPoller,- DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller) {+ DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,+ StorageFactory storageFactory) {this.functionStore = functionStore;this.executorService = executorService;this.concurrencyLimiter = concurrencyLimiter;@@ -148,6 +166,7 @@ public class LambdaService {this.poller = poller;this.kinesisPoller = kinesisPoller;this.dynamodbStreamsPoller = dynamodbStreamsPoller;+ this.storageFactory = storageFactory;}/** Package-private accessor for tests that want to assert limiter state directly. */@@ -155,12 +174,33 @@ public class LambdaService {return concurrencyLimiter;}+ @PostConstruct+ void init() {+ initializeStorage();+ rehydrateConcurrency();+ }++ /**+ * Version counters and event-invoke configs are durable Lambda state: a counter+ * lost on restart re-issues already-used version numbers from PublishVersion.+ * Wrapped through the same "lambda" storage key as the function store.+ */+ void initializeStorage() {+ if (storageFactory == null) {+ return; // keeps non-CDI unit tests working+ }+ this.versionCounters = new StorageBackedMap<>(storageFactory.create("lambda",+ "lambda-version-counters.json", new TypeReference<Map<String, Integer>>() {}));+ this.eventInvokeConfigs = new StorageBackedMap<>(storageFactory.create("lambda",+ "lambda-event-invoke-configs.json",+ new TypeReference<Map<String, FunctionEventInvokeConfig>>() {}));+ }+/*** Rehydrates reserved concurrency into the limiter from persisted function state.* Without this, restarts leave {@code totalReserved()=0} and allow validatePut /* unreserved-pool sizing to drift until each function is re-Put.*/- @PostConstructvoid rehydrateConcurrency() {if (concurrencyLimiter == null) {return;@@ -810,10 +850,25 @@ public class LambdaService {// ──────────────────────────── Versions ────────────────────────────+ /**+ * Locked get-increment-put: StorageBackedMap has no atomic merge, so the+ * sequence must not interleave or concurrent PublishVersion calls could issue+ * duplicate version numbers. The lock is per counter key (same pattern as+ * {@code concurrencyOpLocks}) so publishes of unrelated functions do not+ * serialize on the instance monitor for the storage round-trip.+ */+ private int nextVersionNumber(String counterKey) {+ synchronized (versionCounterLocks.computeIfAbsent(counterKey, k -> new Object())) {+ int next = versionCounters.getOrDefault(counterKey, 0) + 1;+ versionCounters.put(counterKey, next);+ return next;+ }+ }+public LambdaFunction publishVersion(String region, String functionName, String description) {LambdaFunction fn = getFunction(region, functionName);functionName = fn.getFunctionName();- int version = versionCounters.merge(region + "::" + functionName, 1, Integer::sum);+ int version = nextVersionNumber(region + "::" + functionName);LambdaFunction snapshot = new LambdaFunction();snapshot.setFunctionName(fn.getFunctionName());snapshot.setVersion(String.valueOf(version));@@ -1391,6 +1446,8 @@ public class LambdaService {}applyEventInvokeRequest(existing, request, false);existing.setLastModified(System.currentTimeMillis());+ // Re-put so StorageBackedMap routes the mutation through the backend+ eventInvokeConfigs.put(key, existing);return existing;}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.javaindex 7ebc1bc93a..79edc3d8bc 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/FunctionEventInvokeConfig.java@@ -33,6 +33,13 @@ public class FunctionEventInvokeConfig {return lastModifiedMillis / 1000.0;}+ // Deserialization counterpart so the timestamp survives a persisted-state reload;+ // without it "LastModified" falls into ignoreUnknown and resets to 0.+ @JsonProperty("LastModified")+ void setLastModifiedSeconds(double seconds) {+ this.lastModifiedMillis = Math.round(seconds * 1000);+ }+public String getFunctionArn() { return functionArn; }public void setFunctionArn(String functionArn) { this.functionArn = functionArn; }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.javanew file mode 100644index 0000000000..eef5856ba2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java@@ -0,0 +1,121 @@+package io.github.hectorvent.floci.services.lambda;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;+import io.github.hectorvent.floci.services.lambda.zip.CodeStore;+import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;+import org.junit.jupiter.api.Test;++import java.nio.file.Path;+import java.util.HashMap;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Verifies version counters and event-invoke configs survive a restart. Two service+ * instances share the same {@link StorageFactory} backend; the second simulates a+ * process restart reloading from disk. Without the counter persisting, PublishVersion+ * after a restart re-issues already-used version numbers.+ */+class LambdaServicePersistenceTest {++ private static final String REGION = "us-east-1";+ private static final String ACCOUNT_ID = "000000000000";++ @Test+ void publishVersionContinuesNumberingAfterRestart() {+ SharedStorageFactory storage = new SharedStorageFactory();+ LambdaFunctionStore store = new LambdaFunctionStore(storage);++ LambdaService first = serviceWithStorage(store, storage);+ first.createFunction(REGION, baseRequest("versioned-fn"));+ assertEquals("1", first.publishVersion(REGION, "versioned-fn", null).getVersion());+ assertEquals("2", first.publishVersion(REGION, "versioned-fn", null).getVersion());++ LambdaService reloaded = serviceWithStorage(store, storage);+ LambdaFunction third = reloaded.publishVersion(REGION, "versioned-fn", null);+ assertEquals("3", third.getVersion());+ assertTrue(third.getFunctionArn().endsWith(":3"));+ }++ @Test+ void eventInvokeConfigSurvivesRestartIncludingUpdates() {+ SharedStorageFactory storage = new SharedStorageFactory();+ LambdaFunctionStore store = new LambdaFunctionStore(storage);++ LambdaService first = serviceWithStorage(store, storage);+ first.createFunction(REGION, baseRequest("cfg-fn"));+ first.putEventInvokeConfig(REGION, "cfg-fn", null,+ new HashMap<>(Map.of("MaximumRetryAttempts", 2, "MaximumEventAgeInSeconds", 120)));+ // updateEventInvokeConfig mutates in place — the re-put must reach the backend+ first.updateEventInvokeConfig(REGION, "cfg-fn", null,+ new HashMap<>(Map.of("MaximumRetryAttempts", 0)));++ LambdaService reloaded = serviceWithStorage(store, storage);+ FunctionEventInvokeConfig cfg = reloaded.getEventInvokeConfig(REGION, "cfg-fn", null);+ assertEquals(0, cfg.getMaximumRetryAttempts());+ assertEquals(120, cfg.getMaximumEventAgeInSeconds());+ assertTrue(cfg.getLastModifiedSeconds() > 0,+ "LastModified must round-trip through persisted JSON");+ }++ @Test+ void deletedEventInvokeConfigDoesNotReappearAfterRestart() {+ SharedStorageFactory storage = new SharedStorageFactory();+ LambdaFunctionStore store = new LambdaFunctionStore(storage);++ LambdaService first = serviceWithStorage(store, storage);+ first.createFunction(REGION, baseRequest("gone-fn"));+ first.putEventInvokeConfig(REGION, "gone-fn", null,+ new HashMap<>(Map.of("MaximumRetryAttempts", 1)));+ first.deleteEventInvokeConfig(REGION, "gone-fn", null);++ LambdaService reloaded = serviceWithStorage(store, storage);+ assertThrows(Exception.class, () -> reloaded.getEventInvokeConfig(REGION, "gone-fn", null));+ }++ private static LambdaService serviceWithStorage(LambdaFunctionStore store, StorageFactory storage) {+ LambdaService service = new LambdaService(store, new WarmPool(),+ new CodeStore(Path.of("target/test-data/lambda-code")),+ new ZipExtractor(), null, new RegionResolver(REGION, "000000000000"), storage);+ service.initializeStorage();+ return service;+ }++ private static Map<String, Object> baseRequest(String name) {+ return new HashMap<>(Map.of(+ "FunctionName", name,+ "Runtime", "nodejs20.x",+ "Role", "arn:aws:iam::000000000000:role/test-role",+ "Handler", "index.handler"+ ));+ }++ private static final class SharedStorageFactory extends StorageFactory {+ private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();++ private SharedStorageFactory() {+ super(null, null);+ }++ @Override+ @SuppressWarnings("unchecked")+ public <V> StorageBackend<String, V> create(String serviceName,+ String fileName,+ TypeReference<Map<String, V>> typeReference) {+ // Wrap like the production factory does so the tests exercise the+ // account-prefixed key space, not a bare backend.+ return (StorageBackend<String, V>) stores.computeIfAbsent(fileName,+ ignored -> new AccountAwareStorageBackend<V>(new InMemoryStorage<>(), null, ACCOUNT_ID));+ }+ }+}