Skip to content

Commit 17c27ed

Browse files
committed
fix (client) : register opt-in local uri membership once per instance.
1 parent e934516 commit 17c27ed

7 files changed

Lines changed: 601 additions & 48 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# opt-in-local-uri-registration
2+
3+
## Purpose
4+
5+
Define the long-lived behavior contract for this capability.
6+
7+
Proposal Issues:
8+
- https://github.com/apache/shenyu/issues/8497
9+
10+
## Requirements
11+
12+
### Requirement: Local URI registration for the opt-in Java client
13+
14+
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; failed enqueue MUST remain retryable. URI-specific processor filtering MUST apply. Disabled registration MUST create no registration pipeline. 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. Legacy defaults and public registration SPI remain unchanged.
15+
16+
#### Scenario: Local instance with multiple APIs and namespaces
17+
18+
- **WHEN** an enabled opt-in servlet application with two eligible APIs starts in local discovery and two namespaces
19+
- **THEN** metadata for both APIs is published in both namespaces; one URI per namespace preserves the configured live host, port, RPC type, app and context and an actual Admin/bootstrap route returns the backend response
20+
21+
#### Scenario: Repeated refresh and processor exclusion
22+
23+
- **WHEN** the same APIs are rediscovered, or a URI processor excludes all of a bean's APIs
24+
- **THEN** rediscovery does not multiply URI work; excluded APIs do not cause a URI registration
25+
26+
#### Scenario: Registry discovery and disabled registration
27+
28+
- **WHEN** discovery is non-local, or shenyu.register.enabled is false
29+
- **THEN** registry mode publishes supported metadata and no local URI; disabled mode constructs no registration pipeline and publishes no registration traffic
30+
31+
#### Scenario: Malformed configuration and retryable failures
32+
33+
- **WHEN** the configured port is malformed, publication throws, or one namespace's HTTP registration fails transiently
34+
- **THEN** the malformed instance is not admitted as a usable URI; a failed enqueue can be tried on refresh and existing failback retries the failed HTTP identity without suppressing successful namespaces
35+
36+
#### Scenario: Lifecycle identity
37+
38+
- **WHEN** successfully registered URIs are heartbeated and taken offline
39+
- **THEN** the payloads retain each URI's namespace, RPC type, application, context, host and port; test evidence distinguishes HTTP attempts from successful acknowledgements
40+
41+
Source SPEC comments:
42+
- https://github.com/apache/shenyu/issues/8497#issuecomment-6905917087

‎shenyu-client/shenyu-client-autoconfig/src/main/java/org/apache/shenyu/client/auto/config/ClientRegisterConfiguration.java‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,17 @@
2727
import org.apache.shenyu.client.core.register.registrar.ApiDocRegistrarImpl;
2828
import org.apache.shenyu.client.core.register.registrar.ApiRegistrar;
2929
import org.apache.shenyu.client.core.register.registrar.MateDataApiRegistrarImpl;
30+
import org.apache.shenyu.client.core.register.registrar.UriApiRegistrarImplImpl;
3031
import org.apache.shenyu.register.client.api.ShenyuClientRegisterRepository;
3132
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
33+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
3234
import org.springframework.context.annotation.Bean;
3335
import org.springframework.context.annotation.Configuration;
3436

3537
import java.util.List;
3638

3739
@Configuration(proxyBeanMethods = false)
40+
@ConditionalOnProperty(value = "shenyu.register.enabled", havingValue = "true", matchIfMissing = true)
3841
public class ClientRegisterConfiguration {
3942

4043
/**
@@ -64,6 +67,20 @@ public MateDataApiRegistrarImpl mateDataApiRegistrarImpl(final ClientRegisterCon
6467
return apiRegistrarImpl;
6568
}
6669

70+
/**
71+
* URI registrar for local instance membership.
72+
*
73+
* @param clientRegisterConfig client registration configuration
74+
* @param processors registration processors
75+
* @return URI registrar
76+
*/
77+
@Bean
78+
public UriApiRegistrarImplImpl uriApiRegistrar(final ClientRegisterConfig clientRegisterConfig, final List<ApiRegisterProcessor> processors) {
79+
UriApiRegistrarImplImpl registrar = new UriApiRegistrarImplImpl(clientRegisterConfig);
80+
processors.forEach(registrar::addApiProcessor);
81+
return registrar;
82+
}
83+
6784
/**
6885
* api doc register.
6986
*

‎shenyu-client/shenyu-client-core/src/main/java/org/apache/shenyu/client/core/register/registrar/UriApiRegistrarImplImpl.java‎

Lines changed: 62 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -17,77 +17,92 @@
1717

1818
package org.apache.shenyu.client.core.register.registrar;
1919

20+
import org.apache.shenyu.client.core.constant.ShenyuClientConstants;
2021
import org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher;
2122
import org.apache.shenyu.client.core.register.ApiBean;
2223
import org.apache.shenyu.client.core.register.ClientRegisterConfig;
2324
import org.apache.shenyu.client.core.utils.ApiBeanUtil;
2425
import org.apache.shenyu.register.common.dto.URIRegisterDTO;
2526
import org.apache.shenyu.register.common.enums.EventType;
27+
import org.springframework.context.EnvironmentAware;
28+
import org.springframework.core.env.Environment;
29+
import org.springframework.core.env.StandardEnvironment;
30+
31+
import java.util.Arrays;
32+
import java.util.HashSet;
33+
import java.util.List;
34+
import java.util.Set;
2635

2736
/**
28-
* UriApiRegistrarImplImpl.
29-
*
30-
* <p>Like the full-mode branches of the client event listeners, URI publication must
31-
* only happen in local discovery mode. This registrar is not wired by any starter yet;
32-
* when it becomes reachable, gate {@link #doRegisterApi} / {@link #doRegisterBean} on
33-
* the discovery mode (see
34-
* {@code AbstractContextRefreshedEventListener#isDiscoveryLocalMode}) to avoid dual
35-
* upstream registration for the same selector.
37+
* Publishes local instance membership once per namespace and instance identity.
38+
* Repository failback owns transport retries after a URI has been enqueued.
3639
*
3740
* @see URIRegisterDTO
3841
*/
39-
public class UriApiRegistrarImplImpl extends BaseApiRegistrarImpl {
40-
42+
public class UriApiRegistrarImplImpl extends BaseApiRegistrarImpl implements EnvironmentAware {
43+
44+
private static final int MAX_PORT = 65535;
45+
4146
private final ShenyuClientRegisterEventPublisher publisher = ShenyuClientRegisterEventPublisher.getInstance();
42-
47+
4348
private final ClientRegisterConfig clientRegisterConfig;
44-
49+
50+
private final Set<List<?>> publishedIdentities = new HashSet<>();
51+
52+
private Environment environment = new StandardEnvironment();
53+
4554
public UriApiRegistrarImplImpl(final ClientRegisterConfig clientRegisterConfig) {
4655
this.clientRegisterConfig = clientRegisterConfig;
4756
}
48-
57+
4958
@Override
50-
protected void doRegisterApi(final ApiBean.ApiDefinition api) {
51-
clientRegisterConfig.getNamespace().forEach(namespaceId -> registerApi(api, namespaceId));
59+
public void setEnvironment(final Environment environment) {
60+
this.environment = environment;
5261
}
5362

54-
private void registerApi(final ApiBean.ApiDefinition api, final String namespaceId) {
55-
final URIRegisterDTO uriRegisterDTO = URIRegisterDTO.builder()
56-
.namespaceId(namespaceId)
57-
.contextPath(clientRegisterConfig.getContextPath())
58-
.appName(clientRegisterConfig.getAppName())
59-
.eventType(EventType.REGISTER)
60-
.host(clientRegisterConfig.getHost())
61-
.port(clientRegisterConfig.getPort())
62-
.rpcType(getRpcType(api))
63-
.build();
64-
publisher.publishEvent(uriRegisterDTO);
63+
@Override
64+
public Class<?> registerDataType() {
65+
return URIRegisterDTO.class;
6566
}
66-
67+
6768
@Override
68-
protected void doRegisterBean(final ApiBean apiBean) {
69-
clientRegisterConfig.getNamespace().forEach(namespaceId -> registerBean(apiBean, namespaceId));
69+
public void register(final ApiBean apiBean) {
70+
if (ShenyuClientConstants.DISCOVERY_LOCAL_MODE.equals(environment.getProperty("shenyu.discovery.type", ShenyuClientConstants.DISCOVERY_LOCAL_MODE))) {
71+
super.register(apiBean);
72+
}
7073
}
7174

72-
private void registerBean(final ApiBean apiBean, final String namespaceId) {
73-
final URIRegisterDTO uriRegisterDTO = URIRegisterDTO.builder()
74-
.namespaceId(namespaceId)
75-
.contextPath(clientRegisterConfig.getContextPath())
76-
.appName(clientRegisterConfig.getAppName())
77-
.eventType(EventType.REGISTER)
78-
.host(clientRegisterConfig.getHost())
79-
.port(clientRegisterConfig.getPort())
80-
.rpcType(getRpcType(apiBean))
81-
.build();
82-
publisher.publishEvent(uriRegisterDTO);
75+
@Override
76+
protected void doRegisterApi(final ApiBean.ApiDefinition api) {
77+
registerUri(ApiBeanUtil.getRpcType(api));
8378
}
84-
85-
private static String getRpcType(final ApiBean.ApiDefinition api) {
86-
return ApiBeanUtil.getRpcType(api);
79+
80+
@Override
81+
protected void doRegisterBean(final ApiBean apiBean) {
82+
registerUri(ApiBeanUtil.getRpcType(apiBean));
8783
}
88-
89-
private static String getRpcType(final ApiBean api) {
90-
return ApiBeanUtil.getRpcType(api);
84+
85+
private synchronized void registerUri(final String rpcType) {
86+
int port = clientRegisterConfig.getPort();
87+
if (port <= 0 || port > MAX_PORT) {
88+
throw new IllegalArgumentException("Local URI registration requires a port between 1 and " + MAX_PORT);
89+
}
90+
for (String namespaceId : clientRegisterConfig.getNamespace()) {
91+
URIRegisterDTO uri = URIRegisterDTO.builder()
92+
.namespaceId(namespaceId)
93+
.contextPath(clientRegisterConfig.getContextPath())
94+
.appName(clientRegisterConfig.getAppName())
95+
.eventType(EventType.REGISTER)
96+
.host(clientRegisterConfig.getHost())
97+
.port(port)
98+
.rpcType(rpcType)
99+
.build();
100+
// Snapshot identity: heartbeat mutates the DTO, and enqueue is not an Admin acknowledgement.
101+
List<?> identity = Arrays.asList(namespaceId, rpcType, uri.getAppName(), uri.getContextPath(), uri.getHost(), port);
102+
if (!publishedIdentities.contains(identity)) {
103+
publisher.publishEvent(uri);
104+
publishedIdentities.add(identity);
105+
}
106+
}
91107
}
92-
93108
}

‎shenyu-client/shenyu-client-core/src/test/java/org/apache/shenyu/client/core/register/registrar/RegistrarNamespaceTest.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ void testUriAndMetadataUseIndependentNamespaceEvents() throws Exception {
6262
registrar.doRegisterBean(bean);
6363
registrar.doRegisterApi(bean.getApiDefinitions().get(0));
6464
ArgumentCaptor<DataTypeParent> captor = ArgumentCaptor.forClass(DataTypeParent.class);
65-
verify(publisher, times(4)).publishEvent(captor.capture());
65+
verify(publisher, times(registrar instanceof UriApiRegistrarImplImpl ? 2 : 4)).publishEvent(captor.capture());
6666
List<DataTypeParent> events = captor.getAllValues();
6767
for (int index = 0; index < events.size(); index += 2) {
6868
assertNotSame(events.get(index), events.get(index + 1));
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.client.core.register.registrar;
19+
20+
import org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher;
21+
import org.apache.shenyu.client.core.register.ApiBean;
22+
import org.apache.shenyu.client.core.register.ClientRegisterConfig;
23+
import org.apache.shenyu.register.common.dto.URIRegisterDTO;
24+
import org.apache.shenyu.register.common.enums.EventType;
25+
import org.junit.jupiter.api.BeforeEach;
26+
import org.junit.jupiter.api.Test;
27+
import org.mockito.ArgumentCaptor;
28+
import org.springframework.mock.env.MockEnvironment;
29+
import org.springframework.test.util.ReflectionTestUtils;
30+
31+
import java.util.List;
32+
33+
import static org.junit.jupiter.api.Assertions.assertEquals;
34+
import static org.junit.jupiter.api.Assertions.assertThrows;
35+
import static org.mockito.ArgumentMatchers.any;
36+
import static org.mockito.Mockito.doNothing;
37+
import static org.mockito.Mockito.mock;
38+
import static org.mockito.Mockito.times;
39+
import static org.mockito.Mockito.verify;
40+
import static org.mockito.Mockito.verifyNoInteractions;
41+
import static org.mockito.Mockito.when;
42+
43+
/** URI instance publication and retry ownership. */
44+
class UriApiRegistrarTest {
45+
46+
private final ClientRegisterConfig config = mock(ClientRegisterConfig.class);
47+
48+
private final ShenyuClientRegisterEventPublisher publisher = mock(ShenyuClientRegisterEventPublisher.class);
49+
50+
private UriApiRegistrarImplImpl registrar;
51+
52+
@BeforeEach
53+
void setUp() {
54+
when(config.getNamespace()).thenReturn(List.of("one", "two"));
55+
when(config.getHost()).thenReturn("127.0.0.1");
56+
when(config.getPort()).thenReturn(8080);
57+
when(config.getAppName()).thenReturn("app");
58+
when(config.getContextPath()).thenReturn("/app");
59+
registrar = new UriApiRegistrarImplImpl(config);
60+
ReflectionTestUtils.setField(registrar, "publisher", publisher);
61+
}
62+
63+
@Test
64+
void testBeanAndApisShareIdentityEvenAfterHeartbeatMutation() throws Exception {
65+
registrar.register(bean());
66+
ArgumentCaptor<URIRegisterDTO> events = ArgumentCaptor.forClass(URIRegisterDTO.class);
67+
verify(publisher, times(2)).publishEvent(events.capture());
68+
events.getAllValues().forEach(uri -> uri.setEventType(EventType.HEARTBEAT));
69+
registrar.register(bean());
70+
verify(publisher, times(2)).publishEvent(any());
71+
assertEquals(URIRegisterDTO.class, registrar.registerDataType());
72+
}
73+
74+
@Test
75+
void testEnqueueFailureCanRetryWithoutRepeatingPublishedNamespaces() throws Exception {
76+
doNothing().doThrow(new IllegalStateException("queue unavailable")).doNothing().when(publisher).publishEvent(any());
77+
assertThrows(IllegalStateException.class, () -> registrar.register(bean()));
78+
registrar.register(bean());
79+
ArgumentCaptor<URIRegisterDTO> events = ArgumentCaptor.forClass(URIRegisterDTO.class);
80+
verify(publisher, times(3)).publishEvent(events.capture());
81+
assertEquals(List.of("one", "two", "two"), events.getAllValues().stream().map(URIRegisterDTO::getNamespaceId).toList());
82+
}
83+
84+
@Test
85+
void testChangedInstanceIdentityIsNotSuppressed() throws Exception {
86+
registrar.register(bean());
87+
when(config.getAppName()).thenReturn("other-app");
88+
registrar.register(bean());
89+
when(config.getContextPath()).thenReturn("/other");
90+
registrar.register(bean());
91+
when(config.getPort()).thenReturn(8081);
92+
registrar.register(bean());
93+
when(config.getHost()).thenReturn("127.0.0.2");
94+
registrar.register(bean());
95+
verify(publisher, times(10)).publishEvent(any());
96+
}
97+
98+
@Test
99+
void testRpcTypesHaveIndependentIdentities() throws Exception {
100+
registrar.register(bean());
101+
ApiBean other = bean();
102+
other.addProperties("rpcType", "grpc");
103+
other.getApiDefinitions().forEach(api -> api.addProperties("rpcType", "grpc"));
104+
registrar.register(other);
105+
verify(publisher, times(4)).publishEvent(any());
106+
}
107+
108+
@Test
109+
void testInvalidPortIsNotPublished() {
110+
for (int port : List.of(-1, 0, 65536)) {
111+
when(config.getPort()).thenReturn(port);
112+
assertThrows(IllegalArgumentException.class, () -> registrar.register(bean()));
113+
}
114+
verifyNoInteractions(publisher);
115+
}
116+
117+
@Test
118+
void testNonLocalDiscoveryDoesNotReadLocalAddress() throws Exception {
119+
for (String mode : List.of("nacos", "LOCAL", "")) {
120+
registrar.setEnvironment(new MockEnvironment().withProperty("shenyu.discovery.type", mode));
121+
registrar.register(bean());
122+
}
123+
verifyNoInteractions(publisher);
124+
}
125+
126+
private ApiBean bean() throws Exception {
127+
ApiBean bean = new ApiBean("http", "endpoints", this, "/api");
128+
bean.addApiDefinition(Object.class.getMethod("toString"), "/one");
129+
bean.addApiDefinition(Object.class.getMethod("hashCode"), "/two");
130+
bean.setStatus(ApiBean.Status.REGISTRABLE);
131+
bean.getApiDefinitions().forEach(api -> api.setStatus(ApiBean.Status.REGISTRABLE));
132+
return bean;
133+
}
134+
}

‎shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springmvc/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,10 @@
4141
<artifactId>shenyu-client-autoconfig</artifactId>
4242
<version>${project.version}</version>
4343
</dependency>
44+
<dependency>
45+
<groupId>org.springframework.boot</groupId>
46+
<artifactId>spring-boot-starter-web</artifactId>
47+
<scope>test</scope>
48+
</dependency>
4449
</dependencies>
4550
</project>

0 commit comments

Comments
 (0)