From fda43579aa42c292dbdcdc5698696d4f0d32e7ac Mon Sep 17 00:00:00 2001 From: seonwoo_jung <79202163+seonwooj0810@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:21:52 +0900 Subject: [PATCH] GH-1574 Fix SupplierExporter and FunctionEndpointInitializer lifecycle edge cases Mark SupplierExporter as running before subscribing and tolerate a missing subscription in stop(), so a stream that completes while subscribing no longer fails and leaves the exporter marked as running. Do not fail in FunctionEndpointInitializer when there is no WebExceptionHandler or HttpHandler bean. Stop the HTTP server when its application context is closed. The startup thread has to stay non-daemon since it keeps the JVM alive while the server is running, but it now ends together with the context. Resolves #1574 Signed-off-by: seonwoo_jung <79202163+seonwooj0810@users.noreply.github.com> --- .../function/FunctionEndpointInitializer.java | 41 +++++++++++++-- .../function/web/source/SupplierExporter.java | 17 ++++-- .../FunctionEndpointInitializerTests.java | 52 +++++++++++++++++++ .../web/source/SupplierExporterTests.java | 35 ++++++++++++- 4 files changed, 134 insertions(+), 11 deletions(-) diff --git a/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializer.java b/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializer.java index 71fbfbe92..e624f3c58 100644 --- a/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializer.java +++ b/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializer.java @@ -46,6 +46,8 @@ import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ApplicationEvent; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.event.ApplicationContextEvent; +import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.SmartApplicationListener; import org.springframework.context.support.GenericApplicationContext; @@ -63,6 +65,7 @@ import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.function.server.ServerResponse.BodyBuilder; +import org.springframework.web.reactive.handler.WebFluxResponseStatusExceptionHandler; import org.springframework.web.server.WebExceptionHandler; import org.springframework.web.server.adapter.HttpWebHandlerAdapter; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; @@ -115,8 +118,10 @@ private void registerEndpoint(GenericApplicationContext context) { } private HttpWebHandlerAdapter httpHandler(GenericApplicationContext context) { + WebExceptionHandler exceptionHandler = context.getBeanProvider(WebExceptionHandler.class).stream().findFirst() + .orElseGet(WebFluxResponseStatusExceptionHandler::new); return (HttpWebHandlerAdapter) RouterFunctions.toHttpHandler(context.getBean(RouterFunction.class), - HandlerStrategies.empty().exceptionHandler(context.getBeansOfType(WebExceptionHandler.class).values().iterator().next()) + HandlerStrategies.empty().exceptionHandler(exceptionHandler) .codecs(config -> config.registerDefaults(true)).build()); } @@ -137,16 +142,25 @@ private static class ServerListener implements SmartApplicationListener { private final GenericApplicationContext context; + private volatile DisposableServer server; + + private volatile boolean closed; + ServerListener(GenericApplicationContext context) { this.context = context; } @Override public void onApplicationEvent(ApplicationEvent event) { - ApplicationContext context = ((ContextRefreshedEvent) event).getApplicationContext(); + ApplicationContext context = ((ApplicationContextEvent) event).getApplicationContext(); if (context != this.context) { return; } + if (event instanceof ContextClosedEvent) { + this.closed = true; + stopServer(); + return; + } if (!ClassUtils.isPresent("org.springframework.http.server.reactive.HttpHandler", null)) { logger.info("No web server classes found so no server to start"); return; @@ -154,18 +168,36 @@ public void onApplicationEvent(ApplicationEvent event) { int port = Integer.parseInt(context.getEnvironment().resolvePlaceholders("${server.port:${PORT:8080}}")); String address = context.getEnvironment().resolvePlaceholders("${server.address:0.0.0.0}"); if (port >= 0) { - HttpHandler handler = context.getBeansOfType(HttpHandler.class).values().iterator().next(); + HttpHandler handler = context.getBeanProvider(HttpHandler.class).stream().findFirst().orElse(null); + if (handler == null) { + logger.info("No HttpHandler found so no server to start"); + return; + } ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); HttpServer httpServer = HttpServer.create().host(address).port(port).handle(adapter); Thread thread = new Thread( () -> httpServer.bindUntilJavaShutdown(Duration.ofSeconds(60), (server) -> callback(server, context)), "server-startup"); + // keeps the JVM alive until the server is stopped thread.setDaemon(false); thread.start(); } } + private void stopServer() { + DisposableServer server = this.server; + if (server != null) { + server.dispose(); + } + } + private void callback(DisposableServer server, ApplicationContext context) { + this.server = server; + if (this.closed) { + // closed while the server was starting + stopServer(); + return; + } logger.info("HTTP server started on port: " + server.port()); if (context instanceof ConfigurableApplicationContext configurableContext) { configurableContext.getEnvironment().getPropertySources().addFirst( @@ -182,7 +214,8 @@ private void callback(DisposableServer server, ApplicationContext context) { @Override public boolean supportsEventType(Class eventType) { - return eventType.isAssignableFrom(ContextRefreshedEvent.class); + return ContextRefreshedEvent.class.isAssignableFrom(eventType) + || ContextClosedEvent.class.isAssignableFrom(eventType); } } diff --git a/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/source/SupplierExporter.java b/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/source/SupplierExporter.java index 2ee9dd0c6..32dd1f5d9 100644 --- a/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/source/SupplierExporter.java +++ b/spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/source/SupplierExporter.java @@ -106,13 +106,17 @@ public void start() { suppliersPresent = true; } if (suppliersPresent) { - this.subscription = streams + // the stream may complete (and call stop()) while subscribing + this.ok = true; + this.running = true; + Disposable subscription = streams .retryWhen(Retry.backoff(5, Duration.ofSeconds(1))) .doOnComplete(this::stop) .subscribe(); - - this.ok = true; - this.running = true; + this.subscription = subscription; + if (!this.running) { + subscription.dispose(); + } } } @@ -124,7 +128,10 @@ public boolean isOk() { public void stop() { logger.info("Stopping"); this.running = false; - this.subscription.dispose(); + Disposable subscription = this.subscription; + if (subscription != null) { + subscription.dispose(); + } } @Override diff --git a/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializerTests.java b/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializerTests.java index 8ab133215..b48e57959 100644 --- a/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializerTests.java +++ b/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/function/FunctionEndpointInitializerTests.java @@ -16,6 +16,8 @@ package org.springframework.cloud.function.web.function; +import java.net.ConnectException; +import java.net.Socket; import java.net.URI; import java.time.Duration; import java.util.HashMap; @@ -32,9 +34,11 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.resttestclient.TestRestTemplate; +import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.cloud.function.context.FunctionRegistration; import org.springframework.cloud.function.context.FunctionalSpringApplication; import org.springframework.cloud.function.context.catalog.FunctionTypeUtils; +import org.springframework.cloud.function.context.config.ContextFunctionCatalogInitializer; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @@ -46,9 +50,15 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.server.WebExceptionHandler; +import org.springframework.web.server.adapter.HttpWebHandlerAdapter; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatNoException; import static org.awaitility.Awaitility.await; /** @@ -174,6 +184,48 @@ public void testGetWithtSupplier() throws Exception { assertThat(response.getBody()).isEqualTo("Jim Lahey"); } + @Test + public void testServerStopsWhenContextIsClosed() { + ConfigurableApplicationContext context = FunctionalSpringApplication.run(ApplicationConfiguration.class, "--server.port=0"); + await().atMost(Duration.ofSeconds(5)) + .until(() -> context.getEnvironment().getProperty("local.server.port") != null); + int port = Integer.parseInt(context.getEnvironment().getProperty("local.server.port")); + + context.close(); + + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> + assertThatExceptionOfType(ConnectException.class).isThrownBy(() -> new Socket("localhost", port).close())); + } + + @Test + public void testMissingWebExceptionHandler() { + try (GenericApplicationContext context = functionalContext("server.port=-1")) { + context.removeBeanDefinition(context.getBeanFactory().getBeanNamesForType(WebExceptionHandler.class)[0]); + + context.refresh(); + + WebTestClient.bindToWebHandler(context.getBean(HttpWebHandlerAdapter.class)).build() + .post().uri("/foo").bodyValue("stressed").exchange().expectStatus().isNotFound(); + } + } + + @Test + public void testMissingHttpHandler() { + try (GenericApplicationContext context = functionalContext("server.port=0")) { + context.removeBeanDefinition(WebHttpHandlerBuilder.WEB_HANDLER_BEAN_NAME); + + assertThatNoException().isThrownBy(context::refresh); + } + } + + private GenericApplicationContext functionalContext(String... properties) { + GenericApplicationContext context = new GenericApplicationContext(); + TestPropertyValues.of(properties).and("spring.functional.enabled=true").applyTo(context); + new ContextFunctionCatalogInitializer().initialize(context); + new FunctionEndpointInitializer().initialize(context); + return context; + } + private int startServerAndWaitForPort(Class primaryAppConfig, boolean functional, String... args) throws InterruptedException { String[] allArgs = new String[args.length + 1]; allArgs[0] = "--server.port=0"; diff --git a/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/source/SupplierExporterTests.java b/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/source/SupplierExporterTests.java index ce2c843a1..ea412094d 100644 --- a/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/source/SupplierExporterTests.java +++ b/spring-cloud-function-web/src/test/java/org/springframework/cloud/function/web/source/SupplierExporterTests.java @@ -17,10 +17,13 @@ package org.springframework.cloud.function.web.source; import java.net.URI; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; +import reactor.core.publisher.Hooks; import org.springframework.cloud.function.context.FunctionCatalog; import org.springframework.http.HttpHeaders; @@ -74,9 +77,37 @@ void stopWithCallbackStopsAndInvokesCallback() { assertThat(called[0]).isTrue(); } - @SuppressWarnings("unchecked") + @Test + void supplierCompletingWhileSubscribingStopsExporter() { + List dropped = new CopyOnWriteArrayList<>(); + Hooks.onErrorDropped(dropped::add); + try { + SupplierExporter exporter = exporter(Flux::empty); + + exporter.start(); + + assertThat(exporter.isRunning()).isFalse(); + assertThat(dropped).isEmpty(); + } + finally { + Hooks.resetOnErrorDropped(); + } + } + + @Test + void stopBeforeStartIsNoOp() { + SupplierExporter exporter = exporterWithNeverEndingSupplier(); + + exporter.stop(); + + assertThat(exporter.isRunning()).isFalse(); + } + private static SupplierExporter exporterWithNeverEndingSupplier() { - Supplier> supplier = Flux::never; + return exporter(Flux::never); + } + + private static SupplierExporter exporter(Supplier> supplier) { FunctionCatalog catalog = mock(FunctionCatalog.class); when(catalog.lookup(eq("words"), any(String[].class))).thenReturn(supplier);