diff --git a/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/loadbalancer.adoc b/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/loadbalancer.adoc index 3eb853ed7..65dd219db 100644 --- a/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/loadbalancer.adoc +++ b/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/loadbalancer.adoc @@ -46,9 +46,8 @@ spring: WARNING: If using the `lb()` filter, it needs to be after any filter that manipulates the path such as `setPath()` or `stripPrefix()`, otherwise the resulting url could be incorrect. The `lb:` scheme handler in configuration, automatically puts the filter in the highest precedence order. -NOTE: By default, when a service instance cannot be found by the `ReactorLoadBalancer`, a `503` is returned. -// TODO: implement use404 -// You can configure the gateway to return a `404` by setting `spring.cloud.gateway.loadbalancer.use404=true`. +NOTE: By default, when a service instance cannot be found by the `LoadBalancerClient`, a `503` is returned. +You can configure the gateway to return a `404` when no service instance is found by setting `spring.cloud.gateway.server.webmvc.loadbalancer.use404=true`. NOTE: The `isSecure` value of the `ServiceInstance` returned from the `LoadBalancerClient` overrides the scheme specified in the request made to the Gateway. diff --git a/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/config/GatewayLoadBalancerProperties.java b/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/config/GatewayLoadBalancerProperties.java new file mode 100644 index 000000000..797a66a7c --- /dev/null +++ b/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/config/GatewayLoadBalancerProperties.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.gateway.server.mvc.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Configuration for the WebMVC load balancer filter. + * + * @author joecqupt + */ +@ConfigurationProperties(GatewayMvcProperties.PREFIX + ".loadbalancer") +public class GatewayLoadBalancerProperties { + + private boolean use404; + + public boolean isUse404() { + return use404; + } + + public void setUse404(boolean use404) { + this.use404 = use404; + } + +} diff --git a/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/FilterAutoConfiguration.java b/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/FilterAutoConfiguration.java index f0065bfdd..35c9ed75b 100644 --- a/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/FilterAutoConfiguration.java +++ b/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/FilterAutoConfiguration.java @@ -27,7 +27,9 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; +import org.springframework.cloud.gateway.server.mvc.config.GatewayLoadBalancerProperties; import org.springframework.cloud.gateway.server.mvc.config.GatewayMvcProperties; import org.springframework.cloud.gateway.server.mvc.config.RouteProperties; import org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctionDefinition; @@ -74,6 +76,7 @@ public CircuitBreakerFilterFunctions.FilterSupplier circuitBreakerFilterFunction @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LoadBalancerClient.class) + @EnableConfigurationProperties(GatewayLoadBalancerProperties.class) public static class LoadBalancerHandlerConfiguration { @Bean diff --git a/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctions.java b/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctions.java index 33b40ebc2..0502d2d9e 100644 --- a/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctions.java +++ b/spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctions.java @@ -40,11 +40,13 @@ import org.springframework.cloud.client.loadbalancer.RequestDataContext; import org.springframework.cloud.client.loadbalancer.ResponseData; import org.springframework.cloud.gateway.server.mvc.common.MvcUtils; +import org.springframework.cloud.gateway.server.mvc.config.GatewayLoadBalancerProperties; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import org.springframework.http.HttpStatus; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.function.HandlerFilterFunction; import org.springframework.web.servlet.function.ServerResponse; @@ -89,10 +91,13 @@ public static HandlerFilterFunction lb(String se if (retrievedInstance == null) { supportedLifecycleProcessors.forEach(lifecycle -> lifecycle .onComplete(new CompletionContext<>(CompletionContext.Status.DISCARD, lbRequest))); - throw new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE, - "Unable to find instance for " + serviceId); - // throw NotFoundException.create(properties.isUse404(), "Unable to find - // instance for " + serviceId); + String message = "Unable to find instance for " + serviceId; + GatewayLoadBalancerProperties properties = getApplicationContext(request) + .getBean(GatewayLoadBalancerProperties.class); + if (properties.isUse404()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, message); + } + throw new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE, message); } URI uri = request.uri(); diff --git a/spring-cloud-gateway-server-webmvc/src/test/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctionsTests.java b/spring-cloud-gateway-server-webmvc/src/test/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctionsTests.java new file mode 100644 index 000000000..c3600bea7 --- /dev/null +++ b/spring-cloud-gateway-server-webmvc/src/test/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctionsTests.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.gateway.server.mvc.filter; + +import java.util.Collections; +import java.util.List; +import java.util.stream.StreamSupport; + +import org.junit.jupiter.api.Test; + +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; +import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle; +import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; +import org.springframework.cloud.gateway.server.mvc.config.GatewayLoadBalancerProperties; +import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverters; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockServletContext; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.servlet.function.ServerRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Tests for the WebMVC load balancer filter's missing-instance response. + * + * @author joecqupt + */ +class LoadBalancerFilterFunctionsTests { + + private final List> converters = StreamSupport + .stream(HttpMessageConverters.forServer().registerDefaults().build().spliterator(), false) + .toList(); + + @Test + void returns503WhenNoInstanceByDefault() { + ServerRequest request = request(new GatewayLoadBalancerProperties()); + + assertThatThrownBy(() -> LoadBalancerFilterFunctions.lb("orders").filter(request, ignored -> null)) + .isInstanceOf(HttpServerErrorException.class) + .satisfies(error -> assertThat(((HttpServerErrorException) error).getStatusCode()) + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE)); + } + + @Test + void returns404WhenNoInstanceAndUse404Enabled() { + GatewayLoadBalancerProperties properties = new GatewayLoadBalancerProperties(); + properties.setUse404(true); + ServerRequest request = request(properties); + + assertThatThrownBy(() -> LoadBalancerFilterFunctions.lb("orders").filter(request, ignored -> null)) + .isInstanceOf(ResponseStatusException.class) + .satisfies(error -> assertThat(((ResponseStatusException) error).getStatusCode()) + .isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void bindsUse404Property() { + new ApplicationContextRunner() + .withUserConfiguration(FilterAutoConfiguration.LoadBalancerHandlerConfiguration.class) + .withPropertyValues("spring.cloud.gateway.server.webmvc.loadbalancer.use404=true") + .run(context -> assertThat(context.getBean(GatewayLoadBalancerProperties.class).isUse404()).isTrue()); + } + + private ServerRequest request(GatewayLoadBalancerProperties properties) { + MockHttpServletRequest servletRequest = MockMvcRequestBuilders.get("/orders") + .buildRequest(new MockServletContext()); + WebApplicationContext applicationContext = mock(WebApplicationContext.class); + LoadBalancerClientFactory clientFactory = mock(LoadBalancerClientFactory.class); + LoadBalancerClient loadBalancerClient = mock(LoadBalancerClient.class); + servletRequest.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext); + when(applicationContext.getBean(LoadBalancerClientFactory.class)).thenReturn(clientFactory); + when(applicationContext.getBean(GatewayLoadBalancerProperties.class)).thenReturn(properties); + when(clientFactory.getInstances("orders", LoadBalancerLifecycle.class)).thenReturn(Collections.emptyMap()); + when(clientFactory.getProperties("orders")).thenReturn(new LoadBalancerProperties()); + when(clientFactory.getInstance("orders", LoadBalancerClient.class)).thenReturn(loadBalancerClient); + return ServerRequest.create(servletRequest, converters); + } + +}