From 468e943c832d6e325d401f76984507bc07d1adb0 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Mon, 27 Jul 2026 22:23:50 -0500 Subject: [PATCH] fix(elbv2): move persisted-listener restore out of @PostConstruct (#2015) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(elbv2): move persisted-listener restore out of @PostConstruct ElbV2Service called back into itself through its own CDI client proxy while it was still being constructed. rebuildIndexes(), reached from the @PostConstruct initializeStorage(), called dataPlane.startListener() for every restored listener; ElbV2DataPlane.binding() then called elbV2Service.getLoadBalancer(), and because Arc had not yet registered the instance in the ApplicationScoped context the proxy started another bean creation. That recursed until the process died. Only reproducible after a restart with persistent storage: on a fresh boot the listener map is empty, so rebuildIndexes() never reaches startListener and the callback never happens. rebuildIndexes() now only builds the in-memory indexes. Starting the data plane and the health checks moved to restorePersistedRuntime(), invoked from EmulatorLifecycle after storageFactory.loadAll() alongside the four services that already restore persisted runtime there. With the bean fully constructed before any listener starts, the callback resolves normally. The blast radius was wider than the issue title: the bean is created lazily on first use, so after a restart every ELBv2 operation failed, not just DeleteStack. DescribeLoadBalancers and DescribeTargetGroups both returned 500. Note the symptom changed with #1931: the storage dedupe removed the per-level allocation, so current main raises StackOverflowError where 1.5.32 exhausted the heap and was OOM-killed. Closes #1913 * test(elbv2): cover the enabled and disabled lifecycle restore paths elbv2 was stubbed disabled in setup, so nothing exercised the new EmulatorLifecycle call: dropping it entirely would have left the suite green. Pin both halves of the gate — restore runs after loadAll when elbv2 is enabled, and does not run when it is disabled. Verified the ordering assertion fails with 'Wanted but not invoked' when the lifecycle call is removed. Refs #1913 --- .../floci/lifecycle/EmulatorLifecycle.java | 7 +++ .../floci/services/elbv2/ElbV2Service.java | 30 ++++++++++--- .../lifecycle/EmulatorLifecycleTest.java | 36 +++++++++++++++- .../services/elbv2/ElbV2ServiceTest.java | 43 ++++++++++++++++++- 4 files changed, 108 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index 9d554a8629..58af767a5c 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerMan import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager; import io.github.hectorvent.floci.services.pipes.PipesService; import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker; +import io.github.hectorvent.floci.services.elbv2.ElbV2Service; import io.github.hectorvent.floci.services.rds.RdsService; import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager; import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager; @@ -75,6 +76,7 @@ public class EmulatorLifecycle { private final NeptuneProxyManager neptuneProxyManager; private final RabbitMqManager rabbitMqManager; private final RdsService rdsService; + private final ElbV2Service elbV2Service; private final InitializationHooksRunner initializationHooksRunner; private final SqsEventSourcePoller sqsPoller; private final KinesisEventSourcePoller kinesisPoller; @@ -103,6 +105,7 @@ public class EmulatorLifecycle { NeptuneProxyManager neptuneProxyManager, RabbitMqManager rabbitMqManager, RdsService rdsService, + ElbV2Service elbV2Service, InitializationHooksRunner initializationHooksRunner, SqsEventSourcePoller sqsPoller, KinesisEventSourcePoller kinesisPoller, @@ -130,6 +133,7 @@ public class EmulatorLifecycle { this.neptuneProxyManager = neptuneProxyManager; this.rabbitMqManager = rabbitMqManager; this.rdsService = rdsService; + this.elbV2Service = elbV2Service; this.initializationHooksRunner = initializationHooksRunner; this.sqsPoller = sqsPoller; this.kinesisPoller = kinesisPoller; @@ -173,6 +177,9 @@ public class EmulatorLifecycle { dynamodbStreamsPoller.startPersistedPollers(); pipesService.startPersistedPollers(); rdsService.restorePersistedRuntime(); + if (config.services().elbv2().enabled()) { + elbV2Service.restorePersistedRuntime(); + } if (config.services().ec2().enabled() && !config.services().ec2().mock()) { ec2MetadataServer.start().exceptionally(ex -> { diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java index b32a2479e1..6936ccd34b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java @@ -101,6 +101,13 @@ public class ElbV2Service { } } + /** + * Rebuilds the in-memory indexes from the storage-backed maps. Pure and in-process on purpose: + * nothing reachable from {@link #initializeStorage()} may call an injected collaborator, because + * {@link ElbV2DataPlane} calls back into this service and CDI has not registered the instance in + * the ApplicationScoped context yet — re-entering bean creation instead (issue #1913). Runtime + * side effects belong in {@link #restorePersistedRuntime()}. + */ private void rebuildIndexes() { lbToListeners.clear(); @@ -123,7 +130,20 @@ public class ElbV2Service { for (TargetGroup targetGroup : regionEntry.getValue().values()) { tgToLbs.computeIfAbsent(targetGroup.getTargetGroupArn(), k -> ConcurrentHashMap.newKeySet()) .addAll(targetGroup.getLoadBalancerArns()); - if (healthChecker != null) { + } + } + } + + /** + * Brings the data plane and health checks back up for state restored from disk. Invoked from + * {@code EmulatorLifecycle} once the bean is fully constructed, alongside the other services that + * restore persisted runtime after {@code storageFactory.loadAll()}. + */ + public void restorePersistedRuntime() + { + if (healthChecker != null) { + for (Map regionTargetGroups : targetGroups.values()) { + for (TargetGroup targetGroup : regionTargetGroups.values()) { healthChecker.startMonitoring(targetGroup); if (!targetGroup.getTargets().isEmpty()) { healthChecker.addTargets(targetGroup.getTargetGroupArn(), targetGroup.getTargets(), targetGroup); @@ -131,10 +151,10 @@ public class ElbV2Service { } } } - for (Map.Entry> regionEntry : listeners.entrySet()) { - String region = regionEntry.getKey(); - for (Listener listener : regionEntry.getValue().values()) { - if (dataPlane != null) { + if (dataPlane != null) { + for (Map.Entry> regionEntry : listeners.entrySet()) { + String region = regionEntry.getKey(); + for (Listener listener : regionEntry.getValue().values()) { dataPlane.startListener(listener, region, getListenerRules(region, listener.getListenerArn())); } } diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index ea3473abdd..9193228408 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -57,6 +57,7 @@ class EmulatorLifecycleTest { @Mock private EmulatorConfig.StorageConfig storageConfig; @Mock private EmulatorConfig.ServicesConfig servicesConfig; @Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig; + @Mock private EmulatorConfig.ElbV2ServiceConfig elbv2ServiceConfig; @Mock private ElastiCacheContainerManager elastiCacheContainerManager; @Mock private ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager; @Mock private ElastiCacheProxyManager elastiCacheProxyManager; @@ -69,6 +70,7 @@ class EmulatorLifecycleTest { @Mock private NeptuneProxyManager neptuneProxyManager; @Mock private io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager rabbitMqManager; @Mock private RdsService rdsService; + @Mock private io.github.hectorvent.floci.services.elbv2.ElbV2Service elbV2Service; @Mock private InitializationHooksRunner initializationHooksRunner; @Mock private SqsEventSourcePoller sqsPoller; @Mock private KinesisEventSourcePoller kinesisPoller; @@ -90,6 +92,8 @@ class EmulatorLifecycleTest { Mockito.lenient().when(config.services()).thenReturn(servicesConfig); Mockito.lenient().when(servicesConfig.ec2()).thenReturn(ec2ServiceConfig); Mockito.lenient().when(ec2ServiceConfig.enabled()).thenReturn(false); + Mockito.lenient().when(servicesConfig.elbv2()).thenReturn(elbv2ServiceConfig); + Mockito.lenient().when(elbv2ServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(config.tls()).thenReturn(tlsConfig); Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false); @@ -99,7 +103,7 @@ class EmulatorLifecycleTest { elastiCacheProxyManager, rdsContainerManager, rdsProxyManager, memoryDbContainerManager, memoryDbProxyManager, docDbContainerManager, neptuneContainerManager, neptuneProxyManager, - rabbitMqManager, rdsService, + rabbitMqManager, rdsService, elbV2Service, initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState, schemaCreationWorker, containerTeardowns, persistentPathValidator); @@ -129,6 +133,36 @@ class EmulatorLifecycleTest { inOrder.verify(rdsService).restorePersistedRuntime(); } + @Test + @DisplayName("Should restore ELBv2 persisted runtime after loading storage when elbv2 is enabled") + void shouldRestoreElbV2PersistedRuntimeAfterStorageLoad() { + // The restore has to happen after the bean is constructed, not from @PostConstruct, or + // ElbV2DataPlane's callback re-enters bean creation (#1913). Pin the ordering so the call + // cannot be dropped or moved back into construction unnoticed. + stubStorageConfig(); + when(elbv2ServiceConfig.enabled()).thenReturn(true); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + var inOrder = Mockito.inOrder(storageFactory, elbV2Service); + inOrder.verify(storageFactory).loadAll(); + inOrder.verify(elbV2Service).restorePersistedRuntime(); + } + + @Test + @DisplayName("Should not restore ELBv2 persisted runtime when elbv2 is disabled") + void shouldNotRestoreElbV2PersistedRuntimeWhenDisabled() { + stubStorageConfig(); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + Mockito.verify(elbV2Service, Mockito.never()).restorePersistedRuntime(); + } + @Test @DisplayName("Should validate the persistent path after BOOT hooks and before loading storage") void shouldValidatePersistentPathBeforeStorageLoad() { diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java index da6e479553..2d7d316b83 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java @@ -40,6 +40,7 @@ import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @@ -179,6 +180,9 @@ class ElbV2ServiceTest { assertTrue(reloadedRules.stream().anyMatch(candidate -> "10".equals(candidate.getPriority()))); assertEquals("test", reloaded.describeTags(List.of(lbArn)).get(lbArn).get("env")); assertThrows(AwsException.class, () -> reloaded.deleteTargetGroup(REGION, tgArn)); + + // Data-plane and health-check startup is deliberately not part of construction (#1913). + reloaded.restorePersistedRuntime(); verify(reloadedHealthChecker).startMonitoring(any(TargetGroup.class)); ArgumentCaptor> targetsCaptor = ArgumentCaptor.captor(); verify(reloadedHealthChecker).addTargets(eq(tgArn), targetsCaptor.capture(), any(TargetGroup.class)); @@ -193,7 +197,41 @@ class ElbV2ServiceTest { } @Test - void initializeStorageStartsPersistedListenersWithoutTargetGroups() { + void initializeStorageDoesNotTouchCollaborators() { + // #1913: ElbV2DataPlane.binding() calls back into this service, and during @PostConstruct the + // ApplicationScoped context has no instance yet — so CDI re-enters bean creation and recurses + // until the stack (or, before the storage dedupe in #1931, the heap) is gone. Nothing reachable + // from initializeStorage() may call an injected collaborator. A mock cannot reproduce the + // recursion, since it never calls back, so assert the absence of the interaction instead. + SharedStorageFactory storageFactory = new SharedStorageFactory(); + ElbV2Service first = serviceWithStorage(storageFactory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class)); + String lbArn = first.createLoadBalancer( + REGION, "recursion-lb", "internal", "application", "ipv4", + ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn(); + String tgArn = first.createTargetGroup( + REGION, "recursion-tg", "HTTP", "HTTP1", 8080, "vpc-a", "instance", + "HTTP", "traffic-port", true, "/health", 15, 5, 3, 2, "200", + "ipv4", Map.of()).getTargetGroupArn(); + String listenerArn = first.createListener( + REGION, lbArn, "HTTP", 9090, null, List.of(), + List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn(); + + ElbV2DataPlane reloadedDataPlane = mock(ElbV2DataPlane.class); + ElbV2HealthChecker reloadedHealthChecker = mock(ElbV2HealthChecker.class); + ElbV2Service reloaded = serviceWithStorage(storageFactory, reloadedDataPlane, reloadedHealthChecker); + + verifyNoInteractions(reloadedDataPlane, reloadedHealthChecker); + + reloaded.restorePersistedRuntime(); + + ArgumentCaptor listenerCaptor = ArgumentCaptor.captor(); + verify(reloadedDataPlane).startListener(listenerCaptor.capture(), eq(REGION), anyList()); + assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn()); + verify(reloadedHealthChecker).startMonitoring(any(TargetGroup.class)); + } + + @Test + void restorePersistedRuntimeStartsPersistedListenersWithoutTargetGroups() { SharedStorageFactory storageFactory = new SharedStorageFactory(); ElbV2Service first = serviceWithStorage(storageFactory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class)); String lbArn = first.createLoadBalancer( @@ -204,7 +242,8 @@ class ElbV2ServiceTest { List.of(), List.of(), Map.of()).getListenerArn(); ElbV2DataPlane reloadedDataPlane = mock(ElbV2DataPlane.class); - serviceWithStorage(storageFactory, reloadedDataPlane, mock(ElbV2HealthChecker.class)); + ElbV2Service reloaded = serviceWithStorage(storageFactory, reloadedDataPlane, mock(ElbV2HealthChecker.class)); + reloaded.restorePersistedRuntime(); ArgumentCaptor listenerCaptor = ArgumentCaptor.captor(); verify(reloadedDataPlane).startListener(listenerCaptor.capture(), eq(REGION), anyList());