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
42 changes: 42 additions & 0 deletions issue-spec/specs/opt-in-local-uri-registration/spec.md
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -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<ApiRegisterProcessor> processors) {
UriApiRegistrarImplImpl registrar = new UriApiRegistrarImplImpl(clientRegisterConfig);
processors.forEach(registrar::addApiProcessor);
return registrar;
}

/**
* api doc register.
*
Expand Down Expand Up @@ -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));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ default List<String> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>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<UriIdentity> 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) {
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ void testUriAndMetadataUseIndependentNamespaceEvents() throws Exception {
registrar.doRegisterBean(bean);
registrar.doRegisterApi(bean.getApiDefinitions().get(0));
ArgumentCaptor<DataTypeParent> captor = ArgumentCaptor.forClass(DataTypeParent.class);
verify(publisher, times(4)).publishEvent(captor.capture());
verify(publisher, times(registrar instanceof UriApiRegistrarImplImpl ? 2 : 4)).publishEvent(captor.capture());
List<DataTypeParent> events = captor.getAllValues();
for (int index = 0; index < events.size(); index += 2) {
assertNotSame(events.get(index), events.get(index + 1));
Expand Down
Loading
Loading