diff --git a/issue-spec/specs/opt-in-local-uri-registration/spec.md b/issue-spec/specs/opt-in-local-uri-registration/spec.md new file mode 100644 index 000000000000..96b22dd28a56 --- /dev/null +++ b/issue-spec/specs/opt-in-local-uri-registration/spec.md @@ -0,0 +1,42 @@ +# opt-in-local-uri-registration + +## Purpose + +Define the long-lived behavior contract for this capability. + +Proposal Issues: +- https://github.com/apache/shenyu/issues/8497 + +## Requirements + +### Requirement: Local URI registration for the opt-in Java client + +Applications using @EnableClientRegister MUST publish local upstream URIs through the existing registration pipeline only in local discovery mode (the default). Each eligible instance identity (namespace, RPC type, application, context path, host, port) MUST be enqueued once rather than once per API or refresh; a failed enqueue MUST remain retryable without blocking other namespaces. URI-specific processor filtering MUST apply. Registry discovery MUST retain metadata behavior without local URI publication. Existing repository failback and lifecycle handling MUST retain the published identity; queued work MUST NOT be represented as an accepted Admin acknowledgement. HTTP and WebSocket URIs MUST retain the configured protocol, defaulting to http:// and ws:// respectively. Existing configuration implementations remain compatible with the optional protocol accessor. Global opt-in registration disable is owned by client-registration-validation (#8504). + +#### Scenario: Local instance with multiple APIs and namespaces + +- **WHEN** an enabled opt-in servlet application with two eligible APIs starts in local discovery and two namespaces +- **THEN** metadata for both APIs is published in both namespaces; one URI per namespace preserves the configured live host, port, RPC type, app, context and protocol. An actual Admin/bootstrap route returns the backend response for the HTTP fixture + +#### Scenario: Repeated refresh and processor exclusion + +- **WHEN** the same APIs are rediscovered, or a URI processor excludes all of a bean's APIs +- **THEN** rediscovery does not multiply URI work; excluded APIs do not cause a URI registration + +#### Scenario: Registry discovery + +- **WHEN** the configured discovery mode is not exactly local +- **THEN** the local URI registrar is absent, while supported metadata is still published + +#### Scenario: Unresolved ports and retryable failures + +- **WHEN** an HTTP/WebSocket port is temporarily unresolved (0 or -1), a port is malformed or out of range, or one namespace's publication fails +- **THEN** an unresolved port skips local URI publication for this refresh without failing startup. No malformed or out-of-range port is published. A failed enqueue does not prevent other namespaces from enqueueing and can be retried on rediscovery. Existing HTTP failback retries a failed transport identity. Actual bound-port resolution is tracked in #8426 + +#### Scenario: Lifecycle identity + +- **WHEN** successfully registered URIs are heartbeated and taken offline +- **THEN** the payloads retain each URI's namespace, RPC type, application, context, host, port and protocol. Test evidence distinguishes HTTP attempts from successful acknowledgements + +Source SPEC comments: +- https://github.com/apache/shenyu/issues/8497#issuecomment-6905917087 diff --git a/shenyu-client/shenyu-client-autoconfig/src/main/java/org/apache/shenyu/client/auto/config/ClientRegisterConfiguration.java b/shenyu-client/shenyu-client-autoconfig/src/main/java/org/apache/shenyu/client/auto/config/ClientRegisterConfiguration.java index daa1ddc6e5d8..91468201278f 100644 --- a/shenyu-client/shenyu-client-autoconfig/src/main/java/org/apache/shenyu/client/auto/config/ClientRegisterConfiguration.java +++ b/shenyu-client/shenyu-client-autoconfig/src/main/java/org/apache/shenyu/client/auto/config/ClientRegisterConfiguration.java @@ -17,6 +17,7 @@ package org.apache.shenyu.client.auto.config; +import org.apache.shenyu.client.core.constant.ShenyuClientConstants; import org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher; import org.apache.shenyu.client.core.register.ClientApiRefreshedEventListener; import org.apache.shenyu.client.core.register.ClientRegisterConfig; @@ -27,10 +28,15 @@ import org.apache.shenyu.client.core.register.registrar.ApiDocRegistrarImpl; import org.apache.shenyu.client.core.register.registrar.ApiRegistrar; import org.apache.shenyu.client.core.register.registrar.MateDataApiRegistrarImpl; +import org.apache.shenyu.client.core.register.registrar.UriApiRegistrarImplImpl; import org.apache.shenyu.register.client.api.ShenyuClientRegisterRepository; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Configuration; +import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.List; @@ -64,6 +70,21 @@ public MateDataApiRegistrarImpl mateDataApiRegistrarImpl(final ClientRegisterCon return apiRegistrarImpl; } + /** + * URI registrar for local instance membership. + * + * @param clientRegisterConfig client registration configuration + * @param processors registration processors + * @return URI registrar + */ + @Bean + @Conditional(LocalDiscoveryCondition.class) + public UriApiRegistrarImplImpl uriApiRegistrar(final ClientRegisterConfig clientRegisterConfig, final List processors) { + UriApiRegistrarImplImpl registrar = new UriApiRegistrarImplImpl(clientRegisterConfig); + processors.forEach(registrar::addApiProcessor); + return registrar; + } + /** * api doc register. * @@ -102,4 +123,13 @@ public ShenyuClientRegisterEventPublisher publisher(final ShenyuClientRegisterRe publisher.start(shenyuClientRegisterRepository); return publisher; } + + static final class LocalDiscoveryCondition implements Condition { + + @Override + public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) { + return ShenyuClientConstants.DISCOVERY_LOCAL_MODE.equals( + context.getEnvironment().getProperty("shenyu.discovery.type", ShenyuClientConstants.DISCOVERY_LOCAL_MODE)); + } + } } diff --git a/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfig.java b/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfig.java index 678158c76e9f..5e8be0529881 100644 --- a/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfig.java +++ b/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfig.java @@ -39,6 +39,15 @@ default List getNamespace() { */ Integer getPort(); + /** + * Gets the scheme advertised by a local URI registration. + * + * @return the configured scheme, or null to retain the protocol-specific default + */ + default String getProtocol() { + return null; + } + /** * Gets host. * @return host diff --git a/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfigImpl.java b/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfigImpl.java index 1696e14ba6a9..495eb5be5d43 100644 --- a/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfigImpl.java +++ b/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/ClientRegisterConfigImpl.java @@ -90,6 +90,15 @@ public Integer getPort() { return this.port; } + @Override + public String getProtocol() { + return switch (rpcTypeEnum) { + case HTTP -> props.getProperty(ShenyuClientConstants.PROTOCOL, ShenyuClientConstants.HTTP); + case WEB_SOCKET -> props.getProperty(ShenyuClientConstants.PROTOCOL, ShenyuClientConstants.WS); + default -> null; + }; + } + @Override public String getHost() { diff --git a/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarImplImpl.java b/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarImplImpl.java index ed12e1d8d177..68f7513d32b9 100644 --- a/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarImplImpl.java +++ b/shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarImplImpl.java @@ -21,73 +21,101 @@ import org.apache.shenyu.client.core.register.ApiBean; import org.apache.shenyu.client.core.register.ClientRegisterConfig; import org.apache.shenyu.client.core.utils.ApiBeanUtil; +import org.apache.shenyu.common.enums.RpcTypeEnum; import org.apache.shenyu.register.common.dto.URIRegisterDTO; import org.apache.shenyu.register.common.enums.EventType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashSet; +import java.util.Set; /** - * UriApiRegistrarImplImpl. - * - *

Like the full-mode branches of the client event listeners, URI publication must - * only happen in local discovery mode. This registrar is not wired by any starter yet; - * when it becomes reachable, gate {@link #doRegisterApi} / {@link #doRegisterBean} on - * the discovery mode (see - * {@code AbstractContextRefreshedEventListener#isDiscoveryLocalMode}) to avoid dual - * upstream registration for the same selector. + * Publishes local instance membership once per namespace and instance identity. + * Repository failback owns transport retries after a URI has been enqueued. * * @see URIRegisterDTO */ public class UriApiRegistrarImplImpl extends BaseApiRegistrarImpl { - + + private static final Logger LOG = LoggerFactory.getLogger(UriApiRegistrarImplImpl.class); + + private static final int MAX_PORT = 65535; + private final ShenyuClientRegisterEventPublisher publisher = ShenyuClientRegisterEventPublisher.getInstance(); - + private final ClientRegisterConfig clientRegisterConfig; - + + private final Set publishedIdentities = new HashSet<>(); + + private boolean awaitingPort; + public UriApiRegistrarImplImpl(final ClientRegisterConfig clientRegisterConfig) { this.clientRegisterConfig = clientRegisterConfig; } - + @Override - protected void doRegisterApi(final ApiBean.ApiDefinition api) { - clientRegisterConfig.getNamespace().forEach(namespaceId -> registerApi(api, namespaceId)); + public Class registerDataType() { + return URIRegisterDTO.class; } - private void registerApi(final ApiBean.ApiDefinition api, final String namespaceId) { - final URIRegisterDTO uriRegisterDTO = URIRegisterDTO.builder() - .namespaceId(namespaceId) - .contextPath(clientRegisterConfig.getContextPath()) - .appName(clientRegisterConfig.getAppName()) - .eventType(EventType.REGISTER) - .host(clientRegisterConfig.getHost()) - .port(clientRegisterConfig.getPort()) - .rpcType(getRpcType(api)) - .build(); - publisher.publishEvent(uriRegisterDTO); + @Override + protected void doRegisterApi(final ApiBean.ApiDefinition api) { + registerUri(ApiBeanUtil.getRpcType(api)); } - + @Override protected void doRegisterBean(final ApiBean apiBean) { - clientRegisterConfig.getNamespace().forEach(namespaceId -> registerBean(apiBean, namespaceId)); + registerUri(ApiBeanUtil.getRpcType(apiBean)); } - private void registerBean(final ApiBean apiBean, final String namespaceId) { - final URIRegisterDTO uriRegisterDTO = URIRegisterDTO.builder() - .namespaceId(namespaceId) - .contextPath(clientRegisterConfig.getContextPath()) - .appName(clientRegisterConfig.getAppName()) - .eventType(EventType.REGISTER) - .host(clientRegisterConfig.getHost()) - .port(clientRegisterConfig.getPort()) - .rpcType(getRpcType(apiBean)) - .build(); - publisher.publishEvent(uriRegisterDTO); + private synchronized void registerUri(final String rpcType) { + int port = clientRegisterConfig.getPort(); + if (isPendingPort(rpcType, port)) { + if (!awaitingPort) { + LOG.warn("Skipping local URI registration until the advertised port is available"); + awaitingPort = true; + } + return; + } + if (port <= 0 || port > MAX_PORT) { + throw new IllegalArgumentException("Local URI registration requires a port between 1 and " + MAX_PORT); + } + awaitingPort = false; + for (String namespaceId : clientRegisterConfig.getNamespace()) { + URIRegisterDTO uri = URIRegisterDTO.builder() + .namespaceId(namespaceId) + .contextPath(clientRegisterConfig.getContextPath()) + .appName(clientRegisterConfig.getAppName()) + .eventType(EventType.REGISTER) + .host(clientRegisterConfig.getHost()) + .port(port) + .rpcType(rpcType) + .protocol(clientRegisterConfig.getProtocol()) + .build(); + publish(uri); + } } - - private static String getRpcType(final ApiBean.ApiDefinition api) { - return ApiBeanUtil.getRpcType(api); + + private static boolean isPendingPort(final String rpcType, final int port) { + boolean supportsAutoPort = RpcTypeEnum.HTTP.getName().equals(rpcType) || RpcTypeEnum.WEB_SOCKET.getName().equals(rpcType); + return supportsAutoPort && (port == 0 || port == -1); + } + + private void publish(final URIRegisterDTO uri) { + // The enqueue key is a snapshot since the subscriber can mutate the DTO. + UriIdentity identity = new UriIdentity(uri.getNamespaceId(), uri.getRpcType(), uri.getAppName(), uri.getContextPath(), uri.getHost(), uri.getPort()); + if (publishedIdentities.contains(identity)) { + return; + } + try { + publisher.publishEvent(uri); + publishedIdentities.add(identity); + } catch (RuntimeException ex) { + LOG.warn("Could not enqueue local URI registration; it can be retried on rediscovery"); + } } - - private static String getRpcType(final ApiBean api) { - return ApiBeanUtil.getRpcType(api); + + private record UriIdentity(String namespaceId, String rpcType, String appName, String contextPath, String host, int port) { } - } diff --git a/shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/RegistrarNamespaceTest.java b/shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/RegistrarNamespaceTest.java index 04191b727d5d..b3988e52c57b 100644 --- a/shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/RegistrarNamespaceTest.java +++ b/shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/RegistrarNamespaceTest.java @@ -62,7 +62,7 @@ void testUriAndMetadataUseIndependentNamespaceEvents() throws Exception { registrar.doRegisterBean(bean); registrar.doRegisterApi(bean.getApiDefinitions().get(0)); ArgumentCaptor captor = ArgumentCaptor.forClass(DataTypeParent.class); - verify(publisher, times(4)).publishEvent(captor.capture()); + verify(publisher, times(registrar instanceof UriApiRegistrarImplImpl ? 2 : 4)).publishEvent(captor.capture()); List events = captor.getAllValues(); for (int index = 0; index < events.size(); index += 2) { assertNotSame(events.get(index), events.get(index + 1)); diff --git a/shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarTest.java b/shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarTest.java new file mode 100644 index 000000000000..298dc7658600 --- /dev/null +++ b/shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarTest.java @@ -0,0 +1,168 @@ +/* + * 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.client.core.register.registrar; + +import org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher; +import org.apache.shenyu.client.core.register.ApiBean; +import org.apache.shenyu.client.core.register.ClientRegisterConfig; +import org.apache.shenyu.client.core.register.ClientRegisterConfigImpl; +import org.apache.shenyu.common.enums.RpcTypeEnum; +import org.apache.shenyu.register.common.config.ShenyuClientConfig; +import org.apache.shenyu.register.common.dto.URIRegisterDTO; +import org.apache.shenyu.register.common.enums.EventType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** URI instance publication and retry ownership. */ +class UriApiRegistrarTest { + + private final ClientRegisterConfig config = mock(ClientRegisterConfig.class); + + private final ShenyuClientRegisterEventPublisher publisher = mock(ShenyuClientRegisterEventPublisher.class); + + private UriApiRegistrarImplImpl registrar; + + @BeforeEach + void setUp() { + when(config.getNamespace()).thenReturn(List.of("one", "two")); + when(config.getHost()).thenReturn("127.0.0.1"); + when(config.getPort()).thenReturn(8080); + when(config.getAppName()).thenReturn("app"); + when(config.getContextPath()).thenReturn("/app"); + registrar = new UriApiRegistrarImplImpl(config); + ReflectionTestUtils.setField(registrar, "publisher", publisher); + } + + @Test + void testBeanAndApisShareIdentityEvenAfterHeartbeatMutation() throws Exception { + registrar.register(bean()); + ArgumentCaptor events = ArgumentCaptor.forClass(URIRegisterDTO.class); + verify(publisher, times(2)).publishEvent(events.capture()); + events.getAllValues().forEach(uri -> uri.setEventType(EventType.HEARTBEAT)); + registrar.register(bean()); + verify(publisher, times(2)).publishEvent(any()); + assertEquals(URIRegisterDTO.class, registrar.registerDataType()); + } + + @Test + void testEnqueueFailureCanRetryWithoutRepeatingPublishedNamespaces() throws Exception { + doThrow(new IllegalStateException("queue unavailable")).doNothing().when(publisher).publishEvent(any()); + ApiBean bean = bean(); + bean.setStatus(ApiBean.Status.REGISTRABLE_BEAN); + registrar.register(bean); + verify(publisher, times(2)).publishEvent(any()); + registrar.register(bean); + ArgumentCaptor events = ArgumentCaptor.forClass(URIRegisterDTO.class); + verify(publisher, times(3)).publishEvent(events.capture()); + assertEquals(List.of("one", "two", "one"), events.getAllValues().stream().map(URIRegisterDTO::getNamespaceId).toList()); + } + + @Test + void testChangedInstanceIdentityIsNotSuppressed() throws Exception { + registrar.register(bean()); + when(config.getAppName()).thenReturn("other-app"); + registrar.register(bean()); + when(config.getContextPath()).thenReturn("/other"); + registrar.register(bean()); + when(config.getPort()).thenReturn(8081); + registrar.register(bean()); + when(config.getHost()).thenReturn("127.0.0.2"); + registrar.register(bean()); + verify(publisher, times(10)).publishEvent(any()); + } + + @Test + void testRpcTypesHaveIndependentIdentities() throws Exception { + registrar.register(bean()); + ApiBean other = bean(); + other.addProperties("rpcType", "grpc"); + other.getApiDefinitions().forEach(api -> api.addProperties("rpcType", "grpc")); + registrar.register(other); + verify(publisher, times(4)).publishEvent(any()); + } + + @Test + void testInvalidPortIsNotPublished() { + for (int port : List.of(-2, 65536)) { + when(config.getPort()).thenReturn(port); + assertThrows(IllegalArgumentException.class, () -> registrar.register(bean())); + } + verifyNoInteractions(publisher); + } + + @Test + void testPendingPortCanPublishOnRediscovery() throws Exception { + for (int port : List.of(0, -1)) { + when(config.getPort()).thenReturn(port); + registrar.register(bean()); + } + verifyNoInteractions(publisher); + when(config.getPort()).thenReturn(8080); + registrar.register(bean()); + verify(publisher, times(2)).publishEvent(any()); + } + + @ParameterizedTest + @ValueSource(strings = {"ws://", "wss://"}) + void testWebSocketProtocolIsPublished(final String protocol) throws Exception { + ShenyuClientConfig.ClientPropertiesConfig websocket = new ShenyuClientConfig.ClientPropertiesConfig(); + websocket.getProps().setProperty("host", "127.0.0.1"); + websocket.getProps().setProperty("port", "8080"); + if ("wss://".equals(protocol)) { + websocket.getProps().setProperty("protocol", protocol); + } + ShenyuClientConfig client = new ShenyuClientConfig(); + client.getClient().put(RpcTypeEnum.WEB_SOCKET.getName(), websocket); + UriApiRegistrarImplImpl websocketRegistrar = new UriApiRegistrarImplImpl( + new ClientRegisterConfigImpl(client, RpcTypeEnum.WEB_SOCKET, null, new MockEnvironment())); + ReflectionTestUtils.setField(websocketRegistrar, "publisher", publisher); + ApiBean bean = bean(); + bean.addProperties("rpcType", RpcTypeEnum.WEB_SOCKET.getName()); + bean.setStatus(ApiBean.Status.REGISTRABLE_BEAN); + websocketRegistrar.register(bean); + ArgumentCaptor event = ArgumentCaptor.forClass(URIRegisterDTO.class); + verify(publisher).publishEvent(event.capture()); + assertEquals(protocol, event.getValue().getProtocol()); + } + + private ApiBean bean() throws Exception { + ApiBean bean = new ApiBean("http", "endpoints", this, "/api"); + bean.addApiDefinition(Object.class.getMethod("toString"), "/one"); + bean.addApiDefinition(Object.class.getMethod("hashCode"), "/two"); + bean.setStatus(ApiBean.Status.REGISTRABLE); + bean.getApiDefinitions().forEach(api -> api.setStatus(ApiBean.Status.REGISTRABLE)); + return bean; + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/pom.xml index 0209dd46c57f..7200f1afd4b7 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/pom.xml @@ -41,5 +41,10 @@ shenyu-client-autoconfig ${project.version} + + org.springframework.boot + spring-boot-starter-web + test + diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/src/test/java/org/apache/shenyu/springboot/starter/client/springmvc/EnableClientRegisterUriTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/src/test/java/org/apache/shenyu/springboot/starter/client/springmvc/EnableClientRegisterUriTest.java new file mode 100644 index 000000000000..d60c7df37e6b --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/src/test/java/org/apache/shenyu/springboot/starter/client/springmvc/EnableClientRegisterUriTest.java @@ -0,0 +1,346 @@ +/* + * 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.springboot.starter.client.springmvc; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.apache.shenyu.client.auto.config.EnableClientRegister; +import org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher; +import org.apache.shenyu.client.core.disruptor.subcriber.ShenyuClientURIExecutorSubscriber; +import org.apache.shenyu.client.core.register.ApiBean; +import org.apache.shenyu.client.core.register.ShenyuClientRegisterRepositoryFactory; +import org.apache.shenyu.client.core.register.matcher.ApiRegisterProcessor; +import org.apache.shenyu.client.core.shutdown.ShutdownHookManager; +import org.apache.shenyu.common.utils.GsonUtils; +import org.apache.shenyu.register.client.api.ShenyuClientRegisterRepository; +import org.apache.shenyu.register.common.dto.MetaDataRegisterDTO; +import org.apache.shenyu.register.common.dto.URIRegisterDTO; +import org.apache.shenyu.register.common.enums.EventType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Servlet application and real HTTP registration, with an isolated recording control-plane endpoint. */ +public final class EnableClientRegisterUriTest { + + private final List metadata = new CopyOnWriteArrayList<>(); + + private final List uris = new CopyOnWriteArrayList<>(); + + private final List attempts = new CopyOnWriteArrayList<>(); + + private final List heartbeats = new CopyOnWriteArrayList<>(); + + private final List offline = new CopyOnWriteArrayList<>(); + + private final AtomicBoolean failSecondNamespace = new AtomicBoolean(); + + private final OwnedPublisher publisher = new OwnedPublisher(); + + private MockedStatic singleton; + + private HttpServer admin; + + private ConfigurableApplicationContext application; + + private Map previousRepositories; + + private Set previousHooks; + + @BeforeEach + public void startAdmin() throws Exception { + previousRepositories = new HashMap<>(ShenyuClientRegisterRepositoryFactory.getRepositoryMap()); + previousHooks = new HashSet<>((Set) Objects.requireNonNull(ReflectionTestUtils.getField(ShutdownHookManager.get(), "hooks"))); + admin = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + admin.createContext("/", this::handleRegistration); + admin.start(); + singleton = Mockito.mockStatic(ShenyuClientRegisterEventPublisher.class); + singleton.when(ShenyuClientRegisterEventPublisher::getInstance).thenReturn(publisher); + ShenyuClientRegisterRepositoryFactory.getRepositoryMap().clear(); + } + + private void handleRegistration(final HttpExchange exchange) throws IOException { + String path = exchange.getRequestURI().getPath(); + String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + int status = 200; + if (path.endsWith("register-metadata")) { + metadata.add(GsonUtils.getGson().fromJson(body, MetaDataRegisterDTO.class)); + } + if (path.endsWith("register-uri")) { + URIRegisterDTO uri = GsonUtils.getGson().fromJson(body, URIRegisterDTO.class); + if (EventType.HEARTBEAT.equals(uri.getEventType())) { + heartbeats.add(uri); + } else { + attempts.add(uri); + if ("two".equals(uri.getNamespaceId()) && failSecondNamespace.compareAndSet(true, false)) { + status = 503; + } else { + uris.add(uri); + } + } + } + if (path.endsWith("offline")) { + offline.add(GsonUtils.getGson().fromJson(body, URIRegisterDTO.class)); + } + String result = "/platform/login".equals(path) ? "{\"code\":200,\"data\":{\"token\":\"fixture\"}}" : "success"; + byte[] response = (status == 200 ? result : "temporarily unavailable").getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status, response.length); + exchange.getResponseBody().write(response); + exchange.close(); + } + + @ParameterizedTest + @ValueSource(strings = {"http://", "https://"}) + public void testLocalRegistrationHasOneUriPerNamespace(final String protocol) throws Exception { + if ("http://".equals(protocol)) { + startApplication(null); + } else { + startApplication(null, "--shenyu.client.http.props.protocol=" + protocol); + } + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> { + assertEquals(4, metadata.size()); + assertEquals(2, uris.size()); + }); + assertFalse(application.containsBean("springHttpClientEventListener")); + assertEquals(List.of("one", "one", "two", "two"), metadata.stream().map(MetaDataRegisterDTO::getNamespaceId).sorted().toList()); + assertEquals(List.of("one", "two"), uris.stream().map(URIRegisterDTO::getNamespaceId).sorted().toList()); + for (URIRegisterDTO uri : uris) { + assertEquals("http", uri.getRpcType()); + assertEquals(protocol, uri.getProtocol()); + assertEquals("/client", uri.getContextPath()); + assertEquals("uri-fixture", uri.getAppName()); + assertEquals("127.0.0.1", uri.getHost()); + assertEquals(application.getEnvironment().getProperty("server.port", Integer.class), uri.getPort()); + } + application.publishEvent(new ContextRefreshedEvent(application)); + await().during(Duration.ofMillis(300)).atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertEquals(2, uris.size())); + } + + @ParameterizedTest + @ValueSource(strings = {"nacos", "LOCAL", ""}) + public void testRegistryDiscoveryKeepsMetadataWithoutLocalUris(final String mode) throws Exception { + startApplication(mode); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(4, metadata.size())); + assertEquals(0, uris.size()); + } + + @ParameterizedTest + @ValueSource(ints = {0, -1}) + public void testPendingAdvertisedPortKeepsApplicationBootable(final int port) throws Exception { + startApplication("local", "--shenyu.client.http.props.port=" + port); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(4, metadata.size())); + assertEquals(0, attempts.size()); + } + + @Test + public void testUriProcessorCanExcludeApisWithoutSuppressingMetadata() throws Exception { + startApplication("local", "--fixture.exclude-uris=true"); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(4, metadata.size())); + assertEquals(0, attempts.size()); + } + + @Test + public void testMalformedPortDoesNotPublishUri() { + assertThrows(RuntimeException.class, () -> startApplication("local", "--shenyu.client.http.props.port=invalid")); + assertEquals(0, attempts.size()); + } + + @Test + public void testPartialHttpFailureRetriesOnlyFailedIdentityAndKeepsLifecycleIdentity() throws Exception { + failSecondNamespace.set(true); + startApplication("local", "--shenyu.client.http.props.protocol=https://"); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> { + assertEquals(2, attempts.size()); + assertEquals(1, uris.size()); + }); + await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> { + assertEquals(3, attempts.size()); + assertEquals(2, uris.size()); + }); + assertEquals(1, attempts.stream().filter(uri -> "one".equals(uri.getNamespaceId())).count()); + assertEquals(2, attempts.stream().filter(uri -> "two".equals(uri.getNamespaceId())).count()); + List tracked = ((List) Objects.requireNonNull(ReflectionTestUtils.getField(publisher.subscriber, "uris"))).stream() + .map(URIRegisterDTO.class::cast).toList(); + assertEquals(2, tracked.size()); + for (URIRegisterDTO uri : tracked) { + ReflectionTestUtils.invokeMethod(publisher.subscriber, "sendHeartbeat", uri); + ReflectionTestUtils.invokeMethod(publisher.subscriber, "offlineAndShutdown", uri); + } + assertEquals(2, heartbeats.size()); + assertEquals(2, offline.size()); + for (int index = 0; index < uris.size(); index++) { + assertEquals(identity(tracked.get(index)), identity(heartbeats.get(index))); + assertEquals(identity(tracked.get(index)), identity(offline.get(index))); + assertEquals(EventType.OFFLINE, offline.get(index).getEventType()); + } + } + + private List identity(final URIRegisterDTO uri) { + return List.of(uri.getNamespaceId(), uri.getRpcType(), uri.getAppName(), uri.getContextPath(), uri.getHost(), uri.getPort(), uri.getProtocol()); + } + + private void startApplication(final String discovery, final String... overrides) throws Exception { + int port; + try (ServerSocket reservation = new ServerSocket(0)) { + port = reservation.getLocalPort(); + } + SpringApplicationBuilder builder = new SpringApplicationBuilder(Fixture.class).properties( + "server.address=127.0.0.1", "server.port=" + port, + "spring.application.name=uri-fixture", + "shenyu.register.registerType=http", + "shenyu.register.serverLists=http://127.0.0.1:" + admin.getAddress().getPort(), + "shenyu.register.props.username=fixture", "shenyu.register.props.password=fixture", + "shenyu.client.http.props.host=127.0.0.1", "shenyu.client.http.props.port=" + port, + "shenyu.client.http.props.appName=uri-fixture", "shenyu.client.http.props.contextPath=/client", + "shenyu.namespace=one;two", "spring.main.banner-mode=off"); + if (Objects.nonNull(discovery)) { + builder.properties("shenyu.discovery.type=" + discovery); + } + application = builder.run(overrides); + } + + @AfterEach + public void stop() throws InterruptedException { + if (Objects.nonNull(application)) { + application.close(); + } + if (Objects.nonNull(publisher.subscriber)) { + publisher.subscriber.shutdown(); + } + if (Objects.nonNull(publisher.getProviderManage())) { + publisher.getProviderManage().getProvider().shutdown(); + ExecutorService executor = (ExecutorService) Objects.requireNonNull(ReflectionTestUtils.getField(publisher.getProviderManage().getProvider(), "executor")); + assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + } + Set hooks = (Set) Objects.requireNonNull(ReflectionTestUtils.getField(ShutdownHookManager.get(), "hooks")); + hooks.removeIf(hook -> !previousHooks.contains(hook)); + singleton.close(); + ShenyuClientRegisterRepositoryFactory.getRepositoryMap().clear(); + ShenyuClientRegisterRepositoryFactory.getRepositoryMap().putAll(previousRepositories); + admin.stop(0); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration(exclude = ErrorMvcAutoConfiguration.class) + @EnableClientRegister + @Import(ShenyuSpringMvcClientConfiguration.class) + public static class Fixture { + + /** + * Run this fixture against an isolated Admin and bootstrap using normal Spring properties. + * + * @param args application properties + */ + public static void main(final String[] args) { + SpringApplication.run(Fixture.class, args); + } + + @Bean + public Endpoints endpoints() { + return new Endpoints(); + } + + @Bean + public ApiRegisterProcessor uriFilter(final Environment environment) { + return new ApiRegisterProcessor() { + @Override + public void process(final ApiBean apiBean) { + if (environment.getProperty("fixture.exclude-uris", Boolean.class, false)) { + apiBean.setStatus(ApiBean.Status.CAN_NO_BE_REGISTERED); + } + } + + @Override + public boolean match(final ApiBean apiBean) { + return true; + } + + @Override + public List> supportedRegisterDataType() { + return List.of(URIRegisterDTO.class); + } + }; + } + } + + @RestController + @RequestMapping(path = "/api") + public static class Endpoints { + + @GetMapping(path = "/hello") + public String hello() { + return "hello"; + } + + @GetMapping(path = "/second") + public String second() { + return "second"; + } + } + + private static final class OwnedPublisher extends ShenyuClientRegisterEventPublisher { + + private ShenyuClientURIExecutorSubscriber subscriber; + + @Override + protected ShenyuClientURIExecutorSubscriber createUriSubscriber(final ShenyuClientRegisterRepository repository) { + subscriber = super.createUriSubscriber(repository); + return subscriber; + } + } +}