This is an automated email from the ASF dual-hosted git repository.

Aias00 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shenyu.git


The following commit(s) were added to refs/heads/master by this push:
     new 3569a77fe6 fix(httpclient): fail over on upstream server errors (#7097)
3569a77fe6 is described below

commit 3569a77fe685eacf3f2a08785c0a89703eb10efa
Author: Liming Deng <[email protected]>
AuthorDate: Thu Oct 1 06:29:57 2026 +0800

    fix(httpclient): fail over on upstream server errors (#7097)
---
 .../httpclient/AbstractHttpClientPlugin.java       |  5 ++++
 .../plugin/httpclient/NettyHttpClientPlugin.java   |  4 +++
 .../shenyu/plugin/httpclient/WebClientPlugin.java  |  3 ++
 .../exception/ShenyuUpstreamStatusException.java   | 35 ++++++++++++++++++++++
 .../httpclient/NettyHttpClientPluginTest.java      | 24 +++++++++++++++
 .../plugin/httpclient/WebClientPluginTest.java     | 24 +++++++++------
 6 files changed, 86 insertions(+), 9 deletions(-)

diff --git 
a/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/AbstractHttpClientPlugin.java
 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/AbstractHttpClientPlugin.java
index 085d38766f..0e8a084a25 100644
--- 
a/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/AbstractHttpClientPlugin.java
+++ 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/AbstractHttpClientPlugin.java
@@ -170,6 +170,11 @@ public abstract class AbstractHttpClientPlugin<R> 
implements ShenyuPlugin {
         return !"GET".equals(httpMethod) && !"HEAD".equals(httpMethod);
     }
 
+    protected boolean shouldFailover(final ServerWebExchange exchange, final 
int statusCode) {
+        String retryStrategy = exchange.getAttribute(Constants.RETRY_STRATEGY);
+        return RetryEnum.FAILOVER.getName().equals(retryStrategy) && 
statusCode >= 500 && statusCode < 600;
+    }
+
     protected void duplicateHeaders(final ServerWebExchange exchange, final 
HttpHeaders headers, final UniqueHeaderEnum uniqueHeaderEnum) {
         final String duplicateHeader = 
exchange.getAttribute(uniqueHeaderEnum.getName());
         if (StringUtils.isEmpty(duplicateHeader)) {
diff --git 
a/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPlugin.java
 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPlugin.java
index 1038ee3d4d..6beabcfa6b 100644
--- 
a/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPlugin.java
+++ 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPlugin.java
@@ -23,6 +23,7 @@ import org.apache.commons.lang3.StringUtils;
 import org.apache.shenyu.common.constant.Constants;
 import org.apache.shenyu.common.enums.PluginEnum;
 import org.apache.shenyu.common.enums.UniqueHeaderEnum;
+import 
org.apache.shenyu.plugin.httpclient.exception.ShenyuUpstreamStatusException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.core.io.buffer.DataBuffer;
@@ -103,6 +104,9 @@ public class NettyHttpClientPlugin extends 
AbstractHttpClientPlugin<HttpClientRe
                     if (LOG.isDebugEnabled()) {
                         LOG.debug("NettyHttpClient response: status={}", 
res.status().code());
                     }
+                    if (shouldFailover(exchange, res.status().code())) {
+                        return 
connection.inbound().receive().then(Mono.error(new 
ShenyuUpstreamStatusException(res.status().code())));
+                    }
                     
exchange.getAttributes().put(Constants.CLIENT_RESPONSE_ATTR, res);
                     
exchange.getAttributes().put(Constants.CLIENT_RESPONSE_CONN_ATTR, connection);
                     final ServerHttpResponse response = exchange.getResponse();
diff --git 
a/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/WebClientPlugin.java
 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/WebClientPlugin.java
index 4ea979dcfb..949623b455 100644
--- 
a/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/WebClientPlugin.java
+++ 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/WebClientPlugin.java
@@ -22,6 +22,7 @@ import org.apache.shenyu.common.enums.PluginEnum;
 import org.apache.shenyu.common.enums.ResultEnum;
 import org.apache.shenyu.common.enums.UniqueHeaderEnum;
 import org.apache.shenyu.plugin.base.utils.MediaTypeUtils;
+import 
org.apache.shenyu.plugin.httpclient.exception.ShenyuUpstreamStatusException;
 import org.springframework.core.io.buffer.DataBuffer;
 import org.springframework.core.io.buffer.DataBufferUtils;
 import org.springframework.http.HttpHeaders;
@@ -100,6 +101,8 @@ public class WebClientPlugin extends 
AbstractHttpClientPlugin<ResponseEntity<Flu
         }
         final WebClient.ResponseSpec responseSpec = requestHeadersSpec
                 .retrieve()
+                .onRawStatus(httpStatus -> shouldFailover(exchange, 
httpStatus), clientResponse -> clientResponse.releaseBody()
+                        .thenReturn(new 
ShenyuUpstreamStatusException(clientResponse.statusCode().value())))
                 // cover DefaultResponseSpec#DEFAULT_STATUS_HANDLER
                 .onRawStatus(httpStatus -> httpStatus >= 400, clientResponse 
-> Mono.empty());
         return responseSpec.toEntityFlux(DataBuffer.class)
diff --git 
a/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/exception/ShenyuUpstreamStatusException.java
 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/exception/ShenyuUpstreamStatusException.java
new file mode 100644
index 0000000000..81bb7ba263
--- /dev/null
+++ 
b/shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/exception/ShenyuUpstreamStatusException.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ *     http://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.apache.shenyu.plugin.httpclient.exception;
+
+/**
+ * Signals an upstream status that should trigger failover.
+ */
+public final class ShenyuUpstreamStatusException extends RuntimeException {
+
+    private static final long serialVersionUID = 660353739127205812L;
+
+    /**
+     * Instantiates a new upstream status exception.
+     *
+     * @param statusCode upstream HTTP status code
+     */
+    public ShenyuUpstreamStatusException(final int statusCode) {
+        super("Upstream returned retryable HTTP status " + statusCode);
+    }
+}
diff --git 
a/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPluginTest.java
 
b/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPluginTest.java
index a37d8cff8a..5d54bb633d 100644
--- 
a/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPluginTest.java
+++ 
b/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/NettyHttpClientPluginTest.java
@@ -22,10 +22,12 @@ import io.netty.handler.codec.http.HttpHeaderValues;
 import org.apache.shenyu.common.constant.Constants;
 import org.apache.shenyu.common.enums.PluginEnum;
 import org.apache.shenyu.common.enums.RpcTypeEnum;
+import org.apache.shenyu.common.enums.RetryEnum;
 import org.apache.shenyu.plugin.api.ShenyuPluginChain;
 import org.apache.shenyu.plugin.api.context.ShenyuContext;
 import org.apache.shenyu.plugin.api.result.ShenyuResult;
 import org.apache.shenyu.plugin.api.utils.SpringBeanUtils;
+import 
org.apache.shenyu.plugin.httpclient.exception.ShenyuUpstreamStatusException;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
@@ -37,7 +39,10 @@ import 
org.springframework.mock.http.server.reactive.MockServerHttpRequest;
 import org.springframework.mock.web.server.MockServerWebExchange;
 import org.springframework.web.server.ServerWebExchange;
 import reactor.core.publisher.Mono;
+import reactor.core.publisher.Flux;
+import reactor.netty.DisposableServer;
 import reactor.netty.http.client.HttpClient;
+import reactor.netty.http.server.HttpServer;
 import reactor.test.StepVerifier;
 
 import java.net.URI;
@@ -88,6 +93,25 @@ public final class NettyHttpClientPluginTest {
         StepVerifier.create(nettyHttpClientPlugin.execute(exchange, 
chain)).expectSubscription().verifyError();
     }
 
+    @Test
+    public void testServerErrorTriggersFailover() {
+        final DisposableServer server = HttpServer.create()
+                .port(0)
+                .handle((request, response) -> 
response.status(500).sendString(Mono.just("server error")))
+                .bindNow();
+        try {
+            final ServerWebExchange exchange = generateServerWebExchange();
+            exchange.getAttributes().put(Constants.RETRY_STRATEGY, 
RetryEnum.FAILOVER.getName());
+            final URI uri = URI.create("http://127.0.0.1:"; + server.port() + 
"/test");
+
+            StepVerifier.create(nettyHttpClientPlugin.doRequest(exchange, 
"GET", uri, Flux.empty()))
+                    .expectError(ShenyuUpstreamStatusException.class)
+                    .verify();
+        } finally {
+            server.disposeNow();
+        }
+    }
+
     /**
      * test case for NettyHttpClientPlugin {@link 
NettyHttpClientPlugin#skip(ServerWebExchange)}.
      */
diff --git 
a/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/WebClientPluginTest.java
 
b/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/WebClientPluginTest.java
index 0b4470e751..7072002e33 100644
--- 
a/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/WebClientPluginTest.java
+++ 
b/shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/WebClientPluginTest.java
@@ -22,6 +22,8 @@ import org.apache.shenyu.common.enums.PluginEnum;
 import org.apache.shenyu.common.enums.HeaderUniqueStrategyEnum;
 import org.apache.shenyu.common.enums.UniqueHeaderEnum;
 import org.apache.shenyu.common.enums.RpcTypeEnum;
+import org.apache.shenyu.common.enums.RetryEnum;
+import 
org.apache.shenyu.plugin.httpclient.exception.ShenyuUpstreamStatusException;
 import org.apache.shenyu.plugin.api.ShenyuPluginChain;
 import org.apache.shenyu.plugin.api.context.ShenyuContext;
 import org.apache.shenyu.plugin.api.result.ShenyuResult;
@@ -186,6 +188,17 @@ public final class WebClientPluginTest {
                 .verify();
     }
 
+    @Test
+    public void testServerErrorTriggersFailover() {
+        WebClientPlugin plugin = new WebClientPlugin(mockWebClientError(), 
Constants.BYTES_PER_MB);
+        ServerWebExchange exchange = generateServerWebExchange();
+        exchange.getAttributes().put(Constants.RETRY_STRATEGY, 
RetryEnum.FAILOVER.getName());
+
+        StepVerifier.create(plugin.doRequest(exchange, HttpMethod.GET.name(), 
URI.create("/test"), Flux.empty()))
+                .expectError(ShenyuUpstreamStatusException.class)
+                .verify();
+    }
+
     @ParameterizedTest
     @EnumSource(HeaderUniqueStrategyEnum.class)
     public void testOutboundHeaderDeduplication(final HeaderUniqueStrategyEnum 
strategy) {
@@ -248,15 +261,8 @@ public final class WebClientPluginTest {
     }
 
     private WebClient mockWebClientError() {
-        final ClientResponse.Headers headers = 
mock(ClientResponse.Headers.class);
-        when(headers.asHttpHeaders()).thenReturn(new HttpHeaders());
-        
-        final ClientResponse mockResponse = mock(ClientResponse.class);
-        
when(mockResponse.statusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
-        when(mockResponse.headers()).thenReturn(headers);
-        when(mockResponse.bodyToMono(byte[].class)).thenReturn(Mono.just(new 
byte[0]));
-        when(mockResponse.releaseBody()).thenReturn(Mono.empty());
-        
given(this.exchangeFunction.exchange(this.captor.capture())).willReturn(Mono.just(mockResponse));
+        final ClientResponse response = 
ClientResponse.create(HttpStatus.INTERNAL_SERVER_ERROR).build();
+        
given(this.exchangeFunction.exchange(this.captor.capture())).willReturn(Mono.just(response));
         return WebClient.builder().baseUrl("/test")
                 .exchangeFunction(this.exchangeFunction)
                 .apply(consumer -> consumer.defaultHeader("Accept", 
"application/json")

Reply via email to