Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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());
}

Expand All @@ -137,35 +142,62 @@ 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;
}
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(
Expand All @@ -182,7 +214,8 @@ private void callback(DisposableServer server, ApplicationContext context) {

@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return eventType.isAssignableFrom(ContextRefreshedEvent.class);
return ContextRefreshedEvent.class.isAssignableFrom(eventType)
|| ContextClosedEvent.class.isAssignableFrom(eventType);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
}

Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;

/**
Expand Down Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -74,9 +77,37 @@ void stopWithCallbackStopsAndInvokesCallback() {
assertThat(called[0]).isTrue();
}

@SuppressWarnings("unchecked")
@Test
void supplierCompletingWhileSubscribingStopsExporter() {
List<Throwable> 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<Flux<Object>> supplier = Flux::never;
return exporter(Flux::never);
}

private static SupplierExporter exporter(Supplier<Flux<Object>> supplier) {
FunctionCatalog catalog = mock(FunctionCatalog.class);
when(catalog.lookup(eq("words"), any(String[].class))).thenReturn(supplier);

Expand Down
Loading