repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.script;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
* ScriptRouterFactory
* <p>
* Example URLS used by Script Router Factory:
* <ol>
* <li> script://registryAddress?type=js&rule=xxxx
* <li> script:///path/to/routerfile.js?type=js&rule=xxxx
* <li> script://D:\path\to\routerfile.js?type=js&rule=xxxx
* <li> script://C:/path/to/routerfile.js?type=js&rule=xxxx
* </ol>
* The host value in URL points out the address of the source content of the Script Router,Registry、File etc
*
*/
public class ScriptStateRouterFactory implements StateRouterFactory {
public static final String NAME = "script";
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
return new ScriptStateRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.script;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.support.RpcUtils;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_SCRIPT_EXCEPTION;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_SCRIPT_TYPE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
/**
* ScriptRouter
*/
public class ScriptStateRouter<T> extends AbstractStateRouter<T> {
public static final String NAME = "SCRIPT_ROUTER";
private static final int SCRIPT_ROUTER_DEFAULT_PRIORITY = 0;
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ScriptStateRouter.class);
private static final ConcurrentMap<String, ScriptEngine> ENGINES = new ConcurrentHashMap<>();
private final ScriptEngine engine;
private final String rule;
private CompiledScript function;
private AccessControlContext accessControlContext;
{
// Just give permission of reflect to access member.
Permissions perms = new Permissions();
perms.add(new RuntimePermission("accessDeclaredMembers"));
// Cast to Certificate[] required because of ambiguity:
ProtectionDomain domain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null), perms);
accessControlContext = new AccessControlContext(new ProtectionDomain[] {domain});
}
public ScriptStateRouter(URL url) {
super(url);
this.setUrl(url);
engine = getEngine(url);
rule = getRule(url);
try {
Compilable compilable = (Compilable) engine;
function = compilable.compile(rule);
} catch (ScriptException e) {
logger.error(
CLUSTER_SCRIPT_EXCEPTION,
"script route rule invalid",
"",
"script route error, rule has been ignored. rule: " + rule + ", url: "
+ RpcContext.getServiceContext().getUrl(),
e);
}
}
/**
* get rule from url parameters.
*/
private String getRule(URL url) {
String vRule = url.getParameterAndDecoded(RULE_KEY);
if (StringUtils.isEmpty(vRule)) {
throw new IllegalStateException("route rule can not be empty.");
}
return vRule;
}
/**
* create ScriptEngine instance by type from url parameters, then cache it
*/
private ScriptEngine getEngine(URL url) {
String type = url.getParameter(TYPE_KEY, DEFAULT_SCRIPT_TYPE_KEY);
return ConcurrentHashMapUtils.computeIfAbsent(ENGINES, type, t -> {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(type);
if (scriptEngine == null) {
throw new IllegalStateException("unsupported route engine type: " + type);
}
return scriptEngine;
});
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (engine == null || function == null) {
if (needToPrintMessage) {
messageHolder.set("Directly Return. Reason: engine or function is null");
}
return invokers;
}
Bindings bindings = createBindings(invokers, invocation);
return getRoutedInvokers(
invokers,
AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> {
try {
return function.eval(bindings);
} catch (ScriptException e) {
logger.error(
CLUSTER_SCRIPT_EXCEPTION,
"Scriptrouter exec script error",
"",
"Script route error, rule has been ignored. rule: " + rule + ", method:"
+ RpcUtils.getMethodName(invocation) + ", url: "
+ RpcContext.getContext().getUrl(),
e);
return invokers;
}
},
accessControlContext));
}
/**
* get routed invokers from result of script rule evaluation
*/
@SuppressWarnings("unchecked")
protected BitList<Invoker<T>> getRoutedInvokers(BitList<Invoker<T>> invokers, Object obj) {
BitList<Invoker<T>> result = invokers.clone();
if (obj instanceof Invoker[]) {
result.retainAll(Arrays.asList((Invoker<T>[]) obj));
} else if (obj instanceof Object[]) {
result.retainAll(
Arrays.stream((Object[]) obj).map(item -> (Invoker<T>) item).collect(Collectors.toList()));
} else {
result.retainAll((List<Invoker<T>>) obj);
}
return result;
}
/**
* create bindings for script engine
*/
private Bindings createBindings(List<Invoker<T>> invokers, Invocation invocation) {
Bindings bindings = engine.createBindings();
// create a new List of invokers
bindings.put("invokers", new ArrayList<>(invokers));
bindings.put("invocation", invocation);
bindings.put("context", RpcContext.getClientAttachment());
return bindings;
}
@Override
public boolean isRuntime() {
return this.getUrl().getParameter(RUNTIME_KEY, false);
}
@Override
public boolean isForce() {
return this.getUrl().getParameter(FORCE_KEY, false);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.script.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.script.ScriptStateRouter;
import org.apache.dubbo.rpc.cluster.router.script.config.model.ScriptRule;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_EMPTY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_INVALID;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_SCRIPT_TYPE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
public class AppScriptStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AppScriptStateRouter.class);
private static final String RULE_SUFFIX = ".script-router";
private ScriptRule scriptRule;
private ScriptStateRouter<T> scriptRouter;
private String application;
public AppScriptStateRouter(URL url) {
super(url);
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> routerSnapshotNodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (scriptRouter == null || !scriptRule.isValid() || !scriptRule.isEnabled()) {
if (needToPrintMessage) {
messageHolder.set(
"Directly return from script router. Reason: Invokers from previous router is empty or script is not enabled. Script rule is: "
+ (scriptRule == null ? "null" : scriptRule.getRawRule()));
}
return invokers;
}
invokers = scriptRouter.route(invokers, url, invocation, needToPrintMessage, routerSnapshotNodeHolder);
if (needToPrintMessage) {
messageHolder.set(messageHolder.get());
}
return invokers;
}
@Override
public synchronized void process(ConfigChangedEvent event) {
if (logger.isDebugEnabled()) {
logger.debug("Notification of script rule change, type is: " + event.getChangeType() + ", raw rule is:\n "
+ event.getContent());
}
try {
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
this.scriptRule = null;
} else {
this.scriptRule = ScriptRule.parse(event.getContent());
URL scriptUrl = getUrl().addParameter(
TYPE_KEY,
isEmpty(scriptRule.getType()) ? DEFAULT_SCRIPT_TYPE_KEY : scriptRule.getType())
.addParameterAndEncoded(RULE_KEY, scriptRule.getScript())
.addParameter(FORCE_KEY, scriptRule.isForce())
.addParameter(RUNTIME_KEY, scriptRule.isRuntime());
scriptRouter = new ScriptStateRouter<>(scriptUrl);
}
} catch (Exception e) {
logger.error(
CLUSTER_TAG_ROUTE_INVALID,
"Failed to parse the raw tag router rule",
"",
"Failed to parse the raw tag router rule and it will not take effect, please check if the "
+ "rule matches with the template, the raw rule is:\n ",
e);
}
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
if (CollectionUtils.isEmpty(invokers)) {
return;
}
Invoker<T> invoker = invokers.get(0);
URL url = invoker.getUrl();
String providerApplication = url.getRemoteApplication();
if (isEmpty(providerApplication)) {
logger.error(
CLUSTER_TAG_ROUTE_EMPTY,
"tag router get providerApplication is empty",
"",
"TagRouter must getConfig from or subscribe to a specific application, but the application "
+ "in this TagRouter is not specified.");
return;
}
synchronized (this) {
if (!providerApplication.equals(application)) {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
String key = providerApplication + RULE_SUFFIX;
this.getRuleRepository().addListener(key, this);
application = providerApplication;
String rawRule = this.getRuleRepository().getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rawRule)) {
this.process(new ConfigChangedEvent(key, DynamicConfiguration.DEFAULT_GROUP, rawRule));
}
}
}
}
@Override
public void stop() {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
}
// for testing purpose
public void setScriptRule(ScriptRule scriptRule) {
this.scriptRule = scriptRule;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.script.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
@Activate(order = 200)
public class AppScriptRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "script";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new AppScriptStateRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java | /*
* 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.dubbo.rpc.cluster.router.script.config.model;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import java.util.Map;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
public class ScriptRule extends AbstractRouterRule {
private static final String TYPE_KEY = "type";
private static final String SCRIPT_KEY = "script";
private String type;
private String script;
public static ScriptRule parse(String rawRule) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawRule);
ScriptRule rule = new ScriptRule();
rule.parseFromMap0(map);
rule.setRawRule(rawRule);
Object rawType = map.get(TYPE_KEY);
if (rawType != null) {
rule.setType((String) rawType);
}
Object rawScript = map.get(SCRIPT_KEY);
if (rawScript != null) {
rule.setScript((String) rawScript);
} else {
rule.setValid(false);
}
return rule;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/MultiDestConditionRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/MultiDestConditionRouter.java | /*
* 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.dubbo.rpc.cluster.router.condition;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionSubSet;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.DestinationSet;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.MultiDestCondition;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
import static org.apache.dubbo.rpc.cluster.Constants.DefaultRouteConditionSubSetWeight;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
public class MultiDestConditionRouter<T> extends AbstractStateRouter<T> {
public static final String NAME = "multi_condition";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractStateRouter.class);
protected static final Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)");
private Map<String, ConditionMatcher> whenCondition;
private List<ConditionSubSet> thenCondition;
private boolean force;
protected List<ConditionMatcherFactory> matcherFactories;
private boolean enabled;
public MultiDestConditionRouter(URL url, MultiDestCondition multiDestCondition, boolean force, boolean enabled) {
super(url);
this.setForce(force);
this.enabled = enabled;
matcherFactories =
moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions();
this.init(multiDestCondition.getFrom(), multiDestCondition.getTo());
}
public void init(Map<String, String> from, List<Map<String, String>> to) {
try {
if (from == null || to == null) {
throw new IllegalArgumentException("Illegal route rule!");
}
String whenRule = from.get("match");
Map<String, ConditionMatcher> when =
StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<>() : parseRule(whenRule);
this.whenCondition = when;
List<ConditionSubSet> thenConditions = new ArrayList<>();
for (Map<String, String> toMap : to) {
String thenRule = toMap.get("match");
Map<String, ConditionMatcher> then = StringUtils.isBlank(thenRule) || "false".equals(thenRule)
? new HashMap<>()
: parseRule(thenRule);
// NOTE: It should be determined on the business level whether the `When condition` can be empty or not.
thenConditions.add(new ConditionSubSet(
then,
Integer.valueOf(
toMap.getOrDefault("weight", String.valueOf(DefaultRouteConditionSubSetWeight)))));
}
this.thenCondition = thenConditions;
} catch (ParseException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private Map<String, ConditionMatcher> parseRule(String rule) throws ParseException {
Map<String, ConditionMatcher> condition = new HashMap<>();
if (StringUtils.isBlank(rule)) {
return condition;
}
// Key-Value pair, stores both match and mismatch conditions
ConditionMatcher matcherPair = null;
// Multiple values
Set<String> values = null;
final Matcher matcher = ROUTE_PATTERN.matcher(rule);
while (matcher.find()) { // Try to match one by one
String separator = matcher.group(1);
String content = matcher.group(2);
// Start part of the condition expression.
if (StringUtils.isEmpty(separator)) {
matcherPair = this.getMatcher(content);
condition.put(content, matcherPair);
}
// The KV part of the condition expression
else if ("&".equals(separator)) {
if (condition.get(content) == null) {
matcherPair = this.getMatcher(content);
condition.put(content, matcherPair);
} else {
matcherPair = condition.get(content);
}
}
// The Value in the KV part.
else if ("=".equals(separator)) {
if (matcherPair == null) {
throw new ParseException(
"Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index "
+ matcher.start() + " before \"" + content + "\".",
matcher.start());
}
values = matcherPair.getMatches();
values.add(content);
}
// The Value in the KV part.
else if ("!=".equals(separator)) {
if (matcherPair == null) {
throw new ParseException(
"Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index "
+ matcher.start() + " before \"" + content + "\".",
matcher.start());
}
values = matcherPair.getMismatches();
values.add(content);
}
// The Value in the KV part, if Value have more than one items.
else if (",".equals(separator)) { // Should be separated by ','
if (values == null || values.isEmpty()) {
throw new ParseException(
"Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index "
+ matcher.start() + " before \"" + content + "\".",
matcher.start());
}
values.add(content);
} else {
throw new ParseException(
"Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index "
+ matcher.start() + " before \"" + content + "\".",
matcher.start());
}
}
return condition;
}
private ConditionMatcher getMatcher(String key) {
for (ConditionMatcherFactory factory : matcherFactories) {
if (factory.shouldMatch(key)) {
return factory.createMatcher(key, moduleModel);
}
}
return moduleModel
.getExtensionLoader(ConditionMatcherFactory.class)
.getExtension("param")
.createMatcher(key, moduleModel);
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> routerSnapshotNodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (!enabled) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: ConditionRouter disabled.");
}
return invokers;
}
if (CollectionUtils.isEmpty(invokers)) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: Invokers from previous router is empty.");
}
return invokers;
}
try {
if (!matchWhen(url, invocation)) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: WhenCondition not match.");
}
return invokers;
}
if (thenCondition == null || thenCondition.size() == 0) {
logger.warn(
CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,
"condition state router thenCondition is empty",
"",
"The current consumer in the service blocklist. consumer: " + NetUtils.getLocalHost()
+ ", service: " + url.getServiceKey());
if (needToPrintMessage) {
messageHolder.set("Empty return. Reason: ThenCondition is empty.");
}
return BitList.emptyList();
}
DestinationSet destinations = new DestinationSet();
for (ConditionSubSet condition : thenCondition) {
BitList<Invoker<T>> res = invokers.clone();
for (Invoker invoker : invokers) {
if (!doMatch(invoker.getUrl(), url, null, condition.getCondition(), false)) {
res.remove(invoker);
}
}
if (!res.isEmpty()) {
destinations.addDestination(
condition.getSubSetWeight() == null
? DefaultRouteConditionSubSetWeight
: condition.getSubSetWeight(),
res.clone());
}
}
if (!destinations.getDestinations().isEmpty()) {
BitList<Invoker<T>> res = destinations.randDestination();
return res;
} else if (this.isForce()) {
logger.warn(
CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,
"execute condition state router result list is " + "empty. and force=true",
"",
"The route result is empty and force execute. consumer: " + NetUtils.getLocalHost()
+ ", service: " + url.getServiceKey() + ", router: "
+ url.getParameterAndDecoded(RULE_KEY));
if (needToPrintMessage) {
messageHolder.set("Empty return. Reason: Empty result from condition and condition is force.");
}
return BitList.emptyList();
}
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"execute condition state router exception",
"",
"Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: "
+ t.getMessage(),
t);
}
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: Error occurred ( or result is empty ).");
}
return invokers;
}
boolean matchWhen(URL url, Invocation invocation) {
if (CollectionUtils.isEmptyMap(whenCondition)) {
return true;
}
return doMatch(url, null, invocation, whenCondition, true);
}
private boolean doMatch(
URL url,
URL param,
Invocation invocation,
Map<String, ConditionMatcher> conditions,
boolean isWhenCondition) {
Map<String, String> sample = url.toOriginalMap();
for (Map.Entry<String, ConditionMatcher> entry : conditions.entrySet()) {
ConditionMatcher matchPair = entry.getValue();
if (!matchPair.isMatch(sample, param, invocation, isWhenCondition)) {
return false;
}
}
return true;
}
public void setWhenCondition(Map<String, ConditionMatcher> whenCondition) {
this.whenCondition = whenCondition;
}
public void setThenCondition(List<ConditionSubSet> thenCondition) {
this.thenCondition = thenCondition;
}
public void setForce(boolean force) {
this.force = force;
}
public Map<String, ConditionMatcher> getWhenCondition() {
return whenCondition;
}
public boolean isForce() {
return force;
}
public List<ConditionSubSet> getThenCondition() {
return thenCondition;
}
public List<ConditionMatcherFactory> getMatcherFactories() {
return matcherFactories;
}
public void setMatcherFactories(List<ConditionMatcherFactory> matcherFactories) {
this.matcherFactories = matcherFactories;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* ConditionRouterFactory
* Load when "override://" is configured {@link ConditionStateRouter}
*/
public class ConditionStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "condition";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new ConditionStateRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.condition;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
/**
* Condition Router directs traffics matching the 'when condition' to a particular address subset determined by the 'then condition'.
* One typical condition rule is like below, with
* 1. the 'when condition' on the left side of '=>' contains matching rule like 'method=sayHello' and 'method=sayHi'
* 2. the 'then condition' on the right side of '=>' contains matching rule like 'region=hangzhou' and 'address=*:20881'
* <p>
* By default, condition router support matching rules like 'foo=bar', 'foo=bar*', 'arguments[0]=bar', 'attachments[foo]=bar', 'attachments[foo]=1~100', etc.
* It's also very easy to add customized matching rules by extending {@link ConditionMatcherFactory}
* and {@link ValuePattern}
* <p>
* ---
* scope: service
* force: true
* runtime: true
* enabled: true
* key: org.apache.dubbo.samples.governance.api.DemoService
* conditions:
* - method=sayHello => region=hangzhou
* - method=sayHi => address=*:20881
* ...
*/
public class ConditionStateRouter<T> extends AbstractStateRouter<T> {
public static final String NAME = "condition";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractStateRouter.class);
protected static final Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)");
protected Map<String, ConditionMatcher> whenCondition;
protected Map<String, ConditionMatcher> thenCondition;
protected List<ConditionMatcherFactory> matcherFactories;
private final boolean enabled;
public ConditionStateRouter(URL url, String rule, boolean force, boolean enabled) {
super(url);
this.setForce(force);
this.enabled = enabled;
matcherFactories =
moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions();
if (enabled) {
this.init(rule);
}
}
public ConditionStateRouter(URL url) {
super(url);
this.setUrl(url);
this.setForce(url.getParameter(FORCE_KEY, false));
matcherFactories =
moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions();
this.enabled = url.getParameter(ENABLED_KEY, true);
if (enabled) {
init(url.getParameterAndDecoded(RULE_KEY));
}
}
public void init(String rule) {
try {
if (rule == null || rule.trim().length() == 0) {
throw new IllegalArgumentException("Illegal route rule!");
}
rule = rule.replace("consumer.", "").replace("provider.", "");
int i = rule.indexOf("=>");
String whenRule = i < 0 ? null : rule.substring(0, i).trim();
String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim();
Map<String, ConditionMatcher> when =
StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<>() : parseRule(whenRule);
Map<String, ConditionMatcher> then =
StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule);
// NOTE: It should be determined on the business level whether the `When condition` can be empty or not.
this.whenCondition = when;
this.thenCondition = then;
} catch (ParseException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private Map<String, ConditionMatcher> parseRule(String rule) throws ParseException {
Map<String, ConditionMatcher> condition = new HashMap<>();
if (StringUtils.isBlank(rule)) {
return condition;
}
// Key-Value pair, stores both match and mismatch conditions
ConditionMatcher matcherPair = null;
// Multiple values
Set<String> values = null;
final Matcher matcher = ROUTE_PATTERN.matcher(rule);
while (matcher.find()) { // Try to match one by one
String separator = matcher.group(1);
String content = matcher.group(2);
// Start part of the condition expression.
if (StringUtils.isEmpty(separator)) {
matcherPair = this.getMatcher(content);
condition.put(content, matcherPair);
}
// The KV part of the condition expression
else if ("&".equals(separator)) {
if (condition.get(content) == null) {
matcherPair = this.getMatcher(content);
condition.put(content, matcherPair);
} else {
matcherPair = condition.get(content);
}
}
// The Value in the KV part.
else if ("=".equals(separator)) {
if (matcherPair == null) {
throw new ParseException(
"Illegal route rule \""
+ rule + "\", The error char '" + separator
+ "' at index " + matcher.start() + " before \""
+ content + "\".",
matcher.start());
}
values = matcherPair.getMatches();
values.add(content);
}
// The Value in the KV part.
else if ("!=".equals(separator)) {
if (matcherPair == null) {
throw new ParseException(
"Illegal route rule \""
+ rule + "\", The error char '" + separator
+ "' at index " + matcher.start() + " before \""
+ content + "\".",
matcher.start());
}
values = matcherPair.getMismatches();
values.add(content);
}
// The Value in the KV part, if Value have more than one items.
else if (",".equals(separator)) { // Should be separated by ','
if (values == null || values.isEmpty()) {
throw new ParseException(
"Illegal route rule \""
+ rule + "\", The error char '" + separator
+ "' at index " + matcher.start() + " before \""
+ content + "\".",
matcher.start());
}
values.add(content);
} else {
throw new ParseException(
"Illegal route rule \"" + rule
+ "\", The error char '" + separator + "' at index "
+ matcher.start() + " before \"" + content + "\".",
matcher.start());
}
}
return condition;
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (!enabled) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: ConditionRouter disabled.");
}
return invokers;
}
if (CollectionUtils.isEmpty(invokers)) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: Invokers from previous router is empty.");
}
return invokers;
}
try {
if (!matchWhen(url, invocation)) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: WhenCondition not match.");
}
return invokers;
}
if (thenCondition == null) {
logger.warn(
CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,
"condition state router thenCondition is empty",
"",
"The current consumer in the service blocklist. consumer: " + NetUtils.getLocalHost()
+ ", service: " + url.getServiceKey());
if (needToPrintMessage) {
messageHolder.set("Empty return. Reason: ThenCondition is empty.");
}
return BitList.emptyList();
}
BitList<Invoker<T>> result = invokers.clone();
result.removeIf(invoker -> !matchThen(invoker.getUrl(), url));
if (!result.isEmpty()) {
if (needToPrintMessage) {
messageHolder.set("Match return.");
}
return result;
} else if (this.isForce()) {
logger.warn(
CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,
"execute condition state router result list is empty. and force=true",
"",
"The route result is empty and force execute. consumer: " + NetUtils.getLocalHost()
+ ", service: " + url.getServiceKey() + ", router: "
+ url.getParameterAndDecoded(RULE_KEY));
if (needToPrintMessage) {
messageHolder.set("Empty return. Reason: Empty result from condition and condition is force.");
}
return result;
}
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"execute condition state router exception",
"",
"Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: "
+ t.getMessage(),
t);
}
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: Error occurred ( or result is empty ).");
}
return invokers;
}
@Override
public boolean isRuntime() {
// We always return true for previously defined Router, that is, old Router doesn't support cache anymore.
// return true;
return this.getUrl().getParameter(RUNTIME_KEY, false);
}
private ConditionMatcher getMatcher(String key) {
for (ConditionMatcherFactory factory : matcherFactories) {
if (factory.shouldMatch(key)) {
return factory.createMatcher(key, moduleModel);
}
}
return moduleModel
.getExtensionLoader(ConditionMatcherFactory.class)
.getExtension("param")
.createMatcher(key, moduleModel);
}
boolean matchWhen(URL url, Invocation invocation) {
if (CollectionUtils.isEmptyMap(whenCondition)) {
return true;
}
return doMatch(url, null, invocation, whenCondition, true);
}
private boolean matchThen(URL url, URL param) {
if (CollectionUtils.isEmptyMap(thenCondition)) {
return false;
}
return doMatch(url, param, null, thenCondition, false);
}
private boolean doMatch(
URL url,
URL param,
Invocation invocation,
Map<String, ConditionMatcher> conditions,
boolean isWhenCondition) {
Map<String, String> sample = url.toOriginalMap();
for (Map.Entry<String, ConditionMatcher> entry : conditions.entrySet()) {
ConditionMatcher matchPair = entry.getValue();
if (!matchPair.isMatch(sample, param, invocation, isWhenCondition)) {
return false;
}
}
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/ConditionMatcherFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/ConditionMatcherFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ModuleModel;
/**
* Factory of ConditionMatcher instances.
*/
@SPI
public interface ConditionMatcherFactory {
/**
* Check if the key is of the form of the current matcher type which this factory instance represents..
*
* @param key the key of a particular form
* @return true if matches, otherwise false
*/
boolean shouldMatch(String key);
/**
* Create a matcher instance for the key.
*
* @param key the key value conforms to a specific matcher specification
* @param model module model
* @return the specific matcher instance
*/
ConditionMatcher createMatcher(String key, ModuleModel model);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* The abstract implementation of ConditionMatcher, records the match and mismatch patterns of this matcher while at the same time
* provides the common match logics.
*/
public abstract class AbstractConditionMatcher implements ConditionMatcher {
public static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractConditionMatcher.class);
public static final String DOES_NOT_FOUND_VALUE = "dubbo_internal_not_found_argument_condition_value";
final Set<String> matches = new HashSet<>();
final Set<String> mismatches = new HashSet<>();
private final ModuleModel model;
private final List<ValuePattern> valueMatchers;
protected final String key;
public AbstractConditionMatcher(String key, ModuleModel model) {
this.key = key;
this.model = model;
this.valueMatchers = model.getExtensionLoader(ValuePattern.class).getActivateExtensions();
}
public static String getSampleValueFromUrl(
String conditionKey, Map<String, String> sample, URL param, Invocation invocation) {
String sampleValue;
// get real invoked method name from invocation
if (invocation != null && (METHOD_KEY.equals(conditionKey) || METHODS_KEY.equals(conditionKey))) {
sampleValue = RpcUtils.getMethodName(invocation);
} else {
sampleValue = sample.get(conditionKey);
}
return sampleValue;
}
public boolean isMatch(Map<String, String> sample, URL param, Invocation invocation, boolean isWhenCondition) {
String value = getValue(sample, param, invocation);
if (value == null) {
// if key does not present in whichever of url, invocation or attachment based on the matcher type, then
// return false.
return false;
}
if (!matches.isEmpty() && mismatches.isEmpty()) {
for (String match : matches) {
if (doPatternMatch(match, value, param, invocation, isWhenCondition)) {
return true;
}
}
return false;
}
if (!mismatches.isEmpty() && matches.isEmpty()) {
for (String mismatch : mismatches) {
if (doPatternMatch(mismatch, value, param, invocation, isWhenCondition)) {
return false;
}
}
return true;
}
if (!matches.isEmpty() && !mismatches.isEmpty()) {
// when both mismatches and matches contain the same value, then using mismatches first
for (String mismatch : mismatches) {
if (doPatternMatch(mismatch, value, param, invocation, isWhenCondition)) {
return false;
}
}
for (String match : matches) {
if (doPatternMatch(match, value, param, invocation, isWhenCondition)) {
return true;
}
}
return false;
}
return false;
}
@Override
public Set<String> getMatches() {
return matches;
}
@Override
public Set<String> getMismatches() {
return mismatches;
}
// range, equal or other methods
protected boolean doPatternMatch(
String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) {
for (ValuePattern valueMatcher : valueMatchers) {
if (valueMatcher.shouldMatch(pattern)) {
return valueMatcher.match(pattern, value, url, invocation, isWhenCondition);
}
}
// this should never happen.
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Executing condition rule value match expression error.",
"pattern is " + pattern + ", value is " + value + ", condition type "
+ (isWhenCondition ? "when" : "then"),
"There should at least has one ValueMatcher instance that applies to all patterns, will force to use wildcard matcher now.");
ValuePattern paramValueMatcher =
model.getExtensionLoader(ValuePattern.class).getExtension("wildcard");
return paramValueMatcher.match(pattern, value, url, invocation, isWhenCondition);
}
/**
* Used to get value from different places of the request context, for example, url, attachment and invocation.
* This makes condition rule possible to check values in any place of a request.
*/
protected abstract String getValue(Map<String, String> sample, URL url, Invocation invocation);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/ConditionMatcher.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/ConditionMatcher.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import java.util.Map;
import java.util.Set;
/**
* ConditionMatcher represents a specific match condition of a condition rule.
* <p>
* The following condition rule '=bar&arguments[0]=hello* => region=hangzhou' consists of three ConditionMatchers:
* 1. UrlParamConditionMatcher represented by 'foo=bar'
* 2. ArgumentsConditionMatcher represented by 'arguments[0]=hello*'
* 3. UrlParamConditionMatcher represented by 'region=hangzhou'
* <p>
* It's easy to define your own matcher by extending {@link ConditionMatcherFactory}
*/
public interface ConditionMatcher {
/**
* Determines if the patterns of this matcher matches with request context.
*
* @param sample request context in provider url
* @param param request context in consumer url
* @param invocation request context in invocation, typically, service, method, arguments and attachments
* @param isWhenCondition condition type
* @return the matching result
*/
boolean isMatch(Map<String, String> sample, URL param, Invocation invocation, boolean isWhenCondition);
/**
* match patterns extracted from when condition
*
* @return
*/
Set<String> getMatches();
/**
* mismatch patterns extracted from then condition
*
* @return
*/
Set<String> getMismatches();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.attachment;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.AbstractConditionMatcher;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* analysis the arguments in the rule.
* Examples would be like this:
* "attachments[foo]=bar", whenCondition is that the attachment value of 'foo' is equal to 'bar'.
*/
@Activate
public class AttachmentConditionMatcher extends AbstractConditionMatcher {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AttachmentConditionMatcher.class);
private static final Pattern ATTACHMENTS_PATTERN = Pattern.compile("attachments\\[(.+)\\]");
public AttachmentConditionMatcher(String key, ModuleModel model) {
super(key, model);
}
@Override
protected String getValue(Map<String, String> sample, URL url, Invocation invocation) {
try {
// split the rule
String[] expressArray = key.split("\\.");
String argumentExpress = expressArray[0];
final Matcher matcher = ATTACHMENTS_PATTERN.matcher(argumentExpress);
if (!matcher.find()) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument index
String attachmentKey = matcher.group(1);
if (StringUtils.isEmpty(attachmentKey)) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument value
return invocation.getAttachment(attachmentKey);
} catch (Exception e) {
logger.warn(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"condition state router attachment match failed",
"",
"Invalid match condition: " + key,
e);
}
return DOES_NOT_FOUND_VALUE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcherFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcherFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.attachment;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
@Activate(order = 200)
public class AttachmentConditionMatcherFactory implements ConditionMatcherFactory {
private static final String ATTACHMENTS = "attachments";
@Override
public boolean shouldMatch(String key) {
return key.startsWith(ATTACHMENTS);
}
@Override
public ConditionMatcher createMatcher(String key, ModuleModel model) {
return new AttachmentConditionMatcher(key, model);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/ValuePattern.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/ValuePattern.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.pattern;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
@SPI
public interface ValuePattern {
/**
* Is the input pattern of a specific form, for example, range pattern '1~100', wildcard pattern 'hello*', etc.
*
* @param pattern the match or mismatch pattern
* @return true or false
*/
boolean shouldMatch(String pattern);
/**
* Is the pattern matches with the request context
*
* @param pattern pattern value extracted from condition rule
* @param value the real value extracted from request context
* @param url request context in consumer url
* @param invocation request context in invocation
* @param isWhenCondition condition type
* @return true if successfully match
*/
boolean match(String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.pattern.range;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* Matches with patterns like 'key=1~100', 'key=~100' or 'key=1~'
*/
@Activate(order = 100)
public class RangeValuePattern implements ValuePattern {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RangeValuePattern.class);
@Override
public boolean shouldMatch(String pattern) {
return pattern.contains("~");
}
@Override
public boolean match(String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) {
boolean defaultValue = !isWhenCondition;
try {
int intValue = StringUtils.parseInteger(value);
String[] arr = pattern.split("~");
if (arr.length < 2) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"",
"",
"Invalid condition rule " + pattern + " or value " + value + ", will ignore.");
return defaultValue;
}
String rawStart = arr[0];
String rawEnd = arr[1];
if (StringUtils.isEmpty(rawStart) && StringUtils.isEmpty(rawEnd)) {
return defaultValue;
}
if (StringUtils.isEmpty(rawStart)) {
int end = StringUtils.parseInteger(rawEnd);
if (intValue > end) {
return false;
}
} else if (StringUtils.isEmpty(rawEnd)) {
int start = StringUtils.parseInteger(rawStart);
if (intValue < start) {
return false;
}
} else {
int start = StringUtils.parseInteger(rawStart);
int end = StringUtils.parseInteger(rawEnd);
if (intValue < start || intValue > end) {
return false;
}
}
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Parse integer error",
"",
"Invalid condition rule " + pattern + " or value " + value + ", will ignore.",
e);
return defaultValue;
}
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/wildcard/WildcardValuePattern.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/wildcard/WildcardValuePattern.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.pattern.wildcard;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
/**
* Matches with patterns like 'key=hello', 'key=hello*', 'key=*hello', 'key=h*o' or 'key=*'
* <p>
* This pattern evaluator must be the last one being executed.
*/
@Activate(order = Integer.MAX_VALUE)
public class WildcardValuePattern implements ValuePattern {
@Override
public boolean shouldMatch(String key) {
return true;
}
@Override
public boolean match(String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) {
return UrlUtils.isMatchGlobPattern(pattern, value, url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.argument;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.AbstractConditionMatcher;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* analysis the arguments in the rule.
* Examples would be like this:
* "arguments[0]=1", whenCondition is that the first argument is equal to '1'.
* "arguments[1]=a", whenCondition is that the second argument is equal to 'a'.
*/
@Activate
public class ArgumentConditionMatcher extends AbstractConditionMatcher {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ArgumentConditionMatcher.class);
private static final Pattern ARGUMENTS_PATTERN = Pattern.compile("arguments\\[([0-9]+)\\]");
public ArgumentConditionMatcher(String key, ModuleModel model) {
super(key, model);
}
@Override
public String getValue(Map<String, String> sample, URL url, Invocation invocation) {
try {
// split the rule
String[] expressArray = key.split("\\.");
String argumentExpress = expressArray[0];
final Matcher matcher = ARGUMENTS_PATTERN.matcher(argumentExpress);
if (!matcher.find()) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument index
int index = Integer.parseInt(matcher.group(1));
if (index < 0 || index > invocation.getArguments().length) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument value
return String.valueOf(invocation.getArguments()[index]);
} catch (Exception e) {
logger.warn(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Parse argument match condition failed",
"",
"Invalid , will ignore., ",
e);
}
return DOES_NOT_FOUND_VALUE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcherFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcherFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.argument;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.Constants;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
@Activate(order = 300)
public class ArgumentConditionMatcherFactory implements ConditionMatcherFactory {
@Override
public boolean shouldMatch(String key) {
return key.startsWith(Constants.ARGUMENTS);
}
@Override
public ConditionMatcher createMatcher(String key, ModuleModel model) {
return new ArgumentConditionMatcher(key, model);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.param;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.AbstractConditionMatcher;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
/**
* This instance will be loaded separately to ensure it always gets executed as the last matcher.
* So we don't put Active annotation here.
*/
public class UrlParamConditionMatcher extends AbstractConditionMatcher {
public UrlParamConditionMatcher(String key, ModuleModel model) {
super(key, model);
}
@Override
protected String getValue(Map<String, String> sample, URL url, Invocation invocation) {
return getSampleValueFromUrl(key, sample, url, invocation);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcherFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcherFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition.matcher.param;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
// Make sure this is the last matcher being executed.
@Activate(order = Integer.MAX_VALUE)
public class UrlParamConditionMatcherFactory implements ConditionMatcherFactory {
@Override
public boolean shouldMatch(String key) {
return true;
}
@Override
public ConditionMatcher createMatcher(String key, ModuleModel model) {
return new UrlParamConditionMatcher(key, model);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
* Application level router factory
* AppRouter should after ServiceRouter
*/
@Activate(order = 150)
public class AppStateRouterFactory implements StateRouterFactory {
public static final String NAME = "app";
@SuppressWarnings("rawtypes")
private volatile StateRouter router;
@SuppressWarnings("unchecked")
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
if (router != null) {
return router;
}
synchronized (this) {
if (router == null) {
router = createRouter(url);
}
}
return router;
}
private <T> StateRouter<T> createRouter(URL url) {
return new AppStateRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
/**
* Service level router, "server-unique-name.condition-router"
*/
public class ServiceStateRouter<T> extends ListenableStateRouter<T> {
public static final String NAME = "SERVICE_ROUTER";
public ServiceStateRouter(URL url) {
super(url, DynamicConfiguration.getRuleKey(url));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouter;
import org.apache.dubbo.rpc.cluster.router.condition.MultiDestConditionRouter;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRouterRule;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRuleParser;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.MultiDestConditionRouterRule;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.TailStateRouter;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RULE_PARSING;
/**
* Abstract router which listens to dynamic configuration
*/
public abstract class ListenableStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
public static final String NAME = "LISTENABLE_ROUTER";
public static final String RULE_SUFFIX = ".condition-router";
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class);
private volatile AbstractRouterRule routerRule;
private volatile List<ConditionStateRouter<T>> conditionRouters = Collections.emptyList();
// for v3.1
private volatile List<MultiDestConditionRouter<T>> multiDestConditionRouters = Collections.emptyList();
private final String ruleKey;
public ListenableStateRouter(URL url, String ruleKey) {
super(url);
this.setForce(false);
this.init(ruleKey);
this.ruleKey = ruleKey;
}
@Override
public synchronized void process(ConfigChangedEvent event) {
if (logger.isInfoEnabled()) {
logger.info("Notification of condition rule, change type is: " + event.getChangeType() + ", raw rule is:\n "
+ event.getContent());
}
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
routerRule = null;
conditionRouters = Collections.emptyList();
// for v3.1
multiDestConditionRouters = Collections.emptyList();
} else {
try {
routerRule = ConditionRuleParser.parse(event.getContent());
generateConditions(routerRule);
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_RULE_PARSING,
"Failed to parse the raw condition rule",
"",
"Failed to parse the raw condition rule and it will not take effect, please check "
+ "if the condition rule matches with the template, the raw rule is:\n "
+ event.getContent(),
e);
}
}
}
@Override
public BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (CollectionUtils.isEmpty(invokers)
|| (conditionRouters.size() == 0 && multiDestConditionRouters.size() == 0)) {
if (needToPrintMessage) {
messageHolder.set(
"Directly return. Reason: Invokers from previous router is empty or conditionRouters is empty.");
}
return invokers;
}
// We will check enabled status inside each router.
StringBuilder resultMessage = null;
if (needToPrintMessage) {
resultMessage = new StringBuilder();
}
List<? extends AbstractStateRouter<T>> routers;
if (routerRule instanceof MultiDestConditionRouterRule) {
routers = multiDestConditionRouters;
} else {
routers = conditionRouters;
}
for (AbstractStateRouter<T> router : routers) {
invokers = router.route(invokers, url, invocation, needToPrintMessage, nodeHolder);
if (needToPrintMessage) {
resultMessage.append(messageHolder.get());
}
}
if (needToPrintMessage) {
messageHolder.set(resultMessage.toString());
}
return invokers;
}
@Override
public boolean isForce() {
return (routerRule != null && routerRule.isForce());
}
private boolean isRuleRuntime() {
return routerRule != null && routerRule.isValid() && routerRule.isRuntime();
}
private void generateConditions(AbstractRouterRule rule) {
if (rule == null || !rule.isValid()) {
return;
}
if (rule instanceof ConditionRouterRule) {
this.conditionRouters = ((ConditionRouterRule) rule)
.getConditions().stream()
.map(condition ->
new ConditionStateRouter<T>(getUrl(), condition, rule.isForce(), rule.isEnabled()))
.collect(Collectors.toList());
for (ConditionStateRouter<T> conditionRouter : this.conditionRouters) {
conditionRouter.setNextRouter(TailStateRouter.getInstance());
}
} else if (rule instanceof MultiDestConditionRouterRule) {
this.multiDestConditionRouters = ((MultiDestConditionRouterRule) rule)
.getConditions().stream()
.map(condition -> new MultiDestConditionRouter<T>(
getUrl(), condition, rule.isForce(), rule.isEnabled()))
.collect(Collectors.toList());
for (MultiDestConditionRouter<T> conditionRouter : this.multiDestConditionRouters) {
conditionRouter.setNextRouter(TailStateRouter.getInstance());
}
}
}
private synchronized void init(String ruleKey) {
if (StringUtils.isEmpty(ruleKey)) {
return;
}
String routerKey = ruleKey + RULE_SUFFIX;
this.getRuleRepository().addListener(routerKey, this);
String rule = this.getRuleRepository().getRule(routerKey, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rule)) {
this.process(new ConfigChangedEvent(routerKey, DynamicConfiguration.DEFAULT_GROUP, rule));
}
}
@Override
public void stop() {
this.getRuleRepository().removeListener(ruleKey + RULE_SUFFIX, this);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
/**
* Application level router, "application.condition-router"
*/
public class AppStateRouter<T> extends ListenableStateRouter<T> {
public static final String NAME = "APP_ROUTER";
public AppStateRouter(URL url) {
super(url, url.getApplication());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
@Activate(order = 145)
public class ProviderAppStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "provider-app";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new ProviderAppStateRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_EMPTY;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
/**
* Application level router, "application.condition-router"
*/
public class ProviderAppStateRouter<T> extends ListenableStateRouter<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class);
public static final String NAME = "PROVIDER_APP_ROUTER";
private String application;
private final String currentApplication;
public ProviderAppStateRouter(URL url) {
super(url, url.getApplication());
this.currentApplication = url.getApplication();
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
if (CollectionUtils.isEmpty(invokers)) {
return;
}
Invoker<T> invoker = invokers.get(0);
URL url = invoker.getUrl();
String providerApplication = url.getRemoteApplication();
// provider application is empty or equals with the current application
if (isEmpty(providerApplication)) {
logger.warn(
CLUSTER_TAG_ROUTE_EMPTY,
"condition router get providerApplication is empty, will not subscribe to provider app rules.",
"",
"");
return;
}
if (providerApplication.equals(currentApplication)) {
return;
}
synchronized (this) {
if (!providerApplication.equals(application)) {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
String key = providerApplication + RULE_SUFFIX;
this.getRuleRepository().addListener(key, this);
application = providerApplication;
String rawRule = this.getRuleRepository().getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rawRule)) {
this.process(new ConfigChangedEvent(key, DynamicConfiguration.DEFAULT_GROUP, rawRule));
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* Service level router factory
* ServiceRouter should before AppRouter
*/
@Activate(order = 140)
public class ServiceStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "service";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new ServiceStateRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/MultiDestConditionRouterRule.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/MultiDestConditionRouterRule.java | /*
* 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.dubbo.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.rpc.cluster.Constants.CONDITIONS_KEY;
public class MultiDestConditionRouterRule extends AbstractRouterRule {
private List<MultiDestCondition> conditions;
public static AbstractRouterRule parseFromMap(Map<String, Object> map) {
MultiDestConditionRouterRule multiDestConditionRouterRule = new MultiDestConditionRouterRule();
multiDestConditionRouterRule.parseFromMap0(map);
List<Map<String, String>> conditions = (List<Map<String, String>>) map.get(CONDITIONS_KEY);
List<MultiDestCondition> multiDestConditions = new ArrayList<>();
for (Map<String, String> condition : conditions) {
multiDestConditions.add((MultiDestCondition) JsonUtils.convertObject(condition, MultiDestCondition.class));
}
multiDestConditionRouterRule.setConditions(multiDestConditions);
return multiDestConditionRouterRule;
}
public List<MultiDestCondition> getConditions() {
return conditions;
}
public void setConditions(List<MultiDestCondition> conditions) {
this.conditions = conditions;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/MultiDestCondition.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/MultiDestCondition.java | /*
* 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.dubbo.rpc.cluster.router.condition.config.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MultiDestCondition {
private Map<String, String> from = new HashMap<>();
private List<Map<String, String>> to = new ArrayList<>();
public Map<String, String> getFrom() {
return from;
}
public void setFrom(Map<String, String> from) {
this.from = from;
}
public List<Map<String, String>> getTo() {
return to;
}
public void setTo(List<Map<String, String>> to) {
this.to = to;
}
@Override
public String toString() {
return "MultiDestCondition{" + "from=" + from + ", to=" + to + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionSubSet.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionSubSet.java | /*
* 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.dubbo.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.rpc.cluster.Constants.DefaultRouteConditionSubSetWeight;
public class ConditionSubSet {
private Map<String, ConditionMatcher> condition = new HashMap<>();
private Integer subSetWeight;
public ConditionSubSet() {}
public ConditionSubSet(Map<String, ConditionMatcher> condition, Integer subSetWeight) {
this.condition = condition;
this.subSetWeight = subSetWeight;
if (subSetWeight <= 0) {
this.subSetWeight = DefaultRouteConditionSubSetWeight;
}
}
public Map<String, ConditionMatcher> getCondition() {
return condition;
}
public void setCondition(Map<String, ConditionMatcher> condition) {
this.condition = condition;
}
public Integer getSubSetWeight() {
return subSetWeight;
}
public void setSubSetWeight(int subSetWeight) {
this.subSetWeight = subSetWeight;
}
@Override
public String toString() {
return "ConditionSubSet{" + "cond=" + condition + ", subSetWeight=" + subSetWeight + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java | /*
* 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.dubbo.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.rpc.cluster.Constants.CONDITIONS_KEY;
public class ConditionRouterRule extends AbstractRouterRule {
private List<String> conditions;
@SuppressWarnings("unchecked")
public static AbstractRouterRule parseFromMap(Map<String, Object> map) {
ConditionRouterRule conditionRouterRule = new ConditionRouterRule();
conditionRouterRule.parseFromMap0(map);
Object conditions = map.get(CONDITIONS_KEY);
if (conditions != null && List.class.isAssignableFrom(conditions.getClass())) {
conditionRouterRule.setConditions(
((List<Object>) conditions).stream().map(String::valueOf).collect(Collectors.toList()));
}
return conditionRouterRule;
}
public ConditionRouterRule() {}
public List<String> getConditions() {
return conditions;
}
public void setConditions(List<String> conditions) {
this.conditions = conditions;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/DestinationSet.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/DestinationSet.java | /*
* 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.dubbo.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class DestinationSet<T> {
private final List<Destination<T>> destinations;
private long weightSum;
private final ThreadLocalRandom random;
public DestinationSet() {
this.destinations = new ArrayList<>();
this.weightSum = 0;
this.random = ThreadLocalRandom.current();
}
public void addDestination(int weight, BitList<Invoker<T>> invokers) {
destinations.add(new Destination(weight, invokers));
weightSum += weight;
}
public BitList<Invoker<T>> randDestination() {
if (destinations.size() == 1) {
return destinations.get(0).getInvokers();
}
long sum = random.nextLong(weightSum);
for (Destination destination : destinations) {
sum -= destination.getWeight();
if (sum <= 0) {
return destination.getInvokers();
}
}
return BitList.emptyList();
}
public List<Destination<T>> getDestinations() {
return destinations;
}
public long getWeightSum() {
return weightSum;
}
public void setWeightSum(long weightSum) {
this.weightSum = weightSum;
}
public Random getRandom() {
return random;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java | /*
* 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.dubbo.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import java.util.Map;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RULE_PARSING;
import static org.apache.dubbo.rpc.cluster.Constants.CONFIG_VERSION_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_VERSION_V31;
/**
* %YAML1.2
*
* scope: application
* runtime: true
* force: false
* conditions:
* - >
* method!=sayHello =>
* - >
* ip=127.0.0.1
* =>
* 1.1.1.1
*/
public class ConditionRuleParser {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConditionRuleParser.class);
public static AbstractRouterRule parse(String rawRule) {
AbstractRouterRule rule;
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawRule);
String confVersion = (String) map.get(CONFIG_VERSION_KEY);
if (confVersion != null && confVersion.toLowerCase().startsWith(RULE_VERSION_V31)) {
rule = MultiDestConditionRouterRule.parseFromMap(map);
if (CollectionUtils.isEmpty(((MultiDestConditionRouterRule) rule).getConditions())) {
rule.setValid(false);
}
} else if (confVersion != null && confVersion.compareToIgnoreCase(RULE_VERSION_V31) > 0) {
logger.warn(
CLUSTER_FAILED_RULE_PARSING,
"Invalid condition config version number.",
"",
"Ignore this configuration. Only " + RULE_VERSION_V31 + " and below are supported in this release");
rule = null;
} else {
// for under v3.1
rule = ConditionRouterRule.parseFromMap(map);
if (CollectionUtils.isEmpty(((ConditionRouterRule) rule).getConditions())) {
rule.setValid(false);
}
}
if (rule != null) {
rule.setRawRule(rawRule);
}
return rule;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/Destination.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/Destination.java | /*
* 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.dubbo.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
public class Destination<T> {
private int weight;
private BitList<Invoker<T>> invokers;
Destination(int weight, BitList<Invoker<T>> invokers) {
this.weight = weight;
this.invokers = invokers;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public BitList<Invoker<T>> getInvokers() {
return invokers;
}
public void setInvokers(BitList<Invoker<T>> invokers) {
this.invokers = invokers;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java | /*
* 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.dubbo.rpc.cluster.router.tag;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_EMPTY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_INVALID;
import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG;
/**
* TagRouter, "application.tag-router"
*/
public class TagStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
public static final String NAME = "TAG_ROUTER";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TagStateRouter.class);
private static final String RULE_SUFFIX = ".tag-router";
public static final char TAG_SEPERATOR = '|';
private volatile TagRouterRule tagRouterRule;
private String application;
private volatile BitList<Invoker<T>> invokers = BitList.emptyList();
public TagStateRouter(URL url) {
super(url);
}
@Override
public synchronized void process(ConfigChangedEvent event) {
if (logger.isInfoEnabled()) {
logger.info("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n "
+ event.getContent());
}
try {
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
this.tagRouterRule = null;
} else {
TagRouterRule rule = TagRuleParser.parse(event.getContent());
rule.init(this);
this.tagRouterRule = rule;
}
} catch (Exception e) {
logger.error(
CLUSTER_TAG_ROUTE_INVALID,
"Failed to parse the raw tag router rule",
"",
"Failed to parse the raw tag router rule and it will not take effect, please check if the "
+ "rule matches with the template, the raw rule is:\n ",
e);
}
}
@Override
public BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
if (needToPrintMessage) {
messageHolder.set("Directly Return. Reason: Invokers from previous router is empty.");
}
return invokers;
}
// since the rule can be changed by config center, we should copy one to use.
final TagRouterRule tagRouterRuleCopy = tagRouterRule;
if (tagRouterRuleCopy == null || !tagRouterRuleCopy.isValid() || !tagRouterRuleCopy.isEnabled()) {
if (needToPrintMessage) {
messageHolder.set("Disable Tag Router. Reason: tagRouterRule is invalid or disabled");
}
return filterUsingStaticTag(invokers, url, invocation);
}
BitList<Invoker<T>> result = invokers;
String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY))
? url.getParameter(TAG_KEY)
: invocation.getAttachment(TAG_KEY);
// if we are requesting for a Provider with a specific tag
if (StringUtils.isNotEmpty(tag)) {
Map<String, Set<String>> tagnameToAddresses = tagRouterRuleCopy.getTagnameToAddresses();
Set<String> addresses = selectAddressByTagLevel(tagnameToAddresses, tag, isForceUseTag(invocation));
// filter by dynamic tag group first
if (addresses != null) { // null means tag not set
result = filterInvoker(invokers, invoker -> addressMatches(invoker.getUrl(), addresses));
// if result is not null OR it's null but force=true, return result directly
if (CollectionUtils.isNotEmpty(result) || tagRouterRuleCopy.isForce()) {
if (needToPrintMessage) {
messageHolder.set(
"Use tag " + tag + " to route. Reason: result is not null OR it's null but force=true");
}
return result;
}
} else {
// dynamic tag group doesn't have any item about the requested app OR it's null after filtered by
// dynamic tag group but force=false. check static tag
result = filterInvoker(
invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY)));
}
// If there's no tagged providers that can match the current tagged request. force.tag is set by default
// to false, which means it will invoke any providers without a tag unless it's explicitly disallowed.
if (CollectionUtils.isNotEmpty(result) || isForceUseTag(invocation)) {
if (needToPrintMessage) {
messageHolder.set("Use tag " + tag
+ " to route. Reason: result is not empty or ForceUseTag key is true in invocation");
}
return result;
}
// FAILOVER: return all Providers without any tags.
else {
BitList<Invoker<T>> tmp = filterInvoker(
invokers, invoker -> addressNotMatches(invoker.getUrl(), tagRouterRuleCopy.getAddresses()));
if (needToPrintMessage) {
messageHolder.set("FAILOVER: return all Providers without any tags");
}
return filterInvoker(
tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
} else {
// List<String> addresses = tagRouterRule.filter(providerApp);
// return all addresses in dynamic tag group.
Set<String> addresses = tagRouterRuleCopy.getAddresses();
if (CollectionUtils.isNotEmpty(addresses)) {
result = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), addresses));
// 1. all addresses are in dynamic tag group, return empty list.
if (CollectionUtils.isEmpty(result)) {
if (needToPrintMessage) {
messageHolder.set("all addresses are in dynamic tag group, return empty list");
}
return result;
}
// 2. if there are some addresses that are not in any dynamic tag group, continue to filter using the
// static tag group.
}
if (needToPrintMessage) {
messageHolder.set("filter using the static tag group");
}
return filterInvoker(result, invoker -> {
String localTag = invoker.getUrl().getParameter(TAG_KEY);
return StringUtils.isEmpty(localTag);
});
}
}
/**
* If there's no dynamic tag rule being set, use static tag in URL.
* <p>
* A typical scenario is a Consumer using version 2.7.x calls Providers using version 2.6.x or lower,
* the Consumer should always respect the tag in provider URL regardless of whether a dynamic tag rule has been set to it or not.
* <p>
* TODO, to guarantee consistent behavior of interoperability between 2.6- and 2.7+, this method should has the same logic with the TagRouter in 2.6.x.
*
* @param invokers
* @param url
* @param invocation
* @param <T>
* @return
*/
private <T> BitList<Invoker<T>> filterUsingStaticTag(BitList<Invoker<T>> invokers, URL url, Invocation invocation) {
BitList<Invoker<T>> result;
// Dynamic param
String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY))
? url.getParameter(TAG_KEY)
: invocation.getAttachment(TAG_KEY);
// Tag request
if (!StringUtils.isEmpty(tag)) {
result = filterInvoker(
invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY)));
if (CollectionUtils.isEmpty(result) && !isForceUseTag(invocation)) {
result = filterInvoker(
invokers,
invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
} else {
result = filterInvoker(
invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
return result;
}
@Override
public boolean isRuntime() {
return tagRouterRule != null && tagRouterRule.isRuntime();
}
@Override
public boolean isForce() {
// FIXME
return tagRouterRule != null && tagRouterRule.isForce();
}
private boolean isForceUseTag(Invocation invocation) {
return Boolean.parseBoolean(
invocation.getAttachment(FORCE_USE_TAG, this.getUrl().getParameter(FORCE_USE_TAG, "false")));
}
private <T> BitList<Invoker<T>> filterInvoker(BitList<Invoker<T>> invokers, Predicate<Invoker<T>> predicate) {
if (invokers.stream().allMatch(predicate)) {
return invokers;
}
BitList<Invoker<T>> newInvokers = invokers.clone();
newInvokers.removeIf(invoker -> !predicate.test(invoker));
return newInvokers;
}
private boolean addressMatches(URL url, Set<String> addresses) {
return addresses != null && checkAddressMatch(addresses, url.getHost(), url.getPort());
}
private boolean addressNotMatches(URL url, Set<String> addresses) {
return addresses == null || !checkAddressMatch(addresses, url.getHost(), url.getPort());
}
private boolean checkAddressMatch(Set<String> addresses, String host, int port) {
for (String address : addresses) {
try {
if (NetUtils.matchIpExpression(address, host, port)) {
return true;
}
if ((ANYHOST_VALUE + ":" + port).equals(address)) {
return true;
}
} catch (Exception e) {
logger.error(
CLUSTER_TAG_ROUTE_INVALID,
"tag route address is invalid",
"",
"The format of ip address is invalid in tag route. Address :" + address,
e);
}
}
return false;
}
public void setApplication(String app) {
this.application = app;
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
this.invokers = invokers;
if (CollectionUtils.isEmpty(invokers)) {
return;
}
Invoker<T> invoker = invokers.get(0);
URL url = invoker.getUrl();
String providerApplication = url.getRemoteApplication();
if (StringUtils.isEmpty(providerApplication)) {
logger.error(
CLUSTER_TAG_ROUTE_EMPTY,
"tag router get providerApplication is empty",
"",
"TagRouter must getConfig from or subscribe to a specific application, but the application "
+ "in this TagRouter is not specified.");
return;
}
synchronized (this) {
if (!providerApplication.equals(application)) {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
String key = providerApplication + RULE_SUFFIX;
this.getRuleRepository().addListener(key, this);
application = providerApplication;
String rawRule = this.getRuleRepository().getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rawRule)) {
this.process(new ConfigChangedEvent(key, DynamicConfiguration.DEFAULT_GROUP, rawRule));
}
} else {
if (this.tagRouterRule != null) {
TagRouterRule newRule = TagRuleParser.parse(this.tagRouterRule.getRawRule());
newRule.init(this);
this.tagRouterRule = newRule;
}
}
}
}
public BitList<Invoker<T>> getInvokers() {
return invokers;
}
@Override
public void stop() {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
}
// for testing purpose
public void setTagRouterRule(TagRouterRule tagRouterRule) {
this.tagRouterRule = tagRouterRule;
}
/**
* select addresses by tag with level
* <p>
* example:
* selector=beta|team1|partner1
* step1.select tagAddresses with selector=beta|team1|partner1, if result is empty, then run step2
* step2.select tagAddresses with selector=beta|team1, if result is empty, then run step3
* step3.select tagAddresses with selector=beta, if result is empty, result is null
* </p>
*
* @param tagAddresses
* @param tagSelector eg: beta|team1|partner1
* @return
*/
public static Set<String> selectAddressByTagLevel(
Map<String, Set<String>> tagAddresses, String tagSelector, boolean isForce) {
if (isForce || StringUtils.isNotContains(tagSelector, TAG_SEPERATOR)) {
return tagAddresses.get(tagSelector);
}
String[] selectors = StringUtils.split(tagSelector, TAG_SEPERATOR);
for (int i = selectors.length; i > 0; i--) {
String selectorTmp = StringUtils.join(selectors, TAG_SEPERATOR, 0, i);
Set<String> addresses = tagAddresses.get(selectorTmp);
if (CollectionUtils.isNotEmpty(addresses)) {
return addresses;
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.tag;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* Tag router factory
*/
@Activate(order = 100)
public class TagStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "tag";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new TagStateRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/ParamMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/ParamMatch.java | /*
* 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.dubbo.rpc.cluster.router.tag.model;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
public class ParamMatch {
private String key;
private StringMatch value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public StringMatch getValue() {
return value;
}
public void setValue(StringMatch value) {
this.value = value;
}
public boolean isMatch(String input) {
if (getValue() != null) {
return getValue().isMatch(input);
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java | /*
* 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.dubbo.rpc.cluster.router.tag.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.tag.TagStateRouter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_VERSION_V30;
import static org.apache.dubbo.rpc.cluster.Constants.TAGS_KEY;
/**
* %YAML1.2
* ---
* force: true
* runtime: false
* enabled: true
* priority: 1
* key: demo-provider
* tags:
* - name: tag1
* addresses: [ip1, ip2]
* - name: tag2
* addresses: [ip3, ip4]
* ...
*/
public class TagRouterRule extends AbstractRouterRule {
private List<Tag> tags;
private final Map<String, Set<String>> addressToTagnames = new HashMap<>();
private final Map<String, Set<String>> tagnameToAddresses = new HashMap<>();
@SuppressWarnings("unchecked")
public static TagRouterRule parseFromMap(Map<String, Object> map) {
TagRouterRule tagRouterRule = new TagRouterRule();
tagRouterRule.parseFromMap0(map);
Object tags = map.get(TAGS_KEY);
if (tags != null && List.class.isAssignableFrom(tags.getClass())) {
tagRouterRule.setTags(((List<Map<String, Object>>) tags)
.stream()
.map(objMap -> Tag.parseFromMap(objMap, tagRouterRule.getVersion()))
.collect(Collectors.toList()));
}
return tagRouterRule;
}
public void init(TagStateRouter<?> router) {
if (!isValid()) {
return;
}
BitList<? extends Invoker<?>> invokers = router.getInvokers();
// for tags with 'addresses` field set and 'match' field not set
tags.stream()
.filter(tag -> CollectionUtils.isNotEmpty(tag.getAddresses()))
.forEach(tag -> {
tagnameToAddresses.put(tag.getName(), new HashSet<>(tag.getAddresses()));
tag.getAddresses().forEach(addr -> {
Set<String> tagNames = addressToTagnames.computeIfAbsent(addr, k -> new HashSet<>());
tagNames.add(tag.getName());
});
});
if (this.getVersion() != null && this.getVersion().startsWith(RULE_VERSION_V30)) {
// for tags with 'match` field set and 'addresses' field not set
if (CollectionUtils.isNotEmpty(invokers)) {
tags.stream()
.filter(tag -> CollectionUtils.isEmpty(tag.getAddresses()))
.forEach(tag -> {
Set<String> addresses = new HashSet<>();
List<ParamMatch> paramMatchers = tag.getMatch();
invokers.forEach(invoker -> {
boolean isMatch = true;
for (ParamMatch matcher : paramMatchers) {
if (!matcher.isMatch(invoker.getUrl().getOriginalParameter(matcher.getKey()))) {
isMatch = false;
break;
}
}
if (isMatch) {
addresses.add(invoker.getUrl().getAddress());
}
});
if (CollectionUtils.isNotEmpty(addresses)) { // null means tag not set
tagnameToAddresses.put(tag.getName(), addresses);
}
});
}
}
}
public Set<String> getAddresses() {
return tagnameToAddresses.entrySet().stream()
.filter(entry -> CollectionUtils.isNotEmpty(entry.getValue()))
.flatMap(entry -> entry.getValue().stream())
.collect(Collectors.toSet());
}
public List<String> getTagNames() {
return tags.stream().map(Tag::getName).collect(Collectors.toList());
}
public Map<String, Set<String>> getAddressToTagnames() {
return addressToTagnames;
}
public Map<String, Set<String>> getTagnameToAddresses() {
return tagnameToAddresses;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java | /*
* 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.dubbo.rpc.cluster.router.tag.model;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.PojoUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RULE_PARSING;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_VERSION_V30;
public class Tag {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Tag.class);
private String name;
private List<ParamMatch> match;
private List<String> addresses;
@SuppressWarnings("unchecked")
public static Tag parseFromMap(Map<String, Object> map, String version) {
Tag tag = new Tag();
tag.setName((String) map.get("name"));
if (version != null && version.startsWith(RULE_VERSION_V30)) {
if (map.get("match") != null) {
tag.setMatch(((List<Map<String, Object>>) map.get("match"))
.stream()
.map((objectMap) -> {
try {
return PojoUtils.mapToPojo(objectMap, ParamMatch.class);
} catch (ReflectiveOperationException e) {
logger.error(
CLUSTER_FAILED_RULE_PARSING,
" Failed to parse tag rule ",
String.valueOf(objectMap),
"Error occurred when parsing rule component.",
e);
}
return null;
})
.collect(Collectors.toList()));
} else {
logger.warn(
CLUSTER_FAILED_RULE_PARSING,
"",
String.valueOf(map),
"It's recommended to use 'match' instead of 'addresses' for v3.0 tag rule.");
}
}
Object addresses = map.get("addresses");
if (addresses != null && List.class.isAssignableFrom(addresses.getClass())) {
tag.setAddresses(
((List<Object>) addresses).stream().map(String::valueOf).collect(Collectors.toList()));
}
return tag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public List<ParamMatch> getMatch() {
return match;
}
public void setMatch(List<ParamMatch> match) {
this.match = match;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java | /*
* 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.dubbo.rpc.cluster.router.tag.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.Map;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/**
* Parse raw rule into structured tag rule
*/
public class TagRuleParser {
public static TagRouterRule parse(String rawRule) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawRule);
TagRouterRule rule = TagRouterRule.parseFromMap(map);
rule.setRawRule(rawRule);
if (CollectionUtils.isEmpty(rule.getTags())) {
rule.setValid(false);
}
return rule;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/MeshScopeModelInitializer.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/MeshScopeModelInitializer.java | /*
* 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.dubbo.rpc.cluster.router.mesh;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleManager;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class MeshScopeModelInitializer implements ScopeModelInitializer {
public void initializeModuleModel(ModuleModel moduleModel) {
ScopeBeanFactory beanFactory = moduleModel.getBeanFactory();
beanFactory.registerBean(MeshRuleManager.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/TracingContextProvider.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/TracingContextProvider.java | /*
* 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.dubbo.rpc.cluster.router.mesh.util;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
/**
* SPI to get tracing context from 3rd-party tracing utils ( e.g. OpenTracing )
*/
@SPI(scope = ExtensionScope.APPLICATION)
public interface TracingContextProvider {
/**
* Get value from context
*
* @param invocation invocation
* @param key key of value
* @return value (null if absent)
*/
String getValue(Invocation invocation, String key);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java | /*
* 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.dubbo.rpc.cluster.router.mesh.util;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_RULE_LISTENER;
public class MeshRuleDispatcher {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshRuleDispatcher.class);
private final String appName;
private final ConcurrentMap<String, Set<MeshRuleListener>> listenerMap = new ConcurrentHashMap<>();
public MeshRuleDispatcher(String appName) {
this.appName = appName;
}
public synchronized void post(Map<String, List<Map<String, Object>>> ruleMap) {
if (ruleMap.isEmpty()) {
// clear rule
for (Map.Entry<String, Set<MeshRuleListener>> entry : listenerMap.entrySet()) {
for (MeshRuleListener listener : entry.getValue()) {
listener.clearRule(appName);
}
}
} else {
for (Map.Entry<String, List<Map<String, Object>>> entry : ruleMap.entrySet()) {
String ruleType = entry.getKey();
Set<MeshRuleListener> listeners = listenerMap.get(ruleType);
if (CollectionUtils.isNotEmpty(listeners)) {
for (MeshRuleListener listener : listeners) {
listener.onRuleChange(appName, entry.getValue());
}
} else {
logger.warn(
CLUSTER_NO_RULE_LISTENER,
"Receive mesh rule but none of listener has been registered",
"",
"Receive rule but none of listener has been registered. Maybe type not matched. Rule Type: "
+ ruleType);
}
}
// clear rule listener not being notified in this time
for (Map.Entry<String, Set<MeshRuleListener>> entry : listenerMap.entrySet()) {
if (!ruleMap.containsKey(entry.getKey())) {
for (MeshRuleListener listener : entry.getValue()) {
listener.clearRule(appName);
}
}
}
}
}
public synchronized void register(MeshRuleListener listener) {
if (listener == null) {
return;
}
ConcurrentHashMapUtils.computeIfAbsent(listenerMap, listener.ruleSuffix(), (k) -> new ConcurrentHashSet<>())
.add(listener);
}
public synchronized void unregister(MeshRuleListener listener) {
if (listener == null) {
return;
}
Set<MeshRuleListener> listeners = listenerMap.get(listener.ruleSuffix());
if (CollectionUtils.isNotEmpty(listeners)) {
listeners.remove(listener);
}
if (CollectionUtils.isEmpty(listeners)) {
listenerMap.remove(listener.ruleSuffix());
}
}
public boolean isEmpty() {
return listenerMap.isEmpty();
}
/**
* For ut only
*/
@Deprecated
public Map<String, Set<MeshRuleListener>> getListenerMap() {
return listenerMap;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java | /*
* 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.dubbo.rpc.cluster.router.mesh.util;
import java.util.List;
import java.util.Map;
public interface MeshRuleListener {
void onRuleChange(String appName, List<Map<String, Object>> rules);
void clearRule(String appName);
String ruleSuffix();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule;
import java.util.Map;
public class BaseRule {
private String apiVersion;
private String kind;
private Map<String, String> metadata;
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public Map<String, String> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
@Override
public String toString() {
return "BaseRule{" + "apiVersion='"
+ apiVersion + '\'' + ", kind='"
+ kind + '\'' + ", metadata="
+ metadata + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule;
import java.util.LinkedList;
import java.util.List;
public class VsDestinationGroup {
private String appName;
private List<VirtualServiceRule> virtualServiceRuleList = new LinkedList<>();
private List<DestinationRule> destinationRuleList = new LinkedList<>();
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public List<VirtualServiceRule> getVirtualServiceRuleList() {
return virtualServiceRuleList;
}
public void setVirtualServiceRuleList(List<VirtualServiceRule> virtualServiceRuleList) {
this.virtualServiceRuleList = virtualServiceRuleList;
}
public List<DestinationRule> getDestinationRuleList() {
return destinationRuleList;
}
public void setDestinationRuleList(List<DestinationRule> destinationRuleList) {
this.destinationRuleList = destinationRuleList;
}
public boolean isValid() {
return virtualServiceRuleList.size() > 0 && destinationRuleList.size() > 0;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import java.util.List;
public class DubboRoute {
private String name;
private List<StringMatch> services;
private List<DubboRouteDetail> routedetail;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<StringMatch> getServices() {
return services;
}
public void setServices(List<StringMatch> services) {
this.services = services;
}
public List<DubboRouteDetail> getRoutedetail() {
return routedetail;
}
public void setRoutedetail(List<DubboRouteDetail> routedetail) {
this.routedetail = routedetail;
}
@Override
public String toString() {
return "DubboRoute{" + "name='" + name + '\'' + ", services=" + services + ", routedetail=" + routedetail + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice;
import java.util.List;
public class VirtualServiceSpec {
private List<String> hosts;
private List<DubboRoute> dubbo;
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public List<DubboRoute> getDubbo() {
return dubbo;
}
public void setDubbo(List<DubboRoute> dubbo) {
this.dubbo = dubbo;
}
@Override
public String toString() {
return "VirtualServiceSpec{" + "hosts=" + hosts + ", dubbo=" + dubbo + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination.DubboRouteDestination;
import java.util.List;
public class DubboRouteDetail {
private String name;
private List<DubboMatchRequest> match;
private List<DubboRouteDestination> route;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DubboMatchRequest> getMatch() {
return match;
}
public void setMatch(List<DubboMatchRequest> match) {
this.match = match;
}
public List<DubboRouteDestination> getRoute() {
return route;
}
public void setRoute(List<DubboRouteDestination> route) {
this.route = route;
}
@Override
public String toString() {
return "DubboRouteDetail{" + "name='" + name + '\'' + ", match=" + match + ", route=" + route + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.BaseRule;
public class VirtualServiceRule extends BaseRule {
private VirtualServiceSpec spec;
public VirtualServiceSpec getSpec() {
return spec;
}
public void setSpec(VirtualServiceSpec spec) {
this.spec = spec;
}
@Override
public String toString() {
return "VirtualServiceRule{" + "base=" + super.toString() + ", spec=" + spec + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboAttachmentMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboMethodMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Map;
import java.util.Set;
public class DubboMatchRequest {
private String name;
private DubboMethodMatch method;
private Map<String, String> sourceLabels;
private DubboAttachmentMatch attachments;
private Map<String, StringMatch> headers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DubboMethodMatch getMethod() {
return method;
}
public void setMethod(DubboMethodMatch method) {
this.method = method;
}
public Map<String, String> getSourceLabels() {
return sourceLabels;
}
public void setSourceLabels(Map<String, String> sourceLabels) {
this.sourceLabels = sourceLabels;
}
public DubboAttachmentMatch getAttachments() {
return attachments;
}
public void setAttachments(DubboAttachmentMatch attachments) {
this.attachments = attachments;
}
public Map<String, StringMatch> getHeaders() {
return headers;
}
public void setHeaders(Map<String, StringMatch> headers) {
this.headers = headers;
}
@Override
public String toString() {
return "DubboMatchRequest{" + "name='"
+ name + '\'' + ", method="
+ method + ", sourceLabels="
+ sourceLabels + ", attachments="
+ attachments + ", headers="
+ headers + '}';
}
public boolean isMatch(
Invocation invocation, Map<String, String> sourceLabels, Set<TracingContextProvider> contextProviders) {
// Match method
if (getMethod() != null) {
if (!getMethod().isMatch(invocation)) {
return false;
}
}
// Match Source Labels
if (getSourceLabels() != null) {
for (Map.Entry<String, String> entry : getSourceLabels().entrySet()) {
String value = sourceLabels.get(entry.getKey());
if (!entry.getValue().equals(value)) {
return false;
}
}
}
// Match attachment
if (getAttachments() != null) {
return getAttachments().isMatch(invocation, contextProviders);
}
// TODO Match headers
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
public class StringMatch {
private String exact;
private String prefix;
private String regex;
private String noempty;
private String empty;
private String wildcard;
public String getExact() {
return exact;
}
public void setExact(String exact) {
this.exact = exact;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getRegex() {
return regex;
}
public void setRegex(String regex) {
this.regex = regex;
}
public String getNoempty() {
return noempty;
}
public void setNoempty(String noempty) {
this.noempty = noempty;
}
public String getEmpty() {
return empty;
}
public void setEmpty(String empty) {
this.empty = empty;
}
public String getWildcard() {
return wildcard;
}
public void setWildcard(String wildcard) {
this.wildcard = wildcard;
}
public boolean isMatch(String input) {
if (getExact() != null && input != null) {
return input.equals(getExact());
} else if (getPrefix() != null && input != null) {
return input.startsWith(getPrefix());
} else if (getRegex() != null && input != null) {
return input.matches(getRegex());
} else if (getWildcard() != null && input != null) {
// only supports "*"
return input.equals(getWildcard()) || ANY_VALUE.equals(getWildcard());
} else if (getEmpty() != null) {
return input == null || "".equals(input);
} else if (getNoempty() != null) {
return input != null && input.length() > 0;
} else {
return false;
}
}
@Override
public String toString() {
return "StringMatch{" + "exact='"
+ exact + '\'' + ", prefix='"
+ prefix + '\'' + ", regex='"
+ regex + '\'' + ", noempty='"
+ noempty + '\'' + ", empty='"
+ empty + '\'' + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.List;
public class ListBoolMatch {
private List<BoolMatch> oneof;
public List<BoolMatch> getOneof() {
return oneof;
}
public void setOneof(List<BoolMatch> oneof) {
this.oneof = oneof;
}
public boolean isMatch(boolean input) {
for (BoolMatch boolMatch : oneof) {
if (boolMatch.isMatch(input)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/AddressMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/AddressMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.net.UnknownHostException;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
import static org.apache.dubbo.common.utils.NetUtils.matchIpExpression;
import static org.apache.dubbo.common.utils.UrlUtils.isMatchGlobPattern;
public class AddressMatch {
public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AddressMatch.class);
private String wildcard;
private String cird;
private String exact;
public String getWildcard() {
return wildcard;
}
public void setWildcard(String wildcard) {
this.wildcard = wildcard;
}
public String getCird() {
return cird;
}
public void setCird(String cird) {
this.cird = cird;
}
public String getExact() {
return exact;
}
public void setExact(String exact) {
this.exact = exact;
}
public boolean isMatch(String input) {
if (getCird() != null && input != null) {
try {
return input.equals(getCird()) || matchIpExpression(getCird(), input);
} catch (UnknownHostException e) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Executing routing rule match expression error.",
"",
String.format(
"Error trying to match cird formatted address %s with input %s in AddressMatch.",
getCird(), input),
e);
}
}
if (getWildcard() != null && input != null) {
if (ANYHOST_VALUE.equals(getWildcard()) || ANY_VALUE.equals(getWildcard())) {
return true;
}
// FIXME
return isMatchGlobPattern(getWildcard(), input);
}
if (getExact() != null && input != null) {
return input.equals(getExact());
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
public class DoubleMatch {
private Double exact;
private DoubleRangeMatch range;
private Double mod;
public Double getExact() {
return exact;
}
public void setExact(Double exact) {
this.exact = exact;
}
public DoubleRangeMatch getRange() {
return range;
}
public void setRange(DoubleRangeMatch range) {
this.range = range;
}
public Double getMod() {
return mod;
}
public void setMod(Double mod) {
this.mod = mod;
}
public boolean isMatch(Double input) {
if (exact != null && mod == null) {
return input.equals(exact);
} else if (range != null) {
return range.isMatch(input);
} else if (exact != null) {
Double result = input % mod;
return result.equals(exact);
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
public class BoolMatch {
private Boolean exact;
public Boolean getExact() {
return exact;
}
public void setExact(Boolean exact) {
this.exact = exact;
}
public boolean isMatch(boolean input) {
if (exact != null) {
return input == exact;
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.List;
public class ListStringMatch {
private List<StringMatch> oneof;
public List<StringMatch> getOneof() {
return oneof;
}
public void setOneof(List<StringMatch> oneof) {
this.oneof = oneof;
}
public boolean isMatch(String input) {
for (StringMatch stringMatch : oneof) {
if (stringMatch.isMatch(input)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodArg.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodArg.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
public class DubboMethodArg {
private int index;
private String type;
private ListStringMatch str_value;
private ListDoubleMatch num_value;
private BoolMatch bool_value;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ListStringMatch getStr_value() {
return str_value;
}
public void setStr_value(ListStringMatch str_value) {
this.str_value = str_value;
}
public ListDoubleMatch getNum_value() {
return num_value;
}
public void setNum_value(ListDoubleMatch num_value) {
this.num_value = num_value;
}
public BoolMatch getBool_value() {
return bool_value;
}
public void setBool_value(BoolMatch bool_value) {
this.bool_value = bool_value;
}
public boolean isMatch(Object input) {
if (str_value != null) {
return input instanceof String && str_value.isMatch((String) input);
} else if (num_value != null) {
return num_value.isMatch(Double.valueOf(input.toString()));
} else if (bool_value != null) {
return input instanceof Boolean && bool_value.isMatch((Boolean) input);
}
return false;
}
@Override
public String toString() {
return "DubboMethodArg{" + "index="
+ index + ", type='"
+ type + '\'' + ", str_value="
+ str_value + ", num_value="
+ num_value + ", bool_value="
+ bool_value + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.List;
public class ListDoubleMatch {
private List<DoubleMatch> oneof;
public List<DoubleMatch> getOneof() {
return oneof;
}
public void setOneof(List<DoubleMatch> oneof) {
this.oneof = oneof;
}
public boolean isMatch(Double input) {
for (DoubleMatch doubleMatch : oneof) {
if (doubleMatch.isMatch(input)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import java.util.Map;
public class DubboMethodMatch {
private StringMatch name_match;
private Integer argc;
private List<DubboMethodArg> args;
private List<StringMatch> argp;
private Map<String, StringMatch> headers;
public StringMatch getName_match() {
return name_match;
}
public void setName_match(StringMatch name_match) {
this.name_match = name_match;
}
public Integer getArgc() {
return argc;
}
public void setArgc(Integer argc) {
this.argc = argc;
}
public List<DubboMethodArg> getArgs() {
return args;
}
public void setArgs(List<DubboMethodArg> args) {
this.args = args;
}
public List<StringMatch> getArgp() {
return argp;
}
public void setArgp(List<StringMatch> argp) {
this.argp = argp;
}
public Map<String, StringMatch> getHeaders() {
return headers;
}
public void setHeaders(Map<String, StringMatch> headers) {
this.headers = headers;
}
@Override
public String toString() {
return "DubboMethodMatch{" + "name_match="
+ name_match + ", argc="
+ argc + ", args="
+ args + ", argp="
+ argp + ", headers="
+ headers + '}';
}
public boolean isMatch(Invocation invocation) {
StringMatch nameMatch = getName_match();
if (nameMatch != null && !nameMatch.isMatch(RpcUtils.getMethodName(invocation))) {
return false;
}
Integer argc = getArgc();
Object[] arguments = invocation.getArguments();
if (argc != null
&& ((argc != 0 && (arguments == null || arguments.length == 0)) || (argc != arguments.length))) {
return false;
}
List<StringMatch> argp = getArgp();
Class<?>[] parameterTypes = invocation.getParameterTypes();
if (argp != null && argp.size() > 0) {
if (parameterTypes == null || parameterTypes.length == 0) {
return false;
}
if (argp.size() != parameterTypes.length) {
return false;
}
for (int index = 0; index < argp.size(); index++) {
boolean match = argp.get(index).isMatch(parameterTypes[index].getName())
|| argp.get(index).isMatch(parameterTypes[index].getSimpleName());
if (!match) {
return false;
}
}
}
List<DubboMethodArg> args = getArgs();
if (args != null && args.size() > 0) {
if (arguments == null || arguments.length == 0) {
return false;
}
for (DubboMethodArg dubboMethodArg : args) {
int index = dubboMethodArg.getIndex();
if (index >= arguments.length) {
throw new IndexOutOfBoundsException("DubboMethodArg index >= parameters.length");
}
if (!dubboMethodArg.isMatch(arguments[index])) {
return false;
}
}
}
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Map;
import java.util.Set;
public class DubboAttachmentMatch {
private Map<String, StringMatch> tracingContext;
private Map<String, StringMatch> dubboContext;
public Map<String, StringMatch> getTracingContext() {
return tracingContext;
}
public void setTracingContext(Map<String, StringMatch> tracingContext) {
this.tracingContext = tracingContext;
}
public Map<String, StringMatch> getDubboContext() {
return dubboContext;
}
public void setDubboContext(Map<String, StringMatch> dubboContext) {
this.dubboContext = dubboContext;
}
public boolean isMatch(Invocation invocation, Set<TracingContextProvider> contextProviders) {
// Match Dubbo Context
if (dubboContext != null) {
for (Map.Entry<String, StringMatch> entry : dubboContext.entrySet()) {
String key = entry.getKey();
if (!entry.getValue().isMatch(invocation.getAttachment(key))) {
return false;
}
}
}
// Match Tracing Context
if (tracingContext != null) {
for (Map.Entry<String, StringMatch> entry : tracingContext.entrySet()) {
String key = entry.getKey();
boolean match = false;
for (TracingContextProvider contextProvider : contextProviders) {
if (entry.getValue().isMatch(contextProvider.getValue(invocation, key))) {
match = true;
}
}
if (!match) {
return false;
}
}
}
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleRangeMatch.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleRangeMatch.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
public class DoubleRangeMatch {
private Double start;
private Double end;
public Double getStart() {
return start;
}
public void setStart(Double start) {
this.start = start;
}
public Double getEnd() {
return end;
}
public void setEnd(Double end) {
this.end = end;
}
public boolean isMatch(Double input) {
if (start != null && end != null) {
return input.compareTo(start) >= 0 && input.compareTo(end) < 0;
} else if (start != null) {
return input.compareTo(start) >= 0;
} else if (end != null) {
return input.compareTo(end) < 0;
} else {
return false;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination;
public class DubboRouteDestination {
private DubboDestination destination;
private int weight;
public DubboDestination getDestination() {
return destination;
}
public void setDestination(DubboDestination destination) {
this.destination = destination;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination;
public class DubboDestination {
private String host;
private String subset;
private int port;
private DubboRouteDestination fallback;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getSubset() {
return subset;
}
public void setSubset(String subset) {
this.subset = subset;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public DubboRouteDestination getFallback() {
return fallback;
}
public void setFallback(DubboRouteDestination fallback) {
this.fallback = fallback;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination;
public class ConnectionPoolSettings {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination;
public class TCPSettings {
private int maxConnections;
private int connectTimeout;
private TcpKeepalive tcpKeepalive;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination;
import java.util.Map;
public class Subset {
private String name;
private Map<String, String> labels;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getLabels() {
return labels;
}
public void setLabels(Map<String, String> labels) {
this.labels = labels;
}
@Override
public String toString() {
return "Subset{" + "name='" + name + '\'' + ", labels=" + labels + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance.LoadBalancerSettings;
public class TrafficPolicy {
private LoadBalancerSettings loadBalancer;
public LoadBalancerSettings getLoadBalancer() {
return loadBalancer;
}
public void setLoadBalancer(LoadBalancerSettings loadBalancer) {
this.loadBalancer = loadBalancer;
}
@Override
public String toString() {
return "TrafficPolicy{" + "loadBalancer=" + loadBalancer + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination;
import java.util.List;
public class DestinationRuleSpec {
private String host;
private List<Subset> subsets;
private TrafficPolicy trafficPolicy;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public List<Subset> getSubsets() {
return subsets;
}
public void setSubsets(List<Subset> subsets) {
this.subsets = subsets;
}
public TrafficPolicy getTrafficPolicy() {
return trafficPolicy;
}
public void setTrafficPolicy(TrafficPolicy trafficPolicy) {
this.trafficPolicy = trafficPolicy;
}
@Override
public String toString() {
return "DestinationRuleSpec{" + "host='"
+ host + '\'' + ", subsets="
+ subsets + ", trafficPolicy="
+ trafficPolicy + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination;
public class TcpKeepalive {
private int probes;
private int time;
private int interval;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.BaseRule;
public class DestinationRule extends BaseRule {
private DestinationRuleSpec spec;
public DestinationRuleSpec getSpec() {
return spec;
}
public void setSpec(DestinationRuleSpec spec) {
this.spec = spec;
}
@Override
public String toString() {
return "DestinationRule{" + "base=" + super.toString() + ", spec=" + spec + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance;
public class LoadBalancerSettings {
private SimpleLB simple;
private ConsistentHashLB consistentHash;
public SimpleLB getSimple() {
return simple;
}
public void setSimple(SimpleLB simple) {
this.simple = simple;
}
public ConsistentHashLB getConsistentHash() {
return consistentHash;
}
public void setConsistentHash(ConsistentHashLB consistentHash) {
this.consistentHash = consistentHash;
}
@Override
public String toString() {
return "LoadBalancerSettings{" + "simple=" + simple + ", consistentHash=" + consistentHash + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance;
public enum SimpleLB {
ROUND_ROBIN,
LEAST_CONN,
RANDOM,
PASSTHROUGH
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java | /*
* 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.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance;
public class ConsistentHashLB {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
@Activate(order = -50)
public class StandardMeshRuleRouterFactory implements StateRouterFactory {
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
return new StandardMeshRuleRouter<>(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.PojoUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.VsDestinationGroup;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboMatchRequest;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRoute;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRouteDetail;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceSpec;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination.DubboDestination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination.DubboRouteDestination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.DESTINATION_RULE_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.INVALID_APP_NAME;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.KIND_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.VIRTUAL_SERVICE_KEY;
public abstract class MeshRuleRouter<T> extends AbstractStateRouter<T> implements MeshRuleListener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshRuleRouter.class);
private final Map<String, String> sourcesLabels;
private volatile BitList<Invoker<T>> invokerList = BitList.emptyList();
private volatile Set<String> remoteAppName = Collections.emptySet();
protected MeshRuleManager meshRuleManager;
protected Set<TracingContextProvider> tracingContextProviders;
protected volatile MeshRuleCache<T> meshRuleCache = MeshRuleCache.emptyCache();
public MeshRuleRouter(URL url) {
super(url);
sourcesLabels = Collections.unmodifiableMap(new HashMap<>(url.getParameters()));
this.meshRuleManager = url.getOrDefaultModuleModel().getBeanFactory().getBean(MeshRuleManager.class);
this.tracingContextProviders = url.getOrDefaultModuleModel()
.getExtensionLoader(TracingContextProvider.class)
.getSupportedExtensionInstances();
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
MeshRuleCache<T> ruleCache = this.meshRuleCache;
if (!ruleCache.containsRule()) {
if (needToPrintMessage) {
messageHolder.set("MeshRuleCache has not been built. Skip route.");
}
return invokers;
}
BitList<Invoker<T>> result = new BitList<>(invokers.getOriginList(), true, invokers.getTailList());
StringBuilder stringBuilder = needToPrintMessage ? new StringBuilder() : null;
// loop each application
for (String appName : ruleCache.getAppList()) {
// find destination by invocation
List<DubboRouteDestination> routeDestination =
getDubboRouteDestination(ruleCache.getVsDestinationGroup(appName), invocation);
if (routeDestination != null) {
// aggregate target invokers
String subset = randomSelectDestination(ruleCache, appName, routeDestination, invokers);
if (subset != null) {
BitList<Invoker<T>> destination = meshRuleCache.getSubsetInvokers(appName, subset);
result = result.or(destination);
if (stringBuilder != null) {
stringBuilder
.append("Match App: ")
.append(appName)
.append(" Subset: ")
.append(subset)
.append(' ');
}
}
}
}
// result = result.or(ruleCache.getUnmatchedInvokers());
// empty protection
if (result.isEmpty()) {
if (needToPrintMessage) {
messageHolder.set("Empty protection after routed.");
}
return invokers;
}
if (needToPrintMessage) {
messageHolder.set(stringBuilder.toString());
}
return invokers.and(result);
}
/**
* Select RouteDestination by Invocation
*/
protected List<DubboRouteDestination> getDubboRouteDestination(
VsDestinationGroup vsDestinationGroup, Invocation invocation) {
if (vsDestinationGroup != null) {
List<VirtualServiceRule> virtualServiceRuleList = vsDestinationGroup.getVirtualServiceRuleList();
if (CollectionUtils.isNotEmpty(virtualServiceRuleList)) {
for (VirtualServiceRule virtualServiceRule : virtualServiceRuleList) {
// match virtual service (by serviceName)
DubboRoute dubboRoute = getDubboRoute(virtualServiceRule, invocation);
if (dubboRoute != null) {
// match route detail (by params)
return getDubboRouteDestination(dubboRoute, invocation);
}
}
}
}
return null;
}
/**
* Match virtual service (by serviceName)
*/
protected DubboRoute getDubboRoute(VirtualServiceRule virtualServiceRule, Invocation invocation) {
String serviceName = invocation.getServiceName();
VirtualServiceSpec spec = virtualServiceRule.getSpec();
List<DubboRoute> dubboRouteList = spec.getDubbo();
if (CollectionUtils.isNotEmpty(dubboRouteList)) {
for (DubboRoute dubboRoute : dubboRouteList) {
List<StringMatch> stringMatchList = dubboRoute.getServices();
if (CollectionUtils.isEmpty(stringMatchList)) {
return dubboRoute;
}
for (StringMatch stringMatch : stringMatchList) {
if (stringMatch.isMatch(serviceName)) {
return dubboRoute;
}
}
}
}
return null;
}
/**
* Match route detail (by params)
*/
protected List<DubboRouteDestination> getDubboRouteDestination(DubboRoute dubboRoute, Invocation invocation) {
List<DubboRouteDetail> dubboRouteDetailList = dubboRoute.getRoutedetail();
if (CollectionUtils.isNotEmpty(dubboRouteDetailList)) {
for (DubboRouteDetail dubboRouteDetail : dubboRouteDetailList) {
List<DubboMatchRequest> matchRequestList = dubboRouteDetail.getMatch();
if (CollectionUtils.isEmpty(matchRequestList)) {
return dubboRouteDetail.getRoute();
}
if (matchRequestList.stream()
.allMatch(request -> request.isMatch(invocation, sourcesLabels, tracingContextProviders))) {
return dubboRouteDetail.getRoute();
}
}
}
return null;
}
/**
* Find out target invokers from RouteDestination
*/
protected String randomSelectDestination(
MeshRuleCache<T> meshRuleCache,
String appName,
List<DubboRouteDestination> routeDestination,
BitList<Invoker<T>> availableInvokers)
throws RpcException {
// randomly select one DubboRouteDestination from list by weight
int totalWeight = 0;
for (DubboRouteDestination dubboRouteDestination : routeDestination) {
totalWeight += Math.max(dubboRouteDestination.getWeight(), 1);
}
int target = ThreadLocalRandom.current().nextInt(totalWeight);
for (DubboRouteDestination destination : routeDestination) {
target -= Math.max(destination.getWeight(), 1);
if (target <= 0) {
// match weight
String result =
computeDestination(meshRuleCache, appName, destination.getDestination(), availableInvokers);
if (result != null) {
return result;
}
}
}
// fall back
for (DubboRouteDestination destination : routeDestination) {
String result = computeDestination(meshRuleCache, appName, destination.getDestination(), availableInvokers);
if (result != null) {
return result;
}
}
return null;
}
/**
* Compute Destination Subset
*/
protected String computeDestination(
MeshRuleCache<T> meshRuleCache,
String appName,
DubboDestination dubboDestination,
BitList<Invoker<T>> availableInvokers)
throws RpcException {
String subset = dubboDestination.getSubset();
do {
BitList<Invoker<T>> result = meshRuleCache.getSubsetInvokers(appName, subset);
if (CollectionUtils.isNotEmpty(result)
&& !availableInvokers.clone().and(result).isEmpty()) {
return subset;
}
// fall back
DubboRouteDestination dubboRouteDestination = dubboDestination.getFallback();
if (dubboRouteDestination == null) {
break;
}
dubboDestination = dubboRouteDestination.getDestination();
if (dubboDestination == null) {
break;
}
subset = dubboDestination.getSubset();
} while (true);
return null;
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
BitList<Invoker<T>> invokerList = invokers == null ? BitList.emptyList() : invokers;
this.invokerList = invokerList.clone();
registerAppRule(invokerList);
computeSubset(this.meshRuleCache.getAppToVDGroup());
}
private void registerAppRule(BitList<Invoker<T>> invokers) {
Set<String> currentApplication = new HashSet<>();
if (CollectionUtils.isNotEmpty(invokers)) {
for (Invoker<T> invoker : invokers) {
String applicationName = invoker.getUrl().getRemoteApplication();
if (StringUtils.isNotEmpty(applicationName) && !INVALID_APP_NAME.equals(applicationName)) {
currentApplication.add(applicationName);
}
}
}
if (!remoteAppName.equals(currentApplication)) {
synchronized (this) {
Set<String> current = new HashSet<>(currentApplication);
Set<String> previous = new HashSet<>(remoteAppName);
previous.removeAll(currentApplication);
current.removeAll(remoteAppName);
for (String app : current) {
meshRuleManager.register(app, this);
}
for (String app : previous) {
meshRuleManager.unregister(app, this);
}
remoteAppName = currentApplication;
}
}
}
@Override
public synchronized void onRuleChange(String appName, List<Map<String, Object>> rules) {
// only update specified app's rule
Map<String, VsDestinationGroup> appToVDGroup = new ConcurrentHashMap<>(this.meshRuleCache.getAppToVDGroup());
try {
VsDestinationGroup vsDestinationGroup = new VsDestinationGroup();
vsDestinationGroup.setAppName(appName);
for (Map<String, Object> rule : rules) {
if (DESTINATION_RULE_KEY.equals(rule.get(KIND_KEY))) {
DestinationRule destinationRule = PojoUtils.mapToPojo(rule, DestinationRule.class);
vsDestinationGroup.getDestinationRuleList().add(destinationRule);
} else if (VIRTUAL_SERVICE_KEY.equals(rule.get(KIND_KEY))) {
VirtualServiceRule virtualServiceRule = PojoUtils.mapToPojo(rule, VirtualServiceRule.class);
vsDestinationGroup.getVirtualServiceRuleList().add(virtualServiceRule);
}
}
if (vsDestinationGroup.isValid()) {
appToVDGroup.put(appName, vsDestinationGroup);
}
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"failed to parse mesh route rule",
"",
"Error occurred when parsing rule component.",
t);
}
computeSubset(appToVDGroup);
}
@Override
public synchronized void clearRule(String appName) {
Map<String, VsDestinationGroup> appToVDGroup = new ConcurrentHashMap<>(this.meshRuleCache.getAppToVDGroup());
appToVDGroup.remove(appName);
computeSubset(appToVDGroup);
}
protected void computeSubset(Map<String, VsDestinationGroup> vsDestinationGroupMap) {
this.meshRuleCache =
MeshRuleCache.build(getUrl().getProtocolServiceKey(), this.invokerList, vsDestinationGroupMap);
}
@Override
public void stop() {
for (String app : remoteAppName) {
meshRuleManager.unregister(app, this);
}
}
/**
* for ut only
*/
@Deprecated
public Set<String> getRemoteAppName() {
return remoteAppName;
}
/**
* for ut only
*/
@Deprecated
public BitList<Invoker<T>> getInvokerList() {
return invokerList;
}
/**
* for ut only
*/
@Deprecated
public MeshRuleCache<T> getMeshRuleCache() {
return meshRuleCache;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
/**
* Mesh Rule Listener
* Such as Kubernetes, Service Mesh (xDS) environment support define rule in env
*/
public interface MeshEnvListener {
/**
* @return whether current environment support listen
*/
default boolean isEnable() {
return false;
}
void onSubscribe(String appName, MeshAppRuleListener listener);
void onUnSubscribe(String appName);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouter.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.STANDARD_ROUTER_KEY;
public class StandardMeshRuleRouter<T> extends MeshRuleRouter<T> {
public StandardMeshRuleRouter(URL url) {
super(url);
}
@Override
public String ruleSuffix() {
return STANDARD_ROUTER_KEY;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListenerFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListenerFactory.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface MeshEnvListenerFactory {
MeshEnvListener getListener();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleDispatcher;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.METADATA_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.NAME_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.STANDARD_ROUTER_KEY;
public class MeshAppRuleListener implements ConfigurationListener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshAppRuleListener.class);
private final MeshRuleDispatcher meshRuleDispatcher;
private final String appName;
private volatile Map<String, List<Map<String, Object>>> ruleMapHolder;
public MeshAppRuleListener(String appName) {
this.appName = appName;
this.meshRuleDispatcher = new MeshRuleDispatcher(appName);
}
@SuppressWarnings("unchecked")
public void receiveConfigInfo(String configInfo) {
if (logger.isDebugEnabled()) {
logger.debug(MessageFormat.format("[MeshAppRule] Received rule for app [{0}]: {1}.", appName, configInfo));
}
try {
Map<String, List<Map<String, Object>>> groupMap = new HashMap<>();
Representer representer = new Representer(new DumperOptions());
representer.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()), representer);
Iterable<Object> yamlIterator = yaml.loadAll(configInfo);
for (Object obj : yamlIterator) {
if (obj instanceof Map) {
Map<String, Object> resultMap = (Map<String, Object>) obj;
String ruleType = computeRuleType(resultMap);
if (ruleType != null) {
groupMap.computeIfAbsent(ruleType, (k) -> new LinkedList<>())
.add(resultMap);
} else {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"receive mesh app route rule is invalid",
"",
"Unable to get rule type from raw rule. "
+ "Probably the metadata.name is absent. App Name: " + appName + " RawRule: "
+ configInfo);
}
} else {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"receive mesh app route rule is invalid",
"",
"Rule format is unacceptable. App Name: " + appName + " RawRule: " + configInfo);
}
}
ruleMapHolder = groupMap;
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"failed to receive mesh app route rule",
"",
"[MeshAppRule] parse failed: " + configInfo,
e);
}
if (ruleMapHolder != null) {
meshRuleDispatcher.post(ruleMapHolder);
}
}
@SuppressWarnings("unchecked")
private String computeRuleType(Map<String, Object> rule) {
Object obj = rule.get(METADATA_KEY);
if (obj instanceof Map && CollectionUtils.isNotEmptyMap((Map<String, String>) obj)) {
Map<String, String> metadata = (Map<String, String>) obj;
String name = metadata.get(NAME_KEY);
if (!name.contains(".")) {
return STANDARD_ROUTER_KEY;
} else {
return name.substring(name.indexOf(".") + 1);
}
}
return null;
}
public <T> void register(MeshRuleListener subscriber) {
if (ruleMapHolder != null) {
List<Map<String, Object>> rule = ruleMapHolder.get(subscriber.ruleSuffix());
if (rule != null) {
subscriber.onRuleChange(appName, rule);
}
}
meshRuleDispatcher.register(subscriber);
}
public <T> void unregister(MeshRuleListener subscriber) {
meshRuleDispatcher.unregister(subscriber);
}
@Override
public void process(ConfigChangedEvent event) {
if (event.getChangeType() == ConfigChangeType.DELETED) {
receiveConfigInfo("");
return;
}
receiveConfigInfo(event.getContent());
}
public boolean isEmpty() {
return meshRuleDispatcher.isEmpty();
}
/**
* For ut only
*/
@Deprecated
public MeshRuleDispatcher getMeshRuleDispatcher() {
return meshRuleDispatcher;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleConstants.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleConstants.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
public class MeshRuleConstants {
public static final String INVALID_APP_NAME = "unknown";
public static final String DESTINATION_RULE_KEY = "DestinationRule";
public static final String VIRTUAL_SERVICE_KEY = "VirtualService";
public static final String KIND_KEY = "kind";
public static final String MESH_RULE_DATA_ID_SUFFIX = ".MESHAPPRULE";
public static final String NAME_KEY = "name";
public static final String METADATA_KEY = "metadata";
public static final String STANDARD_ROUTER_KEY = "standard";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.MESH_RULE_DATA_ID_SUFFIX;
public class MeshRuleManager {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshRuleManager.class);
private final ConcurrentHashMap<String, MeshAppRuleListener> APP_RULE_LISTENERS = new ConcurrentHashMap<>();
private final GovernanceRuleRepository ruleRepository;
private final Set<MeshEnvListener> envListeners;
public MeshRuleManager(ModuleModel moduleModel) {
this.ruleRepository = moduleModel.getDefaultExtension(GovernanceRuleRepository.class);
Set<MeshEnvListenerFactory> envListenerFactories =
moduleModel.getExtensionLoader(MeshEnvListenerFactory.class).getSupportedExtensionInstances();
this.envListeners = envListenerFactories.stream()
.map(MeshEnvListenerFactory::getListener)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
private synchronized MeshAppRuleListener subscribeAppRule(String app) {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener(app);
// demo-app.MESHAPPRULE
String appRuleDataId = app + MESH_RULE_DATA_ID_SUFFIX;
// Add listener to rule repository ( dynamic configuration )
try {
String rawConfig = ruleRepository.getRule(appRuleDataId, DynamicConfiguration.DEFAULT_GROUP, 5000L);
if (rawConfig != null) {
meshAppRuleListener.receiveConfigInfo(rawConfig);
}
} catch (Throwable throwable) {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"failed to get mesh app route rule",
"",
"get MeshRuleManager app rule failed.",
throwable);
}
ruleRepository.addListener(appRuleDataId, DynamicConfiguration.DEFAULT_GROUP, meshAppRuleListener);
// Add listener to env ( kubernetes, xDS )
for (MeshEnvListener envListener : envListeners) {
if (envListener.isEnable()) {
envListener.onSubscribe(app, meshAppRuleListener);
}
}
APP_RULE_LISTENERS.put(app, meshAppRuleListener);
return meshAppRuleListener;
}
private synchronized void unsubscribeAppRule(String app, MeshAppRuleListener meshAppRuleListener) {
// demo-app.MESHAPPRULE
String appRuleDataId = app + MESH_RULE_DATA_ID_SUFFIX;
// Remove listener from rule repository ( dynamic configuration )
ruleRepository.removeListener(appRuleDataId, DynamicConfiguration.DEFAULT_GROUP, meshAppRuleListener);
// Remove listener from env ( kubernetes, xDS )
for (MeshEnvListener envListener : envListeners) {
if (envListener.isEnable()) {
envListener.onUnSubscribe(app);
}
}
}
public synchronized <T> void register(String app, MeshRuleListener subscriber) {
MeshAppRuleListener meshAppRuleListener = APP_RULE_LISTENERS.get(app);
if (meshAppRuleListener == null) {
meshAppRuleListener = subscribeAppRule(app);
}
meshAppRuleListener.register(subscriber);
}
public synchronized <T> void unregister(String app, MeshRuleListener subscriber) {
MeshAppRuleListener meshAppRuleListener = APP_RULE_LISTENERS.get(app);
meshAppRuleListener.unregister(subscriber);
if (meshAppRuleListener.isEmpty()) {
unsubscribeAppRule(app, meshAppRuleListener);
APP_RULE_LISTENERS.remove(app);
}
}
/**
* for ut only
*/
@Deprecated
public ConcurrentHashMap<String, MeshAppRuleListener> getAppRuleListeners() {
return APP_RULE_LISTENERS;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java | /*
* 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.dubbo.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.VsDestinationGroup;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRuleSpec;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.Subset;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.INVALID_APP_NAME;
public class MeshRuleCache<T> {
private final List<String> appList;
private final Map<String, VsDestinationGroup> appToVDGroup;
private final Map<String, Map<String, BitList<Invoker<T>>>> totalSubsetMap;
private final BitList<Invoker<T>> unmatchedInvokers;
private MeshRuleCache(
List<String> appList,
Map<String, VsDestinationGroup> appToVDGroup,
Map<String, Map<String, BitList<Invoker<T>>>> totalSubsetMap,
BitList<Invoker<T>> unmatchedInvokers) {
this.appList = appList;
this.appToVDGroup = appToVDGroup;
this.totalSubsetMap = totalSubsetMap;
this.unmatchedInvokers = unmatchedInvokers;
}
public List<String> getAppList() {
return appList;
}
public Map<String, VsDestinationGroup> getAppToVDGroup() {
return appToVDGroup;
}
public Map<String, Map<String, BitList<Invoker<T>>>> getTotalSubsetMap() {
return totalSubsetMap;
}
public BitList<Invoker<T>> getUnmatchedInvokers() {
return unmatchedInvokers;
}
public VsDestinationGroup getVsDestinationGroup(String appName) {
return appToVDGroup.get(appName);
}
public BitList<Invoker<T>> getSubsetInvokers(String appName, String subset) {
Map<String, BitList<Invoker<T>>> appToSubSets = totalSubsetMap.get(appName);
if (CollectionUtils.isNotEmptyMap(appToSubSets)) {
BitList<Invoker<T>> subsetInvokers = appToSubSets.get(subset);
if (CollectionUtils.isNotEmpty(subsetInvokers)) {
return subsetInvokers;
}
}
return BitList.emptyList();
}
public boolean containsRule() {
return !totalSubsetMap.isEmpty();
}
public static <T> MeshRuleCache<T> build(
String protocolServiceKey,
BitList<Invoker<T>> invokers,
Map<String, VsDestinationGroup> vsDestinationGroupMap) {
if (CollectionUtils.isNotEmptyMap(vsDestinationGroupMap)) {
BitList<Invoker<T>> unmatchedInvokers = new BitList<>(invokers.getOriginList(), true);
Map<String, Map<String, BitList<Invoker<T>>>> totalSubsetMap = new HashMap<>();
for (Invoker<T> invoker : invokers) {
String remoteApplication = invoker.getUrl().getRemoteApplication();
if (StringUtils.isEmpty(remoteApplication) || INVALID_APP_NAME.equals(remoteApplication)) {
unmatchedInvokers.add(invoker);
continue;
}
VsDestinationGroup vsDestinationGroup = vsDestinationGroupMap.get(remoteApplication);
if (vsDestinationGroup == null) {
unmatchedInvokers.add(invoker);
continue;
}
Map<String, BitList<Invoker<T>>> subsetMap =
totalSubsetMap.computeIfAbsent(remoteApplication, (k) -> new HashMap<>());
boolean matched = false;
for (DestinationRule destinationRule : vsDestinationGroup.getDestinationRuleList()) {
DestinationRuleSpec destinationRuleSpec = destinationRule.getSpec();
List<Subset> subsetList = destinationRuleSpec.getSubsets();
for (Subset subset : subsetList) {
String subsetName = subset.getName();
List<Invoker<T>> subsetInvokers = subsetMap.computeIfAbsent(
subsetName, (k) -> new BitList<>(invokers.getOriginList(), true));
Map<String, String> labels = subset.getLabels();
if (isLabelMatch(invoker.getUrl(), protocolServiceKey, labels)) {
subsetInvokers.add(invoker);
matched = true;
}
}
}
if (!matched) {
unmatchedInvokers.add(invoker);
}
}
return new MeshRuleCache<>(
new LinkedList<>(vsDestinationGroupMap.keySet()),
Collections.unmodifiableMap(vsDestinationGroupMap),
Collections.unmodifiableMap(totalSubsetMap),
unmatchedInvokers);
} else {
return new MeshRuleCache<>(
Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), invokers);
}
}
public static <T> MeshRuleCache<T> emptyCache() {
return new MeshRuleCache<>(
Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), BitList.emptyList());
}
protected static boolean isLabelMatch(URL url, String protocolServiceKey, Map<String, String> inputMap) {
if (inputMap == null || inputMap.size() == 0) {
return true;
}
for (Map.Entry<String, String> entry : inputMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
String originMapValue = url.getOriginalServiceParameter(protocolServiceKey, key);
if (!value.equals(originMapValue)) {
return false;
}
}
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MeshRuleCache<?> ruleCache = (MeshRuleCache<?>) o;
return Objects.equals(appList, ruleCache.appList)
&& Objects.equals(appToVDGroup, ruleCache.appToVDGroup)
&& Objects.equals(totalSubsetMap, ruleCache.totalSubsetMap)
&& Objects.equals(unmatchedInvokers, ruleCache.unmatchedInvokers);
}
@Override
public int hashCode() {
return Objects.hash(appList, appToVDGroup, totalSubsetMap, unmatchedInvokers);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/DefaultGovernanceRuleRepositoryImpl.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/DefaultGovernanceRuleRepositoryImpl.java | /*
* 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.dubbo.rpc.cluster.governance;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.rpc.model.ModuleModel;
public class DefaultGovernanceRuleRepositoryImpl implements GovernanceRuleRepository {
private final ModuleModel moduleModel;
public DefaultGovernanceRuleRepositoryImpl(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
}
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
DynamicConfiguration dynamicConfiguration = getDynamicConfiguration();
if (dynamicConfiguration != null) {
dynamicConfiguration.addListener(key, group, listener);
}
}
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {
DynamicConfiguration dynamicConfiguration = getDynamicConfiguration();
if (dynamicConfiguration != null) {
dynamicConfiguration.removeListener(key, group, listener);
}
}
@Override
public String getRule(String key, String group, long timeout) throws IllegalStateException {
DynamicConfiguration dynamicConfiguration = getDynamicConfiguration();
if (dynamicConfiguration != null) {
return dynamicConfiguration.getConfig(key, group, timeout);
}
return null;
}
private DynamicConfiguration getDynamicConfiguration() {
return moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/GovernanceRuleRepository.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/GovernanceRuleRepository.java | /*
* 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.dubbo.rpc.cluster.governance;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.extension.ExtensionScope.MODULE;
@SPI(value = "default", scope = MODULE)
public interface GovernanceRuleRepository {
String DEFAULT_GROUP = "dubbo";
/**
* {@link #addListener(String, String, ConfigurationListener)}
*
* @param key the key to represent a configuration
* @param listener configuration listener
*/
default void addListener(String key, ConfigurationListener listener) {
addListener(key, DEFAULT_GROUP, listener);
}
/**
* {@link #removeListener(String, String, ConfigurationListener)}
*
* @param key the key to represent a configuration
* @param listener configuration listener
*/
default void removeListener(String key, ConfigurationListener listener) {
removeListener(key, DEFAULT_GROUP, listener);
}
/**
* Register a configuration listener for a specified key
* The listener only works for service governance purpose, so the target group would always be the value user
* specifies at startup or 'dubbo' by default. This method will only register listener, which means it will not
* trigger a notification that contains the current value.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param listener configuration listener
*/
void addListener(String key, String group, ConfigurationListener listener);
/**
* Stops one listener from listening to value changes in the specified key.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param listener configuration listener
*/
void removeListener(String key, String group, ConfigurationListener listener);
/**
* Get the governance rule mapped to the given key and the given group
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @return target configuration mapped to the given key and the given group
*/
default String getRule(String key, String group) {
return getRule(key, group, -1L);
}
/**
* Get the governance rule mapped to the given key and the given group. If the
* rule fails to return after timeout exceeds, IllegalStateException will be thrown.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param timeout timeout value for fetching the target config
* @return target configuration mapped to the given key and the given group, IllegalStateException will be thrown
* if timeout exceeds.
*/
String getRule(String key, String group, long timeout) throws IllegalStateException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/registry/AddressListener.java | dubbo-cluster/src/main/java/org/apache/dubbo/registry/AddressListener.java | /*
* 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.dubbo.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.List;
@SPI(scope = ExtensionScope.MODULE)
public interface AddressListener {
/**
* processing when receiving the address list
*
* @param addresses provider address list
* @param consumerUrl
* @param registryDirectory
*/
List<URL> notify(List<URL> addresses, URL consumerUrl, Directory registryDirectory);
default void destroy(URL consumerUrl, Directory registryDirectory) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringJavaConfigBeanTest.java | dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringJavaConfigBeanTest.java | /*
* 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.dubbo.test.spring;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import org.apache.dubbo.test.common.SysProps;
import org.apache.dubbo.test.common.api.DemoService;
import org.apache.dubbo.test.common.impl.DemoServiceImpl;
import org.apache.dubbo.test.spring.context.MockSpringInitCustomizer;
import java.util.Collection;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class SpringJavaConfigBeanTest {
private static final String MY_PROTOCOL_ID = "myProtocol";
private static final String MY_REGISTRY_ID = "my-registry";
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@BeforeEach
public void beforeEach() {
DubboBootstrap.reset();
}
@AfterEach
public void afterEach() {
SysProps.clear();
}
@Test
public void testBean() {
SysProps.setProperty("dubbo.application.owner", "Tom");
SysProps.setProperty("dubbo.application.qos-enable", "false");
SysProps.setProperty("dubbo.protocol.name", "dubbo");
SysProps.setProperty("dubbo.protocol.port", "2346");
String registryAddress = ZookeeperRegistryCenterConfig.getConnectionAddress();
SysProps.setProperty("dubbo.registry.address", registryAddress);
SysProps.setProperty("dubbo.provider.group", "test");
AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(
TestConfiguration.class, ConsumerConfiguration.class, ProviderConfiguration.class);
try {
consumerContext.start();
ApplicationModel applicationModel = consumerContext.getBean(ApplicationModel.class);
ConfigManager configManager = consumerContext.getBean(ConfigManager.class);
ApplicationConfig application = configManager.getApplication().get();
Assertions.assertEquals(false, application.getQosEnable());
Assertions.assertEquals("Tom", application.getOwner());
RegistryConfig registry = configManager.getRegistry(MY_REGISTRY_ID).get();
Assertions.assertEquals(registryAddress, registry.getAddress());
Collection<ProtocolConfig> protocols = configManager.getProtocols();
Assertions.assertEquals(1, protocols.size());
ProtocolConfig protocolConfig = protocols.iterator().next();
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(2346, protocolConfig.getPort());
Assertions.assertEquals(MY_PROTOCOL_ID, protocolConfig.getId());
ModuleConfigManager moduleConfigManager =
applicationModel.getDefaultModule().getConfigManager();
ConsumerConfig consumerConfig =
moduleConfigManager.getDefaultConsumer().get();
Assertions.assertEquals(1000, consumerConfig.getTimeout());
Assertions.assertEquals("demo", consumerConfig.getGroup());
Assertions.assertEquals(false, consumerConfig.isCheck());
Assertions.assertEquals(2, consumerConfig.getRetries());
Map<String, ReferenceBean> referenceBeanMap = consumerContext.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
ReferenceBean referenceBean = referenceBeanMap.get("&demoService");
Assertions.assertNotNull(referenceBean);
ReferenceConfig referenceConfig = referenceBean.getReferenceConfig();
// use consumer's attributes as default value
Assertions.assertEquals(consumerConfig.getTimeout(), referenceConfig.getTimeout());
Assertions.assertEquals(consumerConfig.getGroup(), referenceConfig.getGroup());
// consumer cannot override reference's attribute
Assertions.assertEquals(5, referenceConfig.getRetries());
DemoService referProxy = (DemoService) referenceConfig.get();
Assertions.assertTrue(referProxy instanceof DemoService);
String result = referProxy.sayHello("dubbo");
Assertions.assertEquals("Hello dubbo", result);
// check initialization customizer
MockSpringInitCustomizer.checkCustomizer(consumerContext);
} finally {
consumerContext.close();
}
}
@EnableDubbo(scanBasePackages = "")
@Configuration
static class TestConfiguration {
@Bean(name = "dubbo-demo-application")
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubbo-demo-application");
return applicationConfig;
}
@Bean(name = MY_PROTOCOL_ID)
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("rest");
protocolConfig.setPort(1234);
return protocolConfig;
}
@Bean(name = MY_REGISTRY_ID)
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("N/A");
return registryConfig;
}
@Bean
public ConsumerConfig consumerConfig() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setTimeout(1000);
consumer.setGroup("demo");
consumer.setCheck(false);
consumer.setRetries(2);
return consumer;
}
}
@Configuration
static class ConsumerConfiguration {
@Bean
@DubboReference(scope = Constants.SCOPE_LOCAL, retries = 5)
public ReferenceBean<DemoService> demoService() {
return new ReferenceBean<>();
}
}
@Configuration
static class ProviderConfiguration {
@Bean
@DubboService(group = "demo")
public DemoService demoServiceImpl() {
return new DemoServiceImpl();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java | dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java | /*
* 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.dubbo.test.spring;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.test.common.api.DemoService;
import org.apache.dubbo.test.spring.context.MockSpringInitCustomizer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
public class SpringAnnotationBeanTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
public void test() {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(TestConfiguration.class);
TestService testService = applicationContext.getBean(TestService.class);
testService.test();
// check initialization customizer
MockSpringInitCustomizer.checkCustomizer(applicationContext);
}
@EnableDubbo(scanBasePackages = "org.apache.dubbo.test.common.impl")
@Configuration
@PropertySource("/demo-app.properties")
static class TestConfiguration {
@Bean
public TestService testService() {
return new TestService();
}
}
static class TestService {
@DubboReference
private DemoService demoService;
public void test() {
String result = demoService.sayHello("dubbo");
Assertions.assertEquals("Hello dubbo", result);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringXmlConfigTest.java | dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringXmlConfigTest.java | /*
* 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.dubbo.test.spring;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.test.common.SysProps;
import org.apache.dubbo.test.common.api.DemoService;
import org.apache.dubbo.test.common.api.GreetingService;
import org.apache.dubbo.test.common.api.RestDemoService;
import org.apache.dubbo.test.spring.context.MockSpringInitCustomizer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
@DisabledForJreRange(min = JRE.JAVA_16)
public class SpringXmlConfigTest {
private static ClassPathXmlApplicationContext providerContext;
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
providerContext.close();
}
private void startProvider() {
providerContext = new ClassPathXmlApplicationContext("/spring/dubbo-demo-provider.xml");
}
@Test
public void test() {
SysProps.setProperty(SHUTDOWN_WAIT_KEY, "2000");
// start provider context
startProvider();
// start consumer context
ClassPathXmlApplicationContext applicationContext = null;
try {
applicationContext = new ClassPathXmlApplicationContext("/spring/dubbo-demo.xml");
GreetingService greetingService = applicationContext.getBean("greetingService", GreetingService.class);
String greeting = greetingService.hello();
Assertions.assertEquals(greeting, "Greetings!");
DemoService demoService = applicationContext.getBean("demoService", DemoService.class);
String sayHelloResult = demoService.sayHello("dubbo");
Assertions.assertTrue(sayHelloResult.startsWith("Hello dubbo"), sayHelloResult);
RestDemoService restDemoService = applicationContext.getBean("restDemoService", RestDemoService.class);
String resetHelloResult = restDemoService.sayHello("dubbo");
Assertions.assertEquals("Hello, dubbo", resetHelloResult);
// check initialization customizer
MockSpringInitCustomizer.checkCustomizer(applicationContext);
} finally {
SysProps.clear();
if (applicationContext != null) {
applicationContext.close();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java | dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java | /*
* 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.dubbo.test.spring.context;
import org.apache.dubbo.config.spring.context.DubboSpringInitContext;
import org.apache.dubbo.config.spring.context.DubboSpringInitCustomizer;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.ConfigurableApplicationContext;
public class MockSpringInitCustomizer implements DubboSpringInitCustomizer {
private List<DubboSpringInitContext> contexts = new ArrayList<>();
@Override
public void customize(DubboSpringInitContext context) {
this.contexts.add(context);
// register post-processor bean, expecting the bean is loaded and invoked by spring container
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(
CustomBeanFactoryPostProcessor.class)
.getBeanDefinition();
context.getRegistry().registerBeanDefinition(CustomBeanFactoryPostProcessor.class.getName(), beanDefinition);
}
public List<DubboSpringInitContext> getContexts() {
return contexts;
}
private static class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
public static void checkCustomizer(ConfigurableApplicationContext applicationContext) {
Set<DubboSpringInitCustomizer> customizers = FrameworkModel.defaultModel()
.getExtensionLoader(DubboSpringInitCustomizer.class)
.getSupportedExtensionInstances();
MockSpringInitCustomizer mockCustomizer = null;
for (DubboSpringInitCustomizer customizer : customizers) {
if (customizer instanceof MockSpringInitCustomizer) {
mockCustomizer = (MockSpringInitCustomizer) customizer;
break;
}
}
Assertions.assertNotNull(mockCustomizer);
// check applicationContext
boolean foundInitContext = false;
List<DubboSpringInitContext> contexts = mockCustomizer.getContexts();
for (DubboSpringInitContext initializationContext : contexts) {
if (initializationContext.getRegistry() == applicationContext.getBeanFactory()) {
foundInitContext = true;
break;
}
}
Assertions.assertEquals(true, foundInitContext);
// expect CustomBeanFactoryPostProcessor is loaded and invoked
CustomBeanFactoryPostProcessor customBeanFactoryPostProcessor =
applicationContext.getBean(CustomBeanFactoryPostProcessor.class);
Assertions.assertEquals(applicationContext.getBeanFactory(), customBeanFactoryPostProcessor.beanFactory);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/ErrorHandler.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/ErrorHandler.java | /*
* 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.dubbo.test.common;
@FunctionalInterface
public interface ErrorHandler {
/**
* Handle the given error, possibly rethrowing it as a fatal exception.
*/
void handleError(Throwable t);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java | /*
* 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.dubbo.test.common;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Use to set and clear System property
*/
public class SysProps {
private static Map<String, String> map = new LinkedHashMap<>();
public static void reset() {
map.clear();
}
public static void setProperty(String key, String value) {
map.put(key, value);
System.setProperty(key, value);
}
public static void clear() {
for (String key : map.keySet()) {
System.clearProperty(key);
}
reset();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/RestDemoServiceImpl.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/RestDemoServiceImpl.java | /*
* 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.dubbo.test.common.impl;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.test.common.api.RestDemoService;
import java.util.Map;
public class RestDemoServiceImpl implements RestDemoService {
private static Map<String, Object> context;
private boolean called;
public String sayHello(String name) {
called = true;
return "Hello, " + name;
}
public boolean isCalled() {
return called;
}
@Override
public Integer hello(Integer a, Integer b) {
context = RpcContext.getServerAttachment().getObjectAttachments();
return a + b;
}
@Override
public String error() {
throw new RuntimeException();
}
public static Map<String, Object> getAttachments() {
return context;
}
@Override
public String getRemoteApplicationName() {
return RpcContext.getServiceContext().getRemoteApplicationName();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/DemoServiceImpl.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/DemoServiceImpl.java | /*
* 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.dubbo.test.common.impl;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.test.common.api.DemoService;
import java.util.concurrent.CompletableFuture;
@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello " + name;
}
@Override
public CompletableFuture<String> sayHelloAsync(String name) {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
return "async result:" + name;
});
return cf;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/GreetingServiceImpl.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/GreetingServiceImpl.java | /*
* 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.dubbo.test.common.impl;
import org.apache.dubbo.test.common.api.GreetingService;
public class GreetingServiceImpl implements GreetingService {
@Override
public String hello() {
return "Greetings!";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/utils/TestSocketUtils.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/utils/TestSocketUtils.java | /*
* Copyright 2002-2022 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.apache.dubbo.test.common.utils;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.security.SecureRandom;
import javax.net.ServerSocketFactory;
import org.apache.dubbo.common.utils.Assert;
/**
* Simple utility for finding available TCP ports on {@code localhost} for use in
* integration testing scenarios.
*
* <p>{@code TestSocketUtils} can be used in integration tests which start an
* external server on an available random port. However, these utilities make no
* guarantee about the subsequent availability of a given port and are therefore
* unreliable. Instead of using {@code TestSocketUtils} to find an available local
* port for a server, it is recommended that you rely on a server's ability to
* start on a random <em>ephemeral</em> port that it selects or is assigned by the
* operating system. To interact with that server, you should query the server
* for the port it is currently using.
*
* @since 3.2
*/
public class TestSocketUtils {
/**
* The minimum value for port ranges used when finding an available TCP port.
*/
static final int PORT_RANGE_MIN = 1024;
/**
* The maximum value for port ranges used when finding an available TCP port.
*/
static final int PORT_RANGE_MAX = 65535;
private static final int PORT_RANGE_PLUS_ONE = PORT_RANGE_MAX - PORT_RANGE_MIN + 1;
private static final int MAX_ATTEMPTS = 1_000;
private static final SecureRandom random = new SecureRandom();
private static final TestSocketUtils INSTANCE = new TestSocketUtils();
private TestSocketUtils() {
}
/**
* Find an available TCP port randomly selected from the range [1024, 65535].
* @return an available TCP port number
* @throws IllegalStateException if no available port could be found
*/
public static int findAvailableTcpPort() {
return INSTANCE.findAvailableTcpPortInternal();
}
/**
* Internal implementation of {@link #findAvailableTcpPort()}.
* <p>Package-private solely for testing purposes.
*/
int findAvailableTcpPortInternal() {
int candidatePort;
int searchCounter = 0;
do {
Assert.assertTrue(++searchCounter <= MAX_ATTEMPTS, String.format(
"Could not find an available TCP port in the range [%d, %d] after %d attempts",
PORT_RANGE_MIN, PORT_RANGE_MAX, MAX_ATTEMPTS));
candidatePort = PORT_RANGE_MIN + random.nextInt(PORT_RANGE_PLUS_ONE);
}
while (!isPortAvailable(candidatePort));
return candidatePort;
}
/**
* Determine if the specified TCP port is currently available on {@code localhost}.
* <p>Package-private solely for testing purposes.
*/
boolean isPortAvailable(int port) {
try {
ServerSocket serverSocket = ServerSocketFactory.getDefault()
.createServerSocket(port, 1, InetAddress.getByName("localhost"));
serverSocket.close();
return true;
}
catch (Exception ex) {
return false;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/DemoService.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/DemoService.java | /*
* 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.dubbo.test.common.api;
import java.util.concurrent.CompletableFuture;
public interface DemoService {
String sayHello(String name);
CompletableFuture<String> sayHelloAsync(String name);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/RestDemoService.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/RestDemoService.java | /*
* 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.dubbo.test.common.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/demoService")
public interface RestDemoService {
@GET
@Path("/hello")
Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b);
@GET
@Path("/error")
String error();
@POST
@Path("/say")
@Consumes({MediaType.TEXT_PLAIN})
String sayHello(String name);
@GET
@Path("/getRemoteApplicationName")
String getRemoteApplicationName();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/GreetingService.java | dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/GreetingService.java | /*
* 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.dubbo.test.common.api;
public interface GreetingService {
String hello();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterStarted.java | dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterStarted.java | /*
* 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.dubbo.test.check;
import org.apache.dubbo.test.check.registrycenter.GlobalRegistryCenter;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
/**
* The entrance to start the mocked registry center.
*/
public class RegistryCenterStarted extends AbstractRegistryCenterTestExecutionListener {
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
try {
if (needRegistryCenter(testPlan)) {
GlobalRegistryCenter.startup();
}
} catch (Throwable cause) {
throw new IllegalStateException("Failed to start zookeeper instance in unit test", cause);
}
}
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
try {
if (needRegistryCenter(testIdentifier)) {
GlobalRegistryCenter.reset();
}
} catch (Throwable cause) {
// ignore the exception
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.