Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,9 @@ private Mono<Void> matchRuleAndExecute(final ServerWebExchange exchange, final S
selectorCache, CacheResolution.NOT_CONSULTED);
return doExecute(exchange, chain, selectorData, rule);
}
// consult the bounded per-path match cache first when it is enabled.
// on a cache miss, match the current rule list with the default strategy.
RuleData ruleData = obtainRuleDataCacheIfEnabled(path);
// Consult the bounded selector-scoped rule cache when it is enabled.
// On a cache miss, match the current rule list with the default strategy.
RuleData ruleData = obtainRuleDataCacheIfEnabled(selectorData.getId(), path);
CacheResolution ruleCache = Objects.nonNull(ruleData) ? CacheResolution.POSITIVE_HIT
: cacheResolution(ruleMatchConfig.getCache().getEnabled());
if (Objects.nonNull(ruleData) && Objects.isNull(ruleData.getId())) {
Expand All @@ -163,7 +163,7 @@ private Mono<Void> matchRuleAndExecute(final ServerWebExchange exchange, final S
return handleRuleIfNull(pluginName, exchange, chain);
}
if (Objects.isNull(ruleData)) {
ruleData = defaultMatchRule(exchange, selectors, rules, path);
ruleData = defaultMatchRule(exchange, rules, selectorData.getId(), path);
if (Objects.isNull(ruleData)) {
reportDecision(Decision.RULE_UNMATCHED, selectorData, null, false,
selectorCache, ruleCache);
Expand Down Expand Up @@ -236,8 +236,8 @@ private SelectorData obtainSelectorDataCacheIfEnabled(final String path) {
return selectorMatchConfig.getCache().getEnabled() ? MatchDataCache.getInstance().obtainSelectorData(named(), path) : null;
}

private RuleData obtainRuleDataCacheIfEnabled(final String path) {
return ruleMatchConfig.getCache().getEnabled() ? MatchDataCache.getInstance().obtainRuleData(named(), path) : null;
private RuleData obtainRuleDataCacheIfEnabled(final String selectorId, final String path) {
return ruleMatchConfig.getCache().getEnabled() ? MatchDataCache.getInstance().obtainRuleData(named(), selectorId, path) : null;
}

private void cacheSelectorData(final String path, final SelectorData selectorData) {
Expand All @@ -261,7 +261,7 @@ private void cacheSelectorData(final String path, final SelectorData selectorDat
}
}

private void cacheRuleData(final String path, final RuleData ruleData) {
private void cacheRuleData(final String selectorId, final String path, final RuleData ruleData) {
// if the ruleCache is disabled or rule data is null, not cache rule data.
if (Boolean.FALSE.equals(ruleMatchConfig.getCache().getEnabled()) || Objects.isNull(ruleData)
|| Boolean.TRUE.equals(ruleData.getMatchRestful())) {
Expand All @@ -271,14 +271,14 @@ private void cacheRuleData(final String path, final RuleData ruleData) {
long maximumSize = ruleMatchConfig.getCache().getMaximumSize();
long ttl = ruleMatchConfig.getCache().getTtl();
if (StringUtils.isBlank(ruleData.getId())) {
MatchDataCache.getInstance().cacheRuleData(path, ruleData, initialCapacity, maximumSize, ttl);
MatchDataCache.getInstance().cacheRuleData(selectorId, path, ruleData, initialCapacity, maximumSize, ttl);
return;
}
List<ConditionData> conditionList = ruleData.getConditionDataList();
if (CollectionUtils.isNotEmpty(conditionList)) {
boolean isUriCondition = conditionList.stream().allMatch(v -> URI_CONDITION_TYPE.equals(v.getParamType()));
if (isUriCondition) {
MatchDataCache.getInstance().cacheRuleData(path, ruleData, initialCapacity, maximumSize, ttl);
MatchDataCache.getInstance().cacheRuleData(selectorId, path, ruleData, initialCapacity, maximumSize, ttl);
}
}
}
Expand Down Expand Up @@ -396,23 +396,21 @@ private SelectorData defaultMatchSelector(final ServerWebExchange exchange, fina
}
}

private RuleData defaultMatchRule(final ServerWebExchange exchange, final List<SelectorData> selectors,
final List<RuleData> rules, final String path) {
private RuleData defaultMatchRule(final ServerWebExchange exchange, final List<RuleData> rules, final String selectorId, final String path) {
Pair<Boolean, RuleData> matchRulePair = matchRule(exchange, rules);
RuleData ruleData = matchRulePair.getRight();
if (Objects.nonNull(ruleData)) {
// cache rule data
if (matchRulePair.getLeft() && rules.stream().filter(RuleData::getEnabled)
.allMatch(rule -> !Boolean.TRUE.equals(rule.getMatchRestful()) && pathOnlyConditions(rule.getConditionDataList()))) {
cacheRuleData(path, ruleData);
cacheRuleData(selectorId, path, ruleData);
}
return ruleData;
} else {
// The rule cache key carries no selector id, so a negative entry additionally
// requires the whole selector set to be decided by the path.
if (matchRulePair.getLeft() && pathOnlySelectorSet(selectors) && pathOnlyRuleSet(rules)) {
RuleData emptyRuleData = RuleData.builder().pluginName(named()).build();
cacheRuleData(path, emptyRuleData);
// Selector identity is in the key; all rule candidates must still be path-only.
if (matchRulePair.getLeft() && pathOnlyRuleSet(rules)) {
RuleData emptyRuleData = RuleData.builder().pluginName(named()).selectorId(selectorId).build();
cacheRuleData(selectorId, path, emptyRuleData);
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@

/**
* plugin name -> LRU Map.
* LRU Map: path -> rule data.
* LRU Map: path or selector-scoped path -> rule data.
*/
private static final ConcurrentMap<String, Map<String, RuleData>> RULE_DATA_MAP = Maps.newConcurrentMap();

Expand Down Expand Up @@ -176,6 +176,21 @@
MapUtils.computeIfAbsent(RULE_DATA_MAP, ruleData.getPluginName(), map ->
new WindowTinyLFUMap<>(initialCapacity, ttl, maximumSize, Boolean.FALSE)).put(path, ruleData);
}

/**
* Cache a rule match within its selected selector, retaining the per-plugin size bound.
*
* @param selectorId selected selector id
* @param path request path
* @param ruleData matched rule or negative result
* @param initialCapacity initial capacity
* @param maximumSize maximum size per plugin
* @param ttl lifetime in milliseconds
*/
public void cacheRuleData(final String selectorId, final String path, final RuleData ruleData,

Check warning on line 190 in shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/cache/MatchDataCache.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q5

[Q5] More than 5 parameters (found 6). Group related parameters into a value object.
final int initialCapacity, final long maximumSize, final long ttl) {
cacheRuleData(ruleCacheKey(selectorId, path), ruleData, initialCapacity, maximumSize, ttl);
}

/**
* remove rule data.
Expand Down Expand Up @@ -260,6 +275,22 @@
final Map<String, RuleData> lruMap = RULE_DATA_MAP.get(pluginName);
return Optional.ofNullable(lruMap).orElse(Maps.newHashMap()).get(path);
}

/**
* Obtain a rule match for the selected selector and request path.
*
* @param pluginName plugin name
* @param selectorId selected selector id
* @param path request path
* @return matched rule or negative result
*/
public RuleData obtainRuleData(final String pluginName, final String selectorId, final String path) {
return obtainRuleData(pluginName, ruleCacheKey(selectorId, path));
}

private static String ruleCacheKey(final String selectorId, final String path) {
return selectorId.length() + ":" + selectorId + path;
}

/**
* get selector match cache.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,14 @@
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

Expand Down Expand Up @@ -424,6 +427,90 @@ public void clear() {
MatchDataCache.getInstance().cleanRuleDataData();
}

@Test
public void ruleCacheMustNotReuseAnotherSelectorsRule() {
SelectorData first = cacheTenantSelector("first", "a");
SelectorData second = cacheTenantSelector("second", "b");
final RuleData firstRule = cachePathRule("first-rule", first.getId(), "/x");
final RuleData secondRule = cachePathRule("second-rule", second.getId(), "/x");
ServerWebExchange firstExchange = tenantExchange("a");
ServerWebExchange secondExchange = tenantExchange("b");

testShenyuPlugin.execute(firstExchange, shenyuPluginChain).block();
testShenyuPlugin.execute(secondExchange, shenyuPluginChain).block();
testShenyuPlugin.execute(firstExchange, shenyuPluginChain).block();

verify(testShenyuPlugin, times(2)).doExecute(firstExchange, shenyuPluginChain, first, firstRule);
verify(testShenyuPlugin).doExecute(secondExchange, shenyuPluginChain, second, secondRule);
verify(testShenyuPlugin, never()).doExecute(secondExchange, shenyuPluginChain, second, firstRule);
}

@Test
public void ruleCacheMissMustNotSuppressAnotherSelector() {
SelectorData first = cacheTenantSelector("first", "a");
SelectorData second = cacheTenantSelector("second", "b");
cachePathRule("first-rule", first.getId(), "/other");
final RuleData secondRule = cachePathRule("second-rule", second.getId(), "/x");
ServerWebExchange firstExchange = tenantExchange("a");
ServerWebExchange secondExchange = tenantExchange("b");
ShenyuPluginChain chain = ignored -> Mono.empty();

testShenyuPlugin.execute(firstExchange, chain).block();
testShenyuPlugin.execute(secondExchange, chain).block();

verify(testShenyuPlugin, never()).doExecute(eq(firstExchange), any(), any(), any());
verify(testShenyuPlugin).doExecute(secondExchange, chain, second, secondRule);
}

@Test
public void ruleCacheHitMustNotHideAnotherSelectorsMiss() {
SelectorData first = cacheTenantSelector("first", "a");
SelectorData second = cacheTenantSelector("second", "b");
final RuleData firstRule = cachePathRule("first-rule", first.getId(), "/x");
cachePathRule("second-rule", second.getId(), "/other");
ServerWebExchange firstExchange = tenantExchange("a");
ServerWebExchange secondExchange = tenantExchange("b");
ShenyuPluginChain chain = ignored -> Mono.empty();

testShenyuPlugin.execute(firstExchange, chain).block();
testShenyuPlugin.execute(secondExchange, chain).block();

verify(testShenyuPlugin).doExecute(firstExchange, chain, first, firstRule);
verify(testShenyuPlugin, never()).doExecute(eq(secondExchange), any(), any(), any());
assertNull(MatchDataCache.getInstance().obtainSelectorData("SHENYU", "/x"));
}

private SelectorData cacheTenantSelector(final String id, final String tenant) {
ConditionData condition = new ConditionData();
condition.setParamType("header");
condition.setParamName("X-Tenant");
condition.setOperator("=");
condition.setParamValue(tenant);
SelectorData selector = SelectorData.builder().id(id).pluginName("SHENYU").enabled(true)
.continued(true).logged(false).matchRestful(false).matchMode(0).sort(0)
.type(SelectorTypeEnum.CUSTOM_FLOW.getCode()).conditionList(Collections.singletonList(condition)).build();
BaseDataCache.getInstance().cachePluginData(pluginData);
BaseDataCache.getInstance().cacheSelectData(selector);
return selector;
}

private RuleData cachePathRule(final String id, final String selectorId, final String path) {
ConditionData condition = new ConditionData();
condition.setParamType("uri");
condition.setParamName("/");
condition.setOperator("=");
condition.setParamValue(path);
RuleData rule = RuleData.builder().id(id).pluginName("SHENYU").selectorId(selectorId)
.enabled(true).logged(false).matchRestful(false).matchMode(0).sort(0)
.conditionDataList(Collections.singletonList(condition)).build();
BaseDataCache.getInstance().cacheRuleData(rule);
return rule;
}

private ServerWebExchange tenantExchange(final String tenant) {
return MockServerWebExchange.from(MockServerHttpRequest.get("/x").header("X-Tenant", tenant));
}

private void clearCache() {
BaseDataCache.getInstance().cleanPluginData();
BaseDataCache.getInstance().cleanSelectorData();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ void dynamicRuleMissMustNotBeCached(final String paramType) {
BaseDataCache.getInstance().cacheRuleData(dynamic);

execute(false);
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, "/x"));
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, "selector", "/x"));
assertNull(plugin.rule);

execute(true);
Expand All @@ -126,7 +126,8 @@ void ruleMissMustNotBeCachedAcrossDynamicSelectors() {
BaseDataCache.getInstance().cacheRuleData(secondRule);

execute(true);
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, "/x"));
assertNotNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, first.getId(), "/x"));
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, second.getId(), "/x"));

execute(false);
assertSame(secondRule, plugin.rule);
Expand Down Expand Up @@ -169,7 +170,7 @@ void timedRuleMissMustNotBeCached(final String operator) {

clock.set(predicateFalse(operator, boundary));
execute(false);
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, "/x"));
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, "selector", "/x"));
assertNull(plugin.rule);

clock.set(predicateTrue(operator, boundary));
Expand All @@ -196,7 +197,7 @@ void pathOnlyRuleMissStillCaches() {

execute(false);

RuleData cached = MatchDataCache.getInstance().obtainRuleData(PLUGIN, "/x");
RuleData cached = MatchDataCache.getInstance().obtainRuleData(PLUGIN, "selector", "/x");
assertNotNull(cached);
assertNull(cached.getId());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ void genericRuleMustNotShadowDynamicCompetitor(final String paramType) {
assertSame(generic, plugin.rule);
execute(true);
assertSame(special, plugin.rule);
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, "/x"));
assertNull(MatchDataCache.getInstance().obtainRuleData(PLUGIN, "selector", "/x"));
MatchDataCache.getInstance().cleanRuleDataData();
execute(true);
assertSame(special, plugin.rule);
Expand Down Expand Up @@ -146,7 +146,7 @@ void pathOnlyCandidatesStillCacheWithDisabledDynamicCompetitors(final boolean in
}
execute(false);
assertSame(generic, MatchDataCache.getInstance().obtainSelectorData(PLUGIN, "/x"));
assertSame(genericRule, MatchDataCache.getInstance().obtainRuleData(PLUGIN, "/x"));
assertSame(genericRule, MatchDataCache.getInstance().obtainRuleData(PLUGIN, generic.getId(), "/x"));
execute(true);
assertSame(generic, plugin.selector);
assertSame(genericRule, plugin.rule);
Expand Down
Loading
Loading