Skip to content

Commit

Permalink
Ftr: Implement condition routing basic functions and complete related…
Browse files Browse the repository at this point in the history
… tests (#2299)
  • Loading branch information
FinalT authored Apr 18, 2023
1 parent 0ea6075 commit 4b13d2b
Show file tree
Hide file tree
Showing 12 changed files with 1,421 additions and 8 deletions.
77 changes: 77 additions & 0 deletions cluster/router/condition/matcher/argument.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* 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 matcher

import (
"fmt"
"regexp"
"strconv"
"strings"
)

import (
"github.com/dubbogo/gost/log/logger"
)

import (
"dubbo.apache.org/dubbo-go/v3/common"
"dubbo.apache.org/dubbo-go/v3/protocol"
)

var (
argumentsPattern = regexp.MustCompile("arguments\\[([0-9]+)\\]")
notFoundArgumentValue = "dubbo internal not found argument condition value"
)

// ArgumentConditionMatcher 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'.
type ArgumentConditionMatcher struct {
BaseConditionMatcher
}

func NewArgumentConditionMatcher(key string) *ArgumentConditionMatcher {
return &ArgumentConditionMatcher{
*NewBaseConditionMatcher(key),
}
}

func (a *ArgumentConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
// split the rule
expressArray := strings.Split(a.key, "\\.")
argumentExpress := expressArray[0]
matcher := argumentsPattern.FindStringSubmatch(argumentExpress)
if len(matcher) == 0 {
logger.Warn(notFoundArgumentValue)
return ""
}

// extract the argument index
index, err := strconv.Atoi(matcher[1])
if err != nil {
logger.Warn(notFoundArgumentValue)
return ""
}

if index < 0 || index > len(invocation.Arguments()) {
logger.Warn(notFoundArgumentValue)
return ""
}
return fmt.Sprint(invocation.Arguments()[index])
}
159 changes: 159 additions & 0 deletions cluster/router/condition/matcher/base.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
* 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 matcher

import (
"sort"
"sync"
)

import (
"github.com/dubbogo/gost/log/logger"
)

import (
"dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern_value"
"dubbo.apache.org/dubbo-go/v3/common"
"dubbo.apache.org/dubbo-go/v3/common/constant"
"dubbo.apache.org/dubbo-go/v3/protocol"
)

var (
valueMatchers = make([]pattern_value.ValuePattern, 0, 8)

once sync.Once
)

// BaseConditionMatcher records the match and mismatch patterns of this matcher while at the same time
// provides the common match logics.
type BaseConditionMatcher struct {
key string
matches map[string]struct{}
misMatches map[string]struct{}
}

func NewBaseConditionMatcher(key string) *BaseConditionMatcher {
return &BaseConditionMatcher{
key: key,
matches: map[string]struct{}{},
misMatches: map[string]struct{}{},
}
}

// GetValue returns a value from different places of the request context.
func (b *BaseConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
return ""
}

// IsMatch indicates whether this matcher matches the patterns with request context.
func (b *BaseConditionMatcher) IsMatch(value string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
if value == "" {
// if key does not present in whichever of url, invocation or attachment based on the matcher type, then return false.
return false
}

if len(b.matches) != 0 && len(b.misMatches) == 0 {
return b.patternMatches(value, param, invocation, isWhenCondition)
}

if len(b.misMatches) != 0 && len(b.matches) == 0 {
return b.patternMisMatches(value, param, invocation, isWhenCondition)
}

if len(b.matches) != 0 && len(b.misMatches) != 0 {
// when both mismatches and matches contain the same value, then using mismatches first
return b.patternMatches(value, param, invocation, isWhenCondition) && b.patternMisMatches(value, param, invocation, isWhenCondition)
}
return false
}

// GetMatches returns matches.
func (b *BaseConditionMatcher) GetMatches() map[string]struct{} {
return b.matches
}

// GetMismatches returns misMatches.
func (b *BaseConditionMatcher) GetMismatches() map[string]struct{} {
return b.misMatches
}

func (b *BaseConditionMatcher) patternMatches(value string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
for match := range b.matches {
if doPatternMatch(match, value, param, invocation, isWhenCondition) {
return true
}
}
return false
}

func (b *BaseConditionMatcher) patternMisMatches(value string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
for mismatch := range b.misMatches {
if doPatternMatch(mismatch, value, param, invocation, isWhenCondition) {
return false
}
}
return true
}

func doPatternMatch(pattern string, value string, url *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
once.Do(initValueMatchers)
for _, valueMatcher := range valueMatchers {
if valueMatcher.ShouldMatch(pattern) {
return valueMatcher.Match(pattern, value, url, invocation, isWhenCondition)
}
}
// If no value matcher is available, will force to use wildcard value matcher
logger.Error("Executing condition rule value match expression error, will force to use wildcard value matcher")

valuePattern := pattern_value.GetValuePattern("wildcard")
return valuePattern.Match(pattern, value, url, invocation, isWhenCondition)
}

// GetSampleValueFromURL returns the value of the conditionKey in the URL
func GetSampleValueFromURL(conditionKey string, sample map[string]string, param *common.URL, invocation protocol.Invocation) string {
var sampleValue string
// get real invoked method name from invocation
if invocation != nil && (constant.MethodKey == conditionKey || constant.MethodsKey == conditionKey) {
sampleValue = invocation.MethodName()
} else {
sampleValue = sample[conditionKey]
}
return sampleValue
}

func Match(condition Matcher, sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
return condition.IsMatch(condition.GetValue(sample, param, invocation), param, invocation, isWhenCondition)
}

func initValueMatchers() {
valuePatterns := pattern_value.GetValuePatterns()
for _, valuePattern := range valuePatterns {
valueMatchers = append(valueMatchers, valuePattern())
}
sortValuePattern(valueMatchers)
}

func sortValuePattern(valuePatterns []pattern_value.ValuePattern) {
sort.Stable(byPriority(valuePatterns))
}

type byPriority []pattern_value.ValuePattern

func (a byPriority) Len() int { return len(a) }
func (a byPriority) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byPriority) Less(i, j int) bool { return a[i].Priority() < a[j].Priority() }
40 changes: 40 additions & 0 deletions cluster/router/condition/matcher/extension.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* 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 matcher

var (
matchers = make(map[string]func() ConditionMatcherFactory)
)

// SetMatcherFactory sets create matcherFactory function with @name
func SetMatcherFactory(name string, fun func() ConditionMatcherFactory) {
matchers[name] = fun
}

// GetMatcherFactory gets create matcherFactory function by name
func GetMatcherFactory(name string) ConditionMatcherFactory {
if matchers[name] == nil {
panic("matcher_factory for " + name + " is not existing, make sure you have imported the package.")
}
return matchers[name]()
}

// GetMatcherFactories gets all create matcherFactory function
func GetMatcherFactories() map[string]func() ConditionMatcherFactory {
return matchers
}
78 changes: 78 additions & 0 deletions cluster/router/condition/matcher/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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 matcher

import (
"math"
"strings"
)

import (
"dubbo.apache.org/dubbo-go/v3/common/constant"
)

func init() {
SetMatcherFactory("argument", NewArgumentMatcherFactory)
SetMatcherFactory("param", NewParamMatcherFactory)
}

// ArgumentMatcherFactory matcher factory
type ArgumentMatcherFactory struct {
}

// NewArgumentMatcherFactory constructs a new argument.ArgumentMatcherFactory
func NewArgumentMatcherFactory() ConditionMatcherFactory {
return &ArgumentMatcherFactory{}
}

func (a *ArgumentMatcherFactory) ShouldMatch(key string) bool {
return strings.HasPrefix(key, constant.Arguments)
}

// NewMatcher constructs a new matcher
func (a *ArgumentMatcherFactory) NewMatcher(key string) Matcher {
return NewArgumentConditionMatcher(key)
}

func (a *ArgumentMatcherFactory) Priority() int64 {
return 300
}

// ParamMatcherFactory matcher factory
type ParamMatcherFactory struct {
}

// NewParamMatcherFactory constructs a new paramMatcherFactory
func NewParamMatcherFactory() ConditionMatcherFactory {
return &ParamMatcherFactory{}
}

func (p *ParamMatcherFactory) ShouldMatch(key string) bool {
return true
}

// NewMatcher constructs a new matcher
func (p *ParamMatcherFactory) NewMatcher(key string) Matcher {
return NewParamConditionMatcher(key)
}

// Priority make sure this is the last matcher being executed.
// This instance will be loaded separately to ensure it always gets executed as the last matcher.
func (p *ParamMatcherFactory) Priority() int64 {
return math.MaxInt64
}
Loading

0 comments on commit 4b13d2b

Please sign in to comment.