You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@dubbo.apache.org by "justxuewei (via GitHub)" <gi...@apache.org> on 2023/04/09 10:13:45 UTC
[GitHub] [dubbo-go] justxuewei commented on a diff in pull request #2276: Ftr: Implement condition routing
justxuewei commented on code in PR #2276:
URL: https://github.com/apache/dubbo-go/pull/2276#discussion_r1152886822
##########
cluster/router/condition/matcher/argument/matcher.go:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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 argument
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/base"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+var (
+ ArgumentsPattern = regexp.MustCompile("arguments\\[([0-9]+)\\]")
+)
+
+/*
+ * 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 ConditionMatcher struct {
+ base.ConditionMatcher
+}
+
+func NewConditionMatcher(key string) *ConditionMatcher {
+ valuePatterns := extension.GetValuePatterns()
+ valueMatchers := make([]pattern.ValuePattern, 0, len(valuePatterns))
+ for _, valuePattern := range valuePatterns {
+ valueMatchers = append(valueMatchers, valuePattern())
+ }
+
+ base.SortValuePattern(valueMatchers)
+
+ conditionMatcher := &ConditionMatcher{
+ base.ConditionMatcher{
+ Key: key,
+ Matches: map[string]struct{}{},
+ Mismatches: map[string]struct{}{},
+ ValueMatchers: valueMatchers,
+ },
+ }
+
+ conditionMatcher.Matcher = conditionMatcher
+ return conditionMatcher
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
Review Comment:
Why does here return a string instead of `(string, error)`?
##########
cluster/router/condition/route.go:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 condition
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+
+ "github.com/pkg/errors"
+
+ "gopkg.in/yaml.v2"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ conf "dubbo.apache.org/dubbo-go/v3/common/config"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "dubbo.apache.org/dubbo-go/v3/config_center"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/remoting"
+)
+
+var (
+ RoutePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+)
+
+type ConditionDynamicRouter struct {
+ ruleKey string
+ conditionRouters []*ConditionStateRouter
+ routerConfig *config.RouterConfig
+}
+
+func NewConditionDynamicRouter() (*ConditionDynamicRouter, error) {
+ return &ConditionDynamicRouter{}, nil
+}
+
+func (c *ConditionDynamicRouter) Route(invokers []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker {
+ if len(invokers) == 0 || len(c.conditionRouters) == 0 {
+ return invokers
+ }
+ for _, router := range c.conditionRouters {
+ invokers = router.Route(invokers, url, invocation)
+ }
+ return invokers
+}
+
+func (c *ConditionDynamicRouter) URL() *common.URL {
+ return nil
+}
+
+func (c *ConditionDynamicRouter) Priority() int64 {
+ return 0
+}
+
+func (c *ConditionDynamicRouter) Notify(invokers []protocol.Invoker) {
+ if len(invokers) == 0 {
+ return
+ }
+ url := invokers[0].GetURL()
+ if url == nil {
+ logger.Error("url is empty")
Review Comment:
```suggestion
logger.Error("Failed to notify a dynamically condition rule, because url is empty")
```
##########
cluster/router/condition/router_test.go:
##########
@@ -0,0 +1,701 @@
+/*
+ * 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 condition
+
+import (
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/protocol/invocation"
+)
+
+const (
+ LocalHost = "127.0.0.1"
+)
+
+func TestRoute_matchWhen(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ whenConsumerUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ consumerUrl *common.URL
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: " => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: " => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 1.2.3.4 => ",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 1.2.3.4 => ",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ resVal := router.matchWhen(data.consumerUrl, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_matchFilter(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
Review Comment:
```suggestion
consumerURL, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
```
##########
cluster/router/condition/router_test.go:
##########
@@ -0,0 +1,701 @@
+/*
+ * 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 condition
+
+import (
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/protocol/invocation"
+)
+
+const (
+ LocalHost = "127.0.0.1"
+)
+
+func TestRoute_matchWhen(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ whenConsumerUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ consumerUrl *common.URL
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: " => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: " => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 1.2.3.4 => ",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 1.2.3.4 => ",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ resVal := router.matchWhen(data.consumerUrl, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_matchFilter(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ comsumerUrl *common.URL
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+
+ wantVal: 2,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " serialization = fastjson",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " serialization = fastjson",
+
+ wantVal: 1,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filteredInvokers := router.Route(invokerList, data.comsumerUrl, rpcInvocation)
+ resVal := len(filteredInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_methodRoute(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ testData := []struct {
+ name string
+ consumerUrl string
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: "More than one methods, mismatch",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Exactly one method, match",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Method routing and Other condition routing can work together",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ consumer, _ := common.NewURL(data.consumerUrl)
+ resVal := router.matchWhen(consumer, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_return(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ urls []string
+ rule string
+
+ wantUrls []string
+ wantVal int
+ }{
+ {
+ name: "ReturnFalse",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => false",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnEmpty",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => ",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnAll",
+ urls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 3,
+ },
+ {
+ name: "HostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "EmptyHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "FalseHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "true => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "PlaceHolder",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = $host",
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ invokers := make([]protocol.Invoker, 0, len(data.urls))
+ for _, urlStr := range data.urls {
+ url, _ := common.NewURL(urlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ invokers = append(invokers, invoker)
+ }
+
+ wantInvokers := make([]protocol.Invoker, 0, len(data.wantUrls))
+ for _, wantUrlStr := range data.wantUrls {
+ url, _ := common.NewURL(wantUrlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ wantInvokers = append(wantInvokers, invoker)
+ }
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filterInvokers := router.Route(invokers, consumerUrl, rpcInvocation)
+ resVal := len(filterInvokers)
+
+ assert.Equal(t, data.wantVal, resVal)
+ assert.Equal(t, wantInvokers, filterInvokers)
+ })
+ }
+}
+
+func TestRoute_arguments(t *testing.T) {
+
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ argument interface{}
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "Empty arguments",
+ argument: nil,
+ rule: "arguments[0] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 3,
+ },
+ {
+ name: "String arguments",
+ argument: "a",
+ rule: "arguments[0] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 0,
+ },
+ {
+ name: "Int arguments",
+ argument: 1,
+ rule: "arguments[0] = 1 " + " => " + " host = 127.0.0.1",
+
+ wantVal: 2,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ arguments := make([]interface{}, 0, 1)
+ arguments = append(arguments, data.argument)
+
+ rpcInvocation := invocation.NewRPCInvocation("getBar", arguments, nil)
+
+ filterInvokers := router.Route(invokerList, consumerUrl, rpcInvocation)
+ resVal := len(filterInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+
+ })
+ }
+}
+
+func TestRoute_attachments(t *testing.T) {
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ attachmentKey string
+ attachmentValue string
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "Empty attachments",
+ attachmentKey: "",
+ attachmentValue: "",
+ rule: "attachments[foo] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 3,
+ },
+ {
+ name: "Yes attachments and no host",
+ attachmentKey: "foo",
+ attachmentValue: "a",
+ rule: "attachments[foo] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 0,
+ },
+ {
+ name: "No attachments and no host",
+ attachmentKey: "foo",
+ attachmentValue: "a",
+ rule: "attachments = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 3,
+ },
+ {
+ name: "Yes attachments and region",
+ attachmentKey: "foo",
+ attachmentValue: "a",
+ rule: "attachments[foo] = a " + " => " + " region = hangzhou",
+
+ wantVal: 1,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getBar", nil, nil)
+ rpcInvocation.SetAttachment(data.attachmentKey, data.attachmentValue)
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filterInvokers := router.Route(invokerList, consumerUrl, rpcInvocation)
+
+ resVal := len(filterInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_range_pattern(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
Review Comment:
```suggestion
consumerURL, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
```
##########
cluster/router/condition/matcher/pattern/value_pattern.go:
##########
@@ -0,0 +1,33 @@
+/*
+ * 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 pattern
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ValuePattern interface {
+ //ShouldMatch return weather the input pattern of a specific form, for example, range pattern '1~100', wildcard pattern 'hello*', etc.
+ ShouldMatch(pattern string) bool
+ //Match is the pattern matches with the request context
Review Comment:
```suggestion
// Match indicates whether a pattern is matched with the request context
```
##########
cluster/router/condition/route.go:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 condition
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+
+ "github.com/pkg/errors"
+
+ "gopkg.in/yaml.v2"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ conf "dubbo.apache.org/dubbo-go/v3/common/config"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "dubbo.apache.org/dubbo-go/v3/config_center"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/remoting"
+)
+
+var (
+ RoutePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+)
+
+type ConditionDynamicRouter struct {
+ ruleKey string
+ conditionRouters []*ConditionStateRouter
+ routerConfig *config.RouterConfig
+}
+
+func NewConditionDynamicRouter() (*ConditionDynamicRouter, error) {
Review Comment:
Using `*ConditionDynamicRouter` as returned value is enough for this case.
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) GetSampleValueFromUrl(conditionKey string, sample map[string]string, param *common.URL, invocation protocol.Invocation) string {
Review Comment:
```suggestion
func (c *ConditionMatcher) GetSampleValueFromURL(conditionKey string, sample map[string]string, param *common.URL, invocation protocol.Invocation) string {
```
##########
cluster/router/condition/factory.go:
##########
@@ -0,0 +1,42 @@
+/*
+ * 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 condition
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+)
+
+func init() {
+ extension.SetRouterFactory(constant.ConditionRouterFactoryKey, NewConditionRouterFactory)
+}
+
+// RouteFactory router factory
+type RouteFactory struct{}
+
+// NewConditionRouterFactory constructs a new PriorityRouterFactory
+func NewConditionRouterFactory() router.PriorityRouterFactory {
+ return &RouteFactory{}
+}
+
+// NewPriorityRouter construct a new ConditionStateRouter
+func (f *RouteFactory) NewPriorityRouter() (router.PriorityRouter, error) {
+ //TODO Modify url
Review Comment:
```suggestion
// TODO Modify url
```
##########
cluster/router/condition/route.go:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 condition
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+
+ "github.com/pkg/errors"
+
+ "gopkg.in/yaml.v2"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ conf "dubbo.apache.org/dubbo-go/v3/common/config"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "dubbo.apache.org/dubbo-go/v3/config_center"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/remoting"
+)
+
+var (
+ RoutePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+)
+
+type ConditionDynamicRouter struct {
+ ruleKey string
+ conditionRouters []*ConditionStateRouter
+ routerConfig *config.RouterConfig
+}
+
+func NewConditionDynamicRouter() (*ConditionDynamicRouter, error) {
+ return &ConditionDynamicRouter{}, nil
+}
+
+func (c *ConditionDynamicRouter) Route(invokers []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker {
+ if len(invokers) == 0 || len(c.conditionRouters) == 0 {
+ return invokers
+ }
+ for _, router := range c.conditionRouters {
+ invokers = router.Route(invokers, url, invocation)
+ }
+ return invokers
+}
+
+func (c *ConditionDynamicRouter) URL() *common.URL {
+ return nil
+}
+
+func (c *ConditionDynamicRouter) Priority() int64 {
+ return 0
+}
+
+func (c *ConditionDynamicRouter) Notify(invokers []protocol.Invoker) {
+ if len(invokers) == 0 {
+ return
+ }
+ url := invokers[0].GetURL()
+ if url == nil {
+ logger.Error("url is empty")
+ return
+ }
+ dynamicConfiguration := conf.GetEnvInstance().GetDynamicConfiguration()
+ if dynamicConfiguration == nil {
+ logger.Warnf("config center does not start, please check if the configuration center has been properly configured in dubbogo.yml")
+ return
+ }
+ key := url.Service() + ":" + url.GetParam("version", "") + ":" + url.GetParam("group", "") + constant.ConditionRouterRuleSuffix
+ dynamicConfiguration.AddListener(key, c)
+ value, err := dynamicConfiguration.GetRule(key)
+ if err != nil {
+ logger.Errorf("query router rule fail,key=%s,err=%v", key, err)
+ return
+ }
+ c.Process(&config_center.ConfigChangeEvent{Key: key, Value: value, ConfigType: remoting.EventTypeAdd})
+}
+
+func (c *ConditionDynamicRouter) Process(event *config_center.ConfigChangeEvent) {
+ if event.ConfigType == remoting.EventTypeDel {
+ c.routerConfig = nil
+ c.conditionRouters = make([]*ConditionStateRouter, 0)
+ } else {
+ routerConfig, err := parseRoute(event.Value.(string))
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ c.routerConfig = routerConfig
+ if c.routerConfig != nil {
+ conditionRouters := make([]*ConditionStateRouter, 0, len(c.routerConfig.Conditions))
+ for _, conditionRule := range c.routerConfig.Conditions {
+ url, err := common.NewURL("condition://")
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ url.AddParam(constant.RuleKey, conditionRule)
+ url.AddParam(constant.ForceKey, strconv.FormatBool(c.routerConfig.Force))
+ url.AddParam(constant.EnabledKey, strconv.FormatBool(c.routerConfig.Enabled))
+ conditionRoute, err := NewConditionStateRouter(url)
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ conditionRouters = append(conditionRouters, conditionRoute)
+ }
+ c.conditionRouters = conditionRouters
+ }
+ }
+}
+
+type ConditionStateRouter struct {
+ enable bool
+ force bool
+ url *common.URL
+ whenCondition map[string]matcher.ConditionMatcher
+ thenCondition map[string]matcher.ConditionMatcher
+ matcherFactories []matcher.ConditionMatcherFactory
+}
+
+func NewConditionStateRouter(url *common.URL) (*ConditionStateRouter, error) {
+
+ matcherFactories := extension.GetMatcherFactories()
+ if len(matcherFactories) == 0 {
+ return nil, errors.Errorf("No ConditionMatcherFactory exits , create one please")
Review Comment:
```suggestion
return nil, errors.Errorf("No ConditionMatcherFactory exists")
```
##########
cluster/router/condition/factory.go:
##########
@@ -0,0 +1,42 @@
+/*
+ * 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 condition
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+)
+
+func init() {
+ extension.SetRouterFactory(constant.ConditionRouterFactoryKey, NewConditionRouterFactory)
+}
+
+// RouteFactory router factory
+type RouteFactory struct{}
+
+// NewConditionRouterFactory constructs a new PriorityRouterFactory
+func NewConditionRouterFactory() router.PriorityRouterFactory {
+ return &RouteFactory{}
+}
+
+// NewPriorityRouter construct a new ConditionStateRouter
Review Comment:
```suggestion
// NewPriorityRouter constructs a new ConditionStateRouter
```
##########
cluster/router/condition/route.go:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 condition
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+
+ "github.com/pkg/errors"
+
+ "gopkg.in/yaml.v2"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ conf "dubbo.apache.org/dubbo-go/v3/common/config"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "dubbo.apache.org/dubbo-go/v3/config_center"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/remoting"
+)
+
+var (
+ RoutePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+)
+
+type ConditionDynamicRouter struct {
+ ruleKey string
+ conditionRouters []*ConditionStateRouter
+ routerConfig *config.RouterConfig
+}
+
+func NewConditionDynamicRouter() (*ConditionDynamicRouter, error) {
+ return &ConditionDynamicRouter{}, nil
+}
+
+func (c *ConditionDynamicRouter) Route(invokers []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker {
+ if len(invokers) == 0 || len(c.conditionRouters) == 0 {
+ return invokers
+ }
+ for _, router := range c.conditionRouters {
+ invokers = router.Route(invokers, url, invocation)
+ }
+ return invokers
+}
+
+func (c *ConditionDynamicRouter) URL() *common.URL {
+ return nil
+}
+
+func (c *ConditionDynamicRouter) Priority() int64 {
+ return 0
+}
+
+func (c *ConditionDynamicRouter) Notify(invokers []protocol.Invoker) {
+ if len(invokers) == 0 {
+ return
+ }
+ url := invokers[0].GetURL()
+ if url == nil {
+ logger.Error("url is empty")
+ return
+ }
+ dynamicConfiguration := conf.GetEnvInstance().GetDynamicConfiguration()
+ if dynamicConfiguration == nil {
+ logger.Warnf("config center does not start, please check if the configuration center has been properly configured in dubbogo.yml")
+ return
+ }
+ key := url.Service() + ":" + url.GetParam("version", "") + ":" + url.GetParam("group", "") + constant.ConditionRouterRuleSuffix
+ dynamicConfiguration.AddListener(key, c)
+ value, err := dynamicConfiguration.GetRule(key)
+ if err != nil {
+ logger.Errorf("query router rule fail,key=%s,err=%v", key, err)
Review Comment:
```suggestion
logger.Errorf("Failed to query condition rule, key=%s, err=%v", key, err)
```
##########
cluster/router/condition/router_test.go:
##########
@@ -0,0 +1,701 @@
+/*
+ * 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 condition
+
+import (
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/protocol/invocation"
+)
+
+const (
+ LocalHost = "127.0.0.1"
+)
+
+func TestRoute_matchWhen(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ whenConsumerUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ consumerUrl *common.URL
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: " => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: " => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 1.2.3.4 => ",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 1.2.3.4 => ",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ resVal := router.matchWhen(data.consumerUrl, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_matchFilter(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ comsumerUrl *common.URL
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+
+ wantVal: 2,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " serialization = fastjson",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " serialization = fastjson",
+
+ wantVal: 1,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filteredInvokers := router.Route(invokerList, data.comsumerUrl, rpcInvocation)
+ resVal := len(filteredInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_methodRoute(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ testData := []struct {
+ name string
+ consumerUrl string
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: "More than one methods, mismatch",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Exactly one method, match",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Method routing and Other condition routing can work together",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ consumer, _ := common.NewURL(data.consumerUrl)
+ resVal := router.matchWhen(consumer, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_return(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
Review Comment:
```suggestion
consumerURL, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
```
##########
cluster/router/condition/route.go:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 condition
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+
+ "github.com/pkg/errors"
+
+ "gopkg.in/yaml.v2"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ conf "dubbo.apache.org/dubbo-go/v3/common/config"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "dubbo.apache.org/dubbo-go/v3/config_center"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/remoting"
+)
+
+var (
+ RoutePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+)
+
+type ConditionDynamicRouter struct {
+ ruleKey string
+ conditionRouters []*ConditionStateRouter
+ routerConfig *config.RouterConfig
+}
+
+func NewConditionDynamicRouter() (*ConditionDynamicRouter, error) {
+ return &ConditionDynamicRouter{}, nil
+}
+
+func (c *ConditionDynamicRouter) Route(invokers []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker {
+ if len(invokers) == 0 || len(c.conditionRouters) == 0 {
+ return invokers
+ }
+ for _, router := range c.conditionRouters {
+ invokers = router.Route(invokers, url, invocation)
+ }
+ return invokers
+}
+
+func (c *ConditionDynamicRouter) URL() *common.URL {
+ return nil
+}
+
+func (c *ConditionDynamicRouter) Priority() int64 {
+ return 0
+}
+
+func (c *ConditionDynamicRouter) Notify(invokers []protocol.Invoker) {
+ if len(invokers) == 0 {
+ return
+ }
+ url := invokers[0].GetURL()
+ if url == nil {
+ logger.Error("url is empty")
+ return
+ }
+ dynamicConfiguration := conf.GetEnvInstance().GetDynamicConfiguration()
+ if dynamicConfiguration == nil {
+ logger.Warnf("config center does not start, please check if the configuration center has been properly configured in dubbogo.yml")
+ return
+ }
+ key := url.Service() + ":" + url.GetParam("version", "") + ":" + url.GetParam("group", "") + constant.ConditionRouterRuleSuffix
+ dynamicConfiguration.AddListener(key, c)
+ value, err := dynamicConfiguration.GetRule(key)
+ if err != nil {
+ logger.Errorf("query router rule fail,key=%s,err=%v", key, err)
+ return
+ }
+ c.Process(&config_center.ConfigChangeEvent{Key: key, Value: value, ConfigType: remoting.EventTypeAdd})
+}
+
+func (c *ConditionDynamicRouter) Process(event *config_center.ConfigChangeEvent) {
+ if event.ConfigType == remoting.EventTypeDel {
+ c.routerConfig = nil
+ c.conditionRouters = make([]*ConditionStateRouter, 0)
+ } else {
+ routerConfig, err := parseRoute(event.Value.(string))
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ c.routerConfig = routerConfig
+ if c.routerConfig != nil {
+ conditionRouters := make([]*ConditionStateRouter, 0, len(c.routerConfig.Conditions))
+ for _, conditionRule := range c.routerConfig.Conditions {
+ url, err := common.NewURL("condition://")
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ url.AddParam(constant.RuleKey, conditionRule)
+ url.AddParam(constant.ForceKey, strconv.FormatBool(c.routerConfig.Force))
+ url.AddParam(constant.EnabledKey, strconv.FormatBool(c.routerConfig.Enabled))
+ conditionRoute, err := NewConditionStateRouter(url)
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ conditionRouters = append(conditionRouters, conditionRoute)
+ }
+ c.conditionRouters = conditionRouters
+ }
+ }
+}
+
+type ConditionStateRouter struct {
+ enable bool
+ force bool
+ url *common.URL
+ whenCondition map[string]matcher.ConditionMatcher
+ thenCondition map[string]matcher.ConditionMatcher
+ matcherFactories []matcher.ConditionMatcherFactory
+}
+
+func NewConditionStateRouter(url *common.URL) (*ConditionStateRouter, error) {
+
+ matcherFactories := extension.GetMatcherFactories()
+ if len(matcherFactories) == 0 {
+ return nil, errors.Errorf("No ConditionMatcherFactory exits , create one please")
+ }
+ factories := make([]matcher.ConditionMatcherFactory, 0, len(matcherFactories))
+ for _, matcherFactory := range matcherFactories {
+ factories = append(factories, matcherFactory())
+ }
+ sortMatcherFactories(factories)
+
+ force := url.GetParamBool(constant.ForceKey, false)
+ enable := url.GetParamBool(constant.EnabledKey, true)
+ c := &ConditionStateRouter{
+ url: url,
+ force: force,
+ matcherFactories: factories,
+ enable: enable,
+ }
+
+ if enable {
+ rule := url.GetParam(constant.RuleKey, "")
+ if rule == "" || len(strings.Trim(rule, " ")) == 0 {
+ return nil, errors.Errorf("Illegal route rule!")
+ }
+ rule = strings.Replace(rule, "consumer.", "", -1)
+ rule = strings.Replace(rule, "privoder.", "", -1)
+ i := strings.Index(rule, "=>")
+ var whenRule string
+ var thenRule string
+ if i < 0 {
Review Comment:
Add some comments like:
```
// for the case of `{then rule}`
// for the case of `{when rule} => {then rule}`
```
##########
cluster/router/condition/router_test.go:
##########
@@ -0,0 +1,701 @@
+/*
+ * 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 condition
+
+import (
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/protocol/invocation"
+)
+
+const (
+ LocalHost = "127.0.0.1"
+)
+
+func TestRoute_matchWhen(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ whenConsumerUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ consumerUrl *common.URL
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: " => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: " => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 1.2.3.4 => ",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 1.2.3.4 => ",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ resVal := router.matchWhen(data.consumerUrl, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_matchFilter(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ comsumerUrl *common.URL
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+
+ wantVal: 2,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " serialization = fastjson",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " serialization = fastjson",
+
+ wantVal: 1,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filteredInvokers := router.Route(invokerList, data.comsumerUrl, rpcInvocation)
+ resVal := len(filteredInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_methodRoute(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ testData := []struct {
+ name string
+ consumerUrl string
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: "More than one methods, mismatch",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Exactly one method, match",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Method routing and Other condition routing can work together",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ consumer, _ := common.NewURL(data.consumerUrl)
+ resVal := router.matchWhen(consumer, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_return(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ urls []string
+ rule string
+
+ wantUrls []string
+ wantVal int
+ }{
+ {
+ name: "ReturnFalse",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => false",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnEmpty",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => ",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnAll",
+ urls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 3,
+ },
+ {
+ name: "HostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "EmptyHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "FalseHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "true => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "PlaceHolder",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = $host",
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ invokers := make([]protocol.Invoker, 0, len(data.urls))
+ for _, urlStr := range data.urls {
+ url, _ := common.NewURL(urlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ invokers = append(invokers, invoker)
+ }
+
+ wantInvokers := make([]protocol.Invoker, 0, len(data.wantUrls))
+ for _, wantUrlStr := range data.wantUrls {
+ url, _ := common.NewURL(wantUrlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ wantInvokers = append(wantInvokers, invoker)
+ }
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filterInvokers := router.Route(invokers, consumerUrl, rpcInvocation)
+ resVal := len(filterInvokers)
+
+ assert.Equal(t, data.wantVal, resVal)
+ assert.Equal(t, wantInvokers, filterInvokers)
+ })
+ }
+}
+
+func TestRoute_arguments(t *testing.T) {
+
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
Review Comment:
```suggestion
consumerURL, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
```
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
+ ShouldMatch(key string) bool
+ //NewMatcher return a matcher instance for the key.
+ NewMatcher(key string) ConditionMatcher
+ // Priority Return Priority in ConditionMatcherFactory
+ // 0 to ^int(0) is better
+ Priority() int64
Review Comment:
See `ValuePattern` interface.
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
+ ShouldMatch(key string) bool
+ //NewMatcher return a matcher instance for the key.
+ NewMatcher(key string) ConditionMatcher
+ // Priority Return Priority in ConditionMatcherFactory
+ // 0 to ^int(0) is better
+ Priority() int64
+}
+
+/*
+ConditionMatcher represents a specific match condition of a condition rule.
+The following condition rule 'foo=bar&arguments[0]=hello* => region=hangzhou' consists of three ConditionMatchers:
+1. param.ConditionMatcher represented by 'foo=bar'
+2. argument.ConditionMatcher represented by 'arguments[0]=hello*'
+3. param.ConditionMatcher represented by 'region=hangzhou'
+*/
+type ConditionMatcher interface {
+ // IsMatch return weather the patterns of this matcher matches with request context.
+ IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool
+ // GetMatches return Matches
+ // match patterns extracted from when condition
+ GetMatches() map[string]struct{}
+ // GetMismatches return Mismatches
+ // mismatch patterns extracted from then condition
+ GetMismatches() map[string]struct{}
+ // GetValue return value from different places of the request context, for example, url, attachment and invocation.
Review Comment:
```suggestion
// GetValue returns a value from different places of the request context, for example, url, attachment and invocation.
```
##########
cluster/router/condition/route.go:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 condition
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+
+ "github.com/pkg/errors"
+
+ "gopkg.in/yaml.v2"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ conf "dubbo.apache.org/dubbo-go/v3/common/config"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "dubbo.apache.org/dubbo-go/v3/config_center"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/remoting"
+)
+
+var (
+ RoutePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+)
+
+type ConditionDynamicRouter struct {
+ ruleKey string
+ conditionRouters []*ConditionStateRouter
+ routerConfig *config.RouterConfig
+}
+
+func NewConditionDynamicRouter() (*ConditionDynamicRouter, error) {
+ return &ConditionDynamicRouter{}, nil
+}
+
+func (c *ConditionDynamicRouter) Route(invokers []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker {
+ if len(invokers) == 0 || len(c.conditionRouters) == 0 {
+ return invokers
+ }
+ for _, router := range c.conditionRouters {
+ invokers = router.Route(invokers, url, invocation)
+ }
+ return invokers
+}
+
+func (c *ConditionDynamicRouter) URL() *common.URL {
+ return nil
+}
+
+func (c *ConditionDynamicRouter) Priority() int64 {
+ return 0
+}
+
+func (c *ConditionDynamicRouter) Notify(invokers []protocol.Invoker) {
+ if len(invokers) == 0 {
+ return
+ }
+ url := invokers[0].GetURL()
+ if url == nil {
+ logger.Error("url is empty")
+ return
+ }
+ dynamicConfiguration := conf.GetEnvInstance().GetDynamicConfiguration()
+ if dynamicConfiguration == nil {
+ logger.Warnf("config center does not start, please check if the configuration center has been properly configured in dubbogo.yml")
+ return
+ }
+ key := url.Service() + ":" + url.GetParam("version", "") + ":" + url.GetParam("group", "") + constant.ConditionRouterRuleSuffix
+ dynamicConfiguration.AddListener(key, c)
+ value, err := dynamicConfiguration.GetRule(key)
+ if err != nil {
+ logger.Errorf("query router rule fail,key=%s,err=%v", key, err)
+ return
+ }
+ c.Process(&config_center.ConfigChangeEvent{Key: key, Value: value, ConfigType: remoting.EventTypeAdd})
+}
+
+func (c *ConditionDynamicRouter) Process(event *config_center.ConfigChangeEvent) {
+ if event.ConfigType == remoting.EventTypeDel {
+ c.routerConfig = nil
+ c.conditionRouters = make([]*ConditionStateRouter, 0)
+ } else {
+ routerConfig, err := parseRoute(event.Value.(string))
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ c.routerConfig = routerConfig
+ if c.routerConfig != nil {
+ conditionRouters := make([]*ConditionStateRouter, 0, len(c.routerConfig.Conditions))
+ for _, conditionRule := range c.routerConfig.Conditions {
+ url, err := common.NewURL("condition://")
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ url.AddParam(constant.RuleKey, conditionRule)
+ url.AddParam(constant.ForceKey, strconv.FormatBool(c.routerConfig.Force))
+ url.AddParam(constant.EnabledKey, strconv.FormatBool(c.routerConfig.Enabled))
+ conditionRoute, err := NewConditionStateRouter(url)
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ conditionRouters = append(conditionRouters, conditionRoute)
+ }
+ c.conditionRouters = conditionRouters
+ }
+ }
+}
+
+type ConditionStateRouter struct {
+ enable bool
+ force bool
+ url *common.URL
+ whenCondition map[string]matcher.ConditionMatcher
+ thenCondition map[string]matcher.ConditionMatcher
+ matcherFactories []matcher.ConditionMatcherFactory
+}
+
+func NewConditionStateRouter(url *common.URL) (*ConditionStateRouter, error) {
+
+ matcherFactories := extension.GetMatcherFactories()
+ if len(matcherFactories) == 0 {
+ return nil, errors.Errorf("No ConditionMatcherFactory exits , create one please")
+ }
+ factories := make([]matcher.ConditionMatcherFactory, 0, len(matcherFactories))
+ for _, matcherFactory := range matcherFactories {
+ factories = append(factories, matcherFactory())
+ }
+ sortMatcherFactories(factories)
+
+ force := url.GetParamBool(constant.ForceKey, false)
+ enable := url.GetParamBool(constant.EnabledKey, true)
+ c := &ConditionStateRouter{
+ url: url,
+ force: force,
+ matcherFactories: factories,
+ enable: enable,
+ }
+
+ if enable {
+ rule := url.GetParam(constant.RuleKey, "")
+ if rule == "" || len(strings.Trim(rule, " ")) == 0 {
+ return nil, errors.Errorf("Illegal route rule!")
+ }
+ rule = strings.Replace(rule, "consumer.", "", -1)
+ rule = strings.Replace(rule, "privoder.", "", -1)
+ i := strings.Index(rule, "=>")
+ var whenRule string
+ var thenRule string
+ if i < 0 {
+ whenRule = ""
+ thenRule = strings.Trim(rule, " ")
+ } else {
+ whenRule = strings.Trim(rule[0:i], " ")
+ thenRule = strings.Trim(rule[i+2:], " ")
+ }
+ var when map[string]matcher.ConditionMatcher
+ var then map[string]matcher.ConditionMatcher
+ var err error
+ if whenRule == "" || whenRule == " " || whenRule == "true" {
+ when = make(map[string]matcher.ConditionMatcher)
+ } else {
+ when, err = c.parseRule(whenRule)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ if thenRule == "" || thenRule == " " || thenRule == "false" {
+ then = nil
+ } else {
+ then, err = c.parseRule(thenRule)
+ if err != nil {
+ return nil, err
+ }
+ }
+ // NOTE: It should be determined on the business level whether the `When condition` can be empty or not.
+ c.whenCondition = when
+ c.thenCondition = then
+ }
+ return c, nil
+}
+
+func (c *ConditionStateRouter) Route(invokers []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker {
+ if !c.enable {
+ return invokers
+ }
+
+ if len(invokers) == 0 {
+ return invokers
+ }
+
+ if !c.matchWhen(url, invocation) {
+ return invokers
+ }
+
+ if len(c.thenCondition) == 0 {
+ logger.Warn("condition state router thenCondition is empty")
+ return []protocol.Invoker{}
+ }
+
+ var result = make([]protocol.Invoker, len(invokers))
+ copy(result, invokers)
+ i := 0
+ for _, invoker := range result {
+ if c.matchThen(invoker.GetURL(), url) {
+ result[i] = invoker
+ i++
+ }
+ }
+ result = result[:i]
Review Comment:
Here is no need to assign the `result` again.
```
var result = []protocol.Invoker
for _, invoker := range result {
if c.matchThen(invoker.GetURL(), url) {
result = append(result, invoker)
}
}
```
##########
cluster/router/condition/router_test.go:
##########
@@ -0,0 +1,701 @@
+/*
+ * 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 condition
+
+import (
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/protocol/invocation"
+)
+
+const (
+ LocalHost = "127.0.0.1"
+)
+
+func TestRoute_matchWhen(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ whenConsumerUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
Review Comment:
```suggestion
whenConsumerURL, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
```
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
+ ShouldMatch(key string) bool
+ //NewMatcher return a matcher instance for the key.
+ NewMatcher(key string) ConditionMatcher
+ // Priority Return Priority in ConditionMatcherFactory
+ // 0 to ^int(0) is better
+ Priority() int64
+}
+
+/*
+ConditionMatcher represents a specific match condition of a condition rule.
+The following condition rule 'foo=bar&arguments[0]=hello* => region=hangzhou' consists of three ConditionMatchers:
+1. param.ConditionMatcher represented by 'foo=bar'
+2. argument.ConditionMatcher represented by 'arguments[0]=hello*'
+3. param.ConditionMatcher represented by 'region=hangzhou'
+*/
+type ConditionMatcher interface {
+ // IsMatch return weather the patterns of this matcher matches with request context.
+ IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool
+ // GetMatches return Matches
Review Comment:
```suggestion
// GetMatches returns Matches from when condition
```
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) 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 (c *ConditionMatcher) IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
+ value := c.Matcher.GetValue(sample, param, invocation)
+ 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(c.Matches) != 0 && len(c.Mismatches) == 0 {
+ for match, _ := range c.Matches {
Review Comment:
```suggestion
for match := range c.Matches {
```
##########
cluster/router/condition/route.go:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 condition
+
+import (
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+
+ "github.com/pkg/errors"
+
+ "gopkg.in/yaml.v2"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ conf "dubbo.apache.org/dubbo-go/v3/common/config"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "dubbo.apache.org/dubbo-go/v3/config_center"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/remoting"
+)
+
+var (
+ RoutePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+)
+
+type ConditionDynamicRouter struct {
+ ruleKey string
+ conditionRouters []*ConditionStateRouter
+ routerConfig *config.RouterConfig
+}
+
+func NewConditionDynamicRouter() (*ConditionDynamicRouter, error) {
+ return &ConditionDynamicRouter{}, nil
+}
+
+func (c *ConditionDynamicRouter) Route(invokers []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker {
+ if len(invokers) == 0 || len(c.conditionRouters) == 0 {
+ return invokers
+ }
+ for _, router := range c.conditionRouters {
+ invokers = router.Route(invokers, url, invocation)
+ }
+ return invokers
+}
+
+func (c *ConditionDynamicRouter) URL() *common.URL {
+ return nil
+}
+
+func (c *ConditionDynamicRouter) Priority() int64 {
+ return 0
+}
+
+func (c *ConditionDynamicRouter) Notify(invokers []protocol.Invoker) {
+ if len(invokers) == 0 {
+ return
+ }
+ url := invokers[0].GetURL()
+ if url == nil {
+ logger.Error("url is empty")
+ return
+ }
+ dynamicConfiguration := conf.GetEnvInstance().GetDynamicConfiguration()
+ if dynamicConfiguration == nil {
+ logger.Warnf("config center does not start, please check if the configuration center has been properly configured in dubbogo.yml")
+ return
+ }
+ key := url.Service() + ":" + url.GetParam("version", "") + ":" + url.GetParam("group", "") + constant.ConditionRouterRuleSuffix
+ dynamicConfiguration.AddListener(key, c)
+ value, err := dynamicConfiguration.GetRule(key)
+ if err != nil {
+ logger.Errorf("query router rule fail,key=%s,err=%v", key, err)
+ return
+ }
+ c.Process(&config_center.ConfigChangeEvent{Key: key, Value: value, ConfigType: remoting.EventTypeAdd})
+}
+
+func (c *ConditionDynamicRouter) Process(event *config_center.ConfigChangeEvent) {
+ if event.ConfigType == remoting.EventTypeDel {
+ c.routerConfig = nil
+ c.conditionRouters = make([]*ConditionStateRouter, 0)
+ } else {
+ routerConfig, err := parseRoute(event.Value.(string))
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
+ "and we will use the original condition rule configuration.", err)
+ return
+ }
+ c.routerConfig = routerConfig
+ if c.routerConfig != nil {
+ conditionRouters := make([]*ConditionStateRouter, 0, len(c.routerConfig.Conditions))
+ for _, conditionRule := range c.routerConfig.Conditions {
+ url, err := common.NewURL("condition://")
+ if err != nil {
+ logger.Warnf("[condition router]Parse new condition route config error, %+v "+
Review Comment:
```suggestion
logger.Warnf("[condition router]Build a new condition route config error, %+v "+
```
##########
cluster/router/condition/matcher/param/factory.go:
##########
@@ -0,0 +1,56 @@
+/*
+ * 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 param
+
+import (
+ "math"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+)
+
+func init() {
+ extension.SetMatcherFactory("param", NewParamMatcherFactory)
+}
+
+// MatcherFactory matcher factory
+type MatcherFactory struct {
+}
+
+// NewParamMatcherFactory constructs a new paramMatcherFactory
+func NewParamMatcherFactory() matcher.ConditionMatcherFactory {
+ return &MatcherFactory{}
+}
+
+func (m *MatcherFactory) ShouldMatch(key string) bool {
+ return true
+}
+
+// NewMatcher construct a new matcher
Review Comment:
```suggestion
// NewMatcher constructs a new matcher
```
##########
cluster/router/condition/router_test.go:
##########
@@ -0,0 +1,701 @@
+/*
+ * 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 condition
+
+import (
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/protocol/invocation"
+)
+
+const (
+ LocalHost = "127.0.0.1"
+)
+
+func TestRoute_matchWhen(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ whenConsumerUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ consumerUrl *common.URL
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: " => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: " => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 1.2.3.4 => ",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 1.2.3.4 => ",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ resVal := router.matchWhen(data.consumerUrl, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_matchFilter(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ comsumerUrl *common.URL
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+
+ wantVal: 2,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " serialization = fastjson",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " serialization = fastjson",
+
+ wantVal: 1,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filteredInvokers := router.Route(invokerList, data.comsumerUrl, rpcInvocation)
+ resVal := len(filteredInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_methodRoute(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ testData := []struct {
+ name string
+ consumerUrl string
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: "More than one methods, mismatch",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Exactly one method, match",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Method routing and Other condition routing can work together",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ consumer, _ := common.NewURL(data.consumerUrl)
+ resVal := router.matchWhen(consumer, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_return(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ urls []string
+ rule string
+
+ wantUrls []string
+ wantVal int
+ }{
+ {
+ name: "ReturnFalse",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => false",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnEmpty",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => ",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnAll",
+ urls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 3,
+ },
+ {
+ name: "HostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "EmptyHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "FalseHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "true => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "PlaceHolder",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = $host",
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ invokers := make([]protocol.Invoker, 0, len(data.urls))
+ for _, urlStr := range data.urls {
+ url, _ := common.NewURL(urlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ invokers = append(invokers, invoker)
+ }
+
+ wantInvokers := make([]protocol.Invoker, 0, len(data.wantUrls))
+ for _, wantUrlStr := range data.wantUrls {
+ url, _ := common.NewURL(wantUrlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ wantInvokers = append(wantInvokers, invoker)
+ }
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filterInvokers := router.Route(invokers, consumerUrl, rpcInvocation)
+ resVal := len(filterInvokers)
+
+ assert.Equal(t, data.wantVal, resVal)
+ assert.Equal(t, wantInvokers, filterInvokers)
+ })
+ }
+}
+
+func TestRoute_arguments(t *testing.T) {
+
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ argument interface{}
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "Empty arguments",
+ argument: nil,
+ rule: "arguments[0] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 3,
+ },
+ {
+ name: "String arguments",
+ argument: "a",
+ rule: "arguments[0] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 0,
+ },
+ {
+ name: "Int arguments",
+ argument: 1,
+ rule: "arguments[0] = 1 " + " => " + " host = 127.0.0.1",
+
+ wantVal: 2,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ arguments := make([]interface{}, 0, 1)
+ arguments = append(arguments, data.argument)
+
+ rpcInvocation := invocation.NewRPCInvocation("getBar", arguments, nil)
+
+ filterInvokers := router.Route(invokerList, consumerUrl, rpcInvocation)
+ resVal := len(filterInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+
+ })
+ }
+}
+
+func TestRoute_attachments(t *testing.T) {
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
Review Comment:
```suggestion
consumerURL, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
```
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
+ ShouldMatch(key string) bool
+ //NewMatcher return a matcher instance for the key.
+ NewMatcher(key string) ConditionMatcher
+ // Priority Return Priority in ConditionMatcherFactory
+ // 0 to ^int(0) is better
+ Priority() int64
+}
+
+/*
+ConditionMatcher represents a specific match condition of a condition rule.
+The following condition rule 'foo=bar&arguments[0]=hello* => region=hangzhou' consists of three ConditionMatchers:
+1. param.ConditionMatcher represented by 'foo=bar'
+2. argument.ConditionMatcher represented by 'arguments[0]=hello*'
+3. param.ConditionMatcher represented by 'region=hangzhou'
+*/
+type ConditionMatcher interface {
+ // IsMatch return weather the patterns of this matcher matches with request context.
+ IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool
+ // GetMatches return Matches
+ // match patterns extracted from when condition
+ GetMatches() map[string]struct{}
+ // GetMismatches return Mismatches
Review Comment:
See above
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) 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 (c *ConditionMatcher) IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
+ value := c.Matcher.GetValue(sample, param, invocation)
+ 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(c.Matches) != 0 && len(c.Mismatches) == 0 {
+ for match, _ := range c.Matches {
+ if c.DoPatternMatch(match, value, param, invocation, isWhenCondition) {
+ return true
+ }
+ }
+ return false
+ }
+
+ if len(c.Mismatches) != 0 && len(c.Matches) == 0 {
+ for mismatch, _ := range c.Mismatches {
+ if c.DoPatternMatch(mismatch, value, param, invocation, isWhenCondition) {
+ return false
+ }
+ }
+ return true
+ }
+
+ if len(c.Matches) != 0 && len(c.Mismatches) != 0 {
+ //when both mismatches and matches contain the same value, then using mismatches first
+ for mismatch, _ := range c.Mismatches {
+ if c.DoPatternMatch(mismatch, value, param, invocation, isWhenCondition) {
+ return false
+ }
+ }
+
+ for match, _ := range c.Matches {
Review Comment:
See above
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
Review Comment:
Why does here need a `Matcher`? I just checked all constructive functions of condition matchers have a same behavior:
```
conditionMatcher.Matcher = conditionMatcher
```
I think it is a self-reference.
##########
common/constant/key.go:
##########
@@ -297,12 +297,18 @@ const (
// Use for router module
const (
TagRouterRuleSuffix = ".tag-router"
- ConditionRouterRuleSuffix = ".condition-router" // Specify condition router suffix
- MeshRouteSuffix = ".MESHAPPRULE" // Specify mesh router suffix
- ForceUseTag = "dubbo.force.tag" // the tag in attachment
- Tagkey = "dubbo.tag" // key of tag
+ ConditionRouterRuleSuffix = ".condition-router" // Specify condition router suffix
+ MeshRouteSuffix = ".MESHAPPRULE" // Specify mesh router suffix
+ ForceUseTag = "dubbo.force.tag" // the tag in attachment
+ ForceUseCondition = "dubbo.force.condition"
+ Tagkey = "dubbo.tag" // key of tag
+ ConditionKey = "dubbo.condition"
AttachmentKey = DubboCtxKey("attachment") // key in context in invoker
TagRouterFactoryKey = "tag"
+ ConditionRouterFactoryKey = "condition"
+ ForceKey = "force"
+ ARGUMENTS = "arguments"
Review Comment:
```suggestion
Arguments = "arguments"
```
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) 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 (c *ConditionMatcher) IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
+ value := c.Matcher.GetValue(sample, param, invocation)
+ 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(c.Matches) != 0 && len(c.Mismatches) == 0 {
+ for match, _ := range c.Matches {
+ if c.DoPatternMatch(match, value, param, invocation, isWhenCondition) {
+ return true
+ }
+ }
+ return false
+ }
+
+ if len(c.Mismatches) != 0 && len(c.Matches) == 0 {
+ for mismatch, _ := range c.Mismatches {
Review Comment:
```suggestion
for mismatch := range c.Mismatches {
```
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) 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 (c *ConditionMatcher) IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
+ value := c.Matcher.GetValue(sample, param, invocation)
+ 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(c.Matches) != 0 && len(c.Mismatches) == 0 {
+ for match, _ := range c.Matches {
+ if c.DoPatternMatch(match, value, param, invocation, isWhenCondition) {
+ return true
+ }
+ }
+ return false
+ }
+
+ if len(c.Mismatches) != 0 && len(c.Matches) == 0 {
+ for mismatch, _ := range c.Mismatches {
+ if c.DoPatternMatch(mismatch, value, param, invocation, isWhenCondition) {
+ return false
+ }
+ }
+ return true
+ }
+
+ if len(c.Matches) != 0 && len(c.Mismatches) != 0 {
+ //when both mismatches and matches contain the same value, then using mismatches first
+ for mismatch, _ := range c.Mismatches {
+ if c.DoPatternMatch(mismatch, value, param, invocation, isWhenCondition) {
+ return false
+ }
+ }
+
+ for match, _ := range c.Matches {
+ if c.DoPatternMatch(match, value, param, invocation, isWhenCondition) {
+ return true
+ }
+ }
+ return false
+ }
+ return false
+}
+
+func (c *ConditionMatcher) GetMatches() map[string]struct{} {
+ return c.Matches
+}
+
+func (c *ConditionMatcher) GetMismatches() map[string]struct{} {
+ return c.Mismatches
+}
+
+func (c *ConditionMatcher) DoPatternMatch(pattern string, value string, url *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
+ for _, valueMatcher := range c.ValueMatchers {
+ if valueMatcher.ShouldMatch(pattern) {
+ return valueMatcher.Match(pattern, value, url, invocation, isWhenCondition)
+ }
+ }
+ // this should never happen.
+ logger.Error("Executing condition rule value match expression error.")
Review Comment:
Why do you say: "this should never happen"? Is this because the wildcard must do match once?
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) 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 (c *ConditionMatcher) IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
+ value := c.Matcher.GetValue(sample, param, invocation)
+ 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(c.Matches) != 0 && len(c.Mismatches) == 0 {
+ for match, _ := range c.Matches {
+ if c.DoPatternMatch(match, value, param, invocation, isWhenCondition) {
+ return true
+ }
+ }
+ return false
+ }
+
+ if len(c.Mismatches) != 0 && len(c.Matches) == 0 {
+ for mismatch, _ := range c.Mismatches {
+ if c.DoPatternMatch(mismatch, value, param, invocation, isWhenCondition) {
+ return false
+ }
+ }
+ return true
+ }
+
+ if len(c.Matches) != 0 && len(c.Mismatches) != 0 {
+ //when both mismatches and matches contain the same value, then using mismatches first
+ for mismatch, _ := range c.Mismatches {
Review Comment:
See above
##########
common/extension/router_condition_value_pattern.go:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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 extension
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+)
+
+var (
+ valuePatterns = make(map[string]func() pattern.ValuePattern)
+)
+
+// SetValuePattern sets create valuePattern function with @name
+func SetValuePattern(name string, fun func() pattern.ValuePattern) {
+ valuePatterns[name] = fun
+}
+
+// GetValuePattern gets create valuePattern function by name
+func GetValuePattern(name string) pattern.ValuePattern {
+ if valuePatterns[name] == nil {
+ panic("value_pattern for " + name + " is not existing, make sure you have import the package.")
Review Comment:
```suggestion
panic("value_pattern for " + name + " is not existing, make sure you have imported the package.")
```
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) 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 (c *ConditionMatcher) IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool {
+ value := c.Matcher.GetValue(sample, param, invocation)
+ 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(c.Matches) != 0 && len(c.Mismatches) == 0 {
+ for match, _ := range c.Matches {
+ if c.DoPatternMatch(match, value, param, invocation, isWhenCondition) {
+ return true
+ }
+ }
+ return false
+ }
+
+ if len(c.Mismatches) != 0 && len(c.Matches) == 0 {
+ for mismatch, _ := range c.Mismatches {
+ if c.DoPatternMatch(mismatch, value, param, invocation, isWhenCondition) {
+ return false
+ }
+ }
+ return true
+ }
+
+ if len(c.Matches) != 0 && len(c.Mismatches) != 0 {
+ //when both mismatches and matches contain the same value, then using mismatches first
Review Comment:
```suggestion
// when both mismatches and matches contain the same value, then using mismatches first
```
##########
common/extension/router_condition_matcher_factory.go:
##########
@@ -0,0 +1,41 @@
+/*
+ * 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 extension
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+)
+
+var (
+ matchers = make(map[string]func() matcher.ConditionMatcherFactory)
+)
+
+func SetMatcherFactory(name string, fun func() matcher.ConditionMatcherFactory) {
+ matchers[name] = fun
+}
+
+func GetMatcherFactory(name string) matcher.ConditionMatcherFactory {
+ if matchers[name] == nil {
+ panic("matcher_factory for " + name + " is not existing, make sure you have import the package.")
Review Comment:
```suggestion
panic("matcher_factory for " + name + " is not existing, make sure you have imported the package.")
```
##########
cluster/utils/url.go:
##########
@@ -0,0 +1,59 @@
+/*
+ * 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 utils
+
+import (
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+)
+
+func IsMatchGlobPattern(pattern string, value string, param *common.URL) bool {
Review Comment:
Add some unit tests for this method.
##########
common/constant/key.go:
##########
@@ -297,12 +297,18 @@ const (
// Use for router module
const (
TagRouterRuleSuffix = ".tag-router"
- ConditionRouterRuleSuffix = ".condition-router" // Specify condition router suffix
- MeshRouteSuffix = ".MESHAPPRULE" // Specify mesh router suffix
- ForceUseTag = "dubbo.force.tag" // the tag in attachment
- Tagkey = "dubbo.tag" // key of tag
+ ConditionRouterRuleSuffix = ".condition-router" // Specify condition router suffix
+ MeshRouteSuffix = ".MESHAPPRULE" // Specify mesh router suffix
+ ForceUseTag = "dubbo.force.tag" // the tag in attachment
+ ForceUseCondition = "dubbo.force.condition"
+ Tagkey = "dubbo.tag" // key of tag
+ ConditionKey = "dubbo.condition"
AttachmentKey = DubboCtxKey("attachment") // key in context in invoker
TagRouterFactoryKey = "tag"
+ ConditionRouterFactoryKey = "condition"
+ ForceKey = "force"
+ ARGUMENTS = "arguments"
+ ATTACHMENTS = "attachments"
Review Comment:
```suggestion
Attachments = "attachments"
```
##########
cluster/router/condition/matcher/argument/matcher.go:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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 argument
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/base"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+var (
+ ArgumentsPattern = regexp.MustCompile("arguments\\[([0-9]+)\\]")
+)
+
+/*
+ * 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 ConditionMatcher struct {
+ base.ConditionMatcher
+}
+
+func NewConditionMatcher(key string) *ConditionMatcher {
+ valuePatterns := extension.GetValuePatterns()
+ valueMatchers := make([]pattern.ValuePattern, 0, len(valuePatterns))
+ for _, valuePattern := range valuePatterns {
+ valueMatchers = append(valueMatchers, valuePattern())
+ }
+
+ base.SortValuePattern(valueMatchers)
+
+ conditionMatcher := &ConditionMatcher{
+ base.ConditionMatcher{
+ Key: key,
+ Matches: map[string]struct{}{},
+ Mismatches: map[string]struct{}{},
+ ValueMatchers: valueMatchers,
+ },
+ }
+
+ conditionMatcher.Matcher = conditionMatcher
+ return conditionMatcher
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ // split the rule
+ expressArray := strings.Split(c.Key, "\\.")
+ argumentExpress := expressArray[0]
+ matcher := ArgumentsPattern.FindStringSubmatch(argumentExpress)
+ if len(matcher) == 0 {
+ return "dubbo internal not found argument condition value"
+ }
+
+ //extract the argument index
+ index, err := strconv.Atoi(matcher[1])
+ if err != nil {
+ logger.Warn("Parse argument match condition failed,Invalid , will ignore., ")
Review Comment:
I don't know the meaning of this warning log.
##########
cluster/router/condition/matcher/pattern/value_pattern.go:
##########
@@ -0,0 +1,33 @@
+/*
+ * 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 pattern
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ValuePattern interface {
+ //ShouldMatch return weather the input pattern of a specific form, for example, range pattern '1~100', wildcard pattern 'hello*', etc.
+ ShouldMatch(pattern string) bool
+ //Match is the pattern matches with the request context
+ Match(pattern string, value string, url *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool
+ // Priority Return Priority in valuePattern
Review Comment:
```suggestion
// Priority returns a priority for this valuePattern
```
##########
cluster/router/condition/router_test.go:
##########
@@ -0,0 +1,701 @@
+/*
+ * 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 condition
+
+import (
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+ "dubbo.apache.org/dubbo-go/v3/protocol/invocation"
+)
+
+const (
+ LocalHost = "127.0.0.1"
+)
+
+func TestRoute_matchWhen(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ whenConsumerUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ consumerUrl *common.URL
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: " => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: " => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 1.2.3.4 => ",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 1.2.3.4 => ",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ {
+ name: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+ consumerUrl: whenConsumerUrl,
+ rule: "host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ resVal := router.matchWhen(data.consumerUrl, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_matchFilter(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ comsumerUrl *common.URL
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.* & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.3 & host != 10.20.3.3",
+
+ wantVal: 0,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4",
+
+ wantVal: 1,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " host != 10.20.3.3",
+
+ wantVal: 2,
+ },
+ {
+ name: "host = " + LocalHost + " => " + " serialization = fastjson",
+ comsumerUrl: consumerUrl,
+ rule: "host = " + LocalHost + " => " + " serialization = fastjson",
+
+ wantVal: 1,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filteredInvokers := router.Route(invokerList, data.comsumerUrl, rpcInvocation)
+ resVal := len(filteredInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_methodRoute(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+
+ testData := []struct {
+ name string
+ consumerUrl string
+ rule string
+
+ wantVal bool
+ }{
+ {
+ name: "More than one methods, mismatch",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Exactly one method, match",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo => host = 1.2.3.4",
+
+ wantVal: true,
+ },
+ {
+ name: "Method routing and Other condition routing can work together",
+ consumerUrl: "consumer://1.1.1.1/com.foo.BarService?methods=getFoo",
+ rule: "methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4",
+
+ wantVal: false,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ url, err := common.NewURL("condition://0.0.0.0/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+ consumer, _ := common.NewURL(data.consumerUrl)
+ resVal := router.matchWhen(consumer, rpcInvocation)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_return(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getFoo", nil, nil)
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ urls []string
+ rule string
+
+ wantUrls []string
+ wantVal int
+ }{
+ {
+ name: "ReturnFalse",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => false",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnEmpty",
+ urls: []string{
+ "",
+ "",
+ "",
+ },
+ rule: "host = " + LocalHost + " => ",
+
+ wantUrls: []string{},
+ wantVal: 0,
+ },
+ {
+ name: "ReturnAll",
+ urls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 3,
+ },
+ {
+ name: "HostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "EmptyHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: " => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "FalseHostFilter",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "true => " + " host = " + LocalHost,
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ {
+ name: "PlaceHolder",
+ urls: []string{
+ "dubbo://10.20.3.3:20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ rule: "host = " + LocalHost + " => " + " host = $host",
+
+ wantUrls: []string{
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ "dubbo://" + LocalHost + ":20880/com.foo.BarService",
+ },
+ wantVal: 2,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ invokers := make([]protocol.Invoker, 0, len(data.urls))
+ for _, urlStr := range data.urls {
+ url, _ := common.NewURL(urlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ invokers = append(invokers, invoker)
+ }
+
+ wantInvokers := make([]protocol.Invoker, 0, len(data.wantUrls))
+ for _, wantUrlStr := range data.wantUrls {
+ url, _ := common.NewURL(wantUrlStr)
+ invoker := protocol.NewBaseInvoker(url)
+ wantInvokers = append(wantInvokers, invoker)
+ }
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filterInvokers := router.Route(invokers, consumerUrl, rpcInvocation)
+ resVal := len(filterInvokers)
+
+ assert.Equal(t, data.wantVal, resVal)
+ assert.Equal(t, wantInvokers, filterInvokers)
+ })
+ }
+}
+
+func TestRoute_arguments(t *testing.T) {
+
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ testData := []struct {
+ name string
+ argument interface{}
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "Empty arguments",
+ argument: nil,
+ rule: "arguments[0] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 3,
+ },
+ {
+ name: "String arguments",
+ argument: "a",
+ rule: "arguments[0] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 0,
+ },
+ {
+ name: "Int arguments",
+ argument: 1,
+ rule: "arguments[0] = 1 " + " => " + " host = 127.0.0.1",
+
+ wantVal: 2,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ arguments := make([]interface{}, 0, 1)
+ arguments = append(arguments, data.argument)
+
+ rpcInvocation := invocation.NewRPCInvocation("getBar", arguments, nil)
+
+ filterInvokers := router.Route(invokerList, consumerUrl, rpcInvocation)
+ resVal := len(filterInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+
+ })
+ }
+}
+
+func TestRoute_attachments(t *testing.T) {
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ attachmentKey string
+ attachmentValue string
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "Empty attachments",
+ attachmentKey: "",
+ attachmentValue: "",
+ rule: "attachments[foo] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 3,
+ },
+ {
+ name: "Yes attachments and no host",
+ attachmentKey: "foo",
+ attachmentValue: "a",
+ rule: "attachments[foo] = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 0,
+ },
+ {
+ name: "No attachments and no host",
+ attachmentKey: "foo",
+ attachmentValue: "a",
+ rule: "attachments = a " + " => " + " host = 1.2.3.4",
+
+ wantVal: 3,
+ },
+ {
+ name: "Yes attachments and region",
+ attachmentKey: "foo",
+ attachmentValue: "a",
+ rule: "attachments[foo] = a " + " => " + " region = hangzhou",
+
+ wantVal: 1,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getBar", nil, nil)
+ rpcInvocation.SetAttachment(data.attachmentKey, data.attachmentValue)
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filterInvokers := router.Route(invokerList, consumerUrl, rpcInvocation)
+
+ resVal := len(filterInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_range_pattern(t *testing.T) {
+
+ consumerUrl, _ := common.NewURL("consumer://" + LocalHost + "/com.foo.BarService")
+
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ attachmentKey string
+ attachmentValue string
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "Empty attachment",
+ attachmentKey: "",
+ attachmentValue: "",
+ rule: "attachments[user_id] = 1~100 " + " => " + " region=hangzhou",
+
+ wantVal: 3,
+ },
+ {
+ name: "In the range",
+ attachmentKey: "user_id",
+ attachmentValue: "80",
+ rule: "attachments[user_id] = 1~100 " + " => " + " region=hangzhou",
+
+ wantVal: 1,
+ },
+ {
+ name: "Out of range",
+ attachmentKey: "user_id",
+ attachmentValue: "101",
+ rule: "attachments[user_id] = 1~100 " + " => " + " region=hangzhou",
+
+ wantVal: 3,
+ },
+ {
+ name: "In the single interval range",
+ attachmentKey: "user_id",
+ attachmentValue: "1",
+ rule: "attachments[user_id] = ~100 " + " => " + " region=hangzhou",
+
+ wantVal: 1,
+ },
+ {
+ name: "Not in the single interval range",
+ attachmentKey: "user_id",
+ attachmentValue: "101",
+ rule: "attachments[user_id] = ~100 " + " => " + " region=hangzhou",
+
+ wantVal: 3,
+ },
+ }
+
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+
+ rpcInvocation := invocation.NewRPCInvocation("getBar", nil, nil)
+ rpcInvocation.SetAttachment(data.attachmentKey, data.attachmentValue)
+
+ url, err := common.NewURL("condition://" + LocalHost + "/com.foo.BarService")
+ assert.Nil(t, err)
+ url.AddParam(constant.RuleKey, data.rule)
+ url.AddParam(constant.ForceKey, "true")
+ router, err := NewConditionStateRouter(url)
+ assert.Nil(t, err)
+
+ filterInvokers := router.Route(invokerList, consumerUrl, rpcInvocation)
+
+ resVal := len(filterInvokers)
+ assert.Equal(t, data.wantVal, resVal)
+ })
+ }
+}
+
+func TestRoute_multiple_conditions(t *testing.T) {
+ url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")
+ url2, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+ url3, _ := common.NewURL("dubbo://" + LocalHost + ":20880/com.foo.BarService")
+
+ ink1 := protocol.NewBaseInvoker(url1)
+ ink2 := protocol.NewBaseInvoker(url2)
+ ink3 := protocol.NewBaseInvoker(url3)
+
+ invokerList := make([]protocol.Invoker, 0, 3)
+ invokerList = append(invokerList, ink1)
+ invokerList = append(invokerList, ink2)
+ invokerList = append(invokerList, ink3)
+
+ testData := []struct {
+ name string
+ argument string
+ consumerUrl string
+ rule string
+
+ wantVal int
+ }{
+ {
+ name: "All conditions match",
+ argument: "a",
+ consumerUrl: "consumer://" + LocalHost + "/com.foo.BarService?application=consumer_app",
+ rule: "application=consumer_app&arguments[0]=a" + " => " + " host = " + LocalHost,
+
+ wantVal: 2,
+ },
+ {
+ name: "One of the conditions does not match",
+ argument: "a",
+ consumerUrl: "consumer://" + LocalHost + "/com.foo.BarService?application=another_consumer_app",
+ rule: "application=consumer_app&arguments[0]=a" + " => " + " host = " + LocalHost,
+
+ wantVal: 3,
+ },
+ }
+ for _, data := range testData {
+ t.Run(data.name, func(t *testing.T) {
+ consumerUrl, err := common.NewURL(data.consumerUrl)
Review Comment:
```suggestion
consumerURL, err := common.NewURL(data.consumerUrl)
```
##########
cluster/router/condition/matcher/argument/matcher.go:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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 argument
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/base"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+var (
+ ArgumentsPattern = regexp.MustCompile("arguments\\[([0-9]+)\\]")
+)
+
+/*
+ * 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 ConditionMatcher struct {
+ base.ConditionMatcher
+}
+
+func NewConditionMatcher(key string) *ConditionMatcher {
+ valuePatterns := extension.GetValuePatterns()
+ valueMatchers := make([]pattern.ValuePattern, 0, len(valuePatterns))
+ for _, valuePattern := range valuePatterns {
+ valueMatchers = append(valueMatchers, valuePattern())
+ }
+
+ base.SortValuePattern(valueMatchers)
+
+ conditionMatcher := &ConditionMatcher{
+ base.ConditionMatcher{
+ Key: key,
+ Matches: map[string]struct{}{},
+ Mismatches: map[string]struct{}{},
+ ValueMatchers: valueMatchers,
+ },
+ }
+
+ conditionMatcher.Matcher = conditionMatcher
+ return conditionMatcher
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ // split the rule
+ expressArray := strings.Split(c.Key, "\\.")
+ argumentExpress := expressArray[0]
+ matcher := ArgumentsPattern.FindStringSubmatch(argumentExpress)
+ if len(matcher) == 0 {
+ return "dubbo internal not found argument condition value"
+ }
+
+ //extract the argument index
Review Comment:
```suggestion
// extract the argument index
```
##########
cluster/router/condition/matcher/pattern/value_pattern.go:
##########
@@ -0,0 +1,33 @@
+/*
+ * 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 pattern
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ValuePattern interface {
+ //ShouldMatch return weather the input pattern of a specific form, for example, range pattern '1~100', wildcard pattern 'hello*', etc.
Review Comment:
I guest you want to say:
```suggestion
// ShouldMatch indicates whether the input is a specific pattern, for example, range pattern '1~100', wildcard pattern 'hello*', etc.
```
##########
cluster/router/condition/matcher/pattern/value_pattern.go:
##########
@@ -0,0 +1,33 @@
+/*
+ * 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 pattern
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ValuePattern interface {
+ //ShouldMatch return weather the input pattern of a specific form, for example, range pattern '1~100', wildcard pattern 'hello*', etc.
+ ShouldMatch(pattern string) bool
+ //Match is the pattern matches with the request context
+ Match(pattern string, value string, url *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool
+ // Priority Return Priority in valuePattern
+ // 0 to ^int(0) is better
Review Comment:
Are you saying the range of priority?
##########
cluster/router/condition/matcher/attachment/matcher.go:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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 attachment
+
+import (
+ "regexp"
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/base"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+var (
+ AttachmentsPattern = regexp.MustCompile("attachments\\[(.+)\\]")
+)
+
+/*
+ * analysis the attachments in the rule.
+ * Examples would be like this:
+ * "attachments[foo]=bar", whenCondition is that the attachment value of 'foo' is equal to 'bar'.
+ */
+
+type ConditionMatcher struct {
+ base.ConditionMatcher
+}
+
+func NewConditionMatcher(key string) *ConditionMatcher {
+ valuePatterns := extension.GetValuePatterns()
+ valueMatchers := make([]pattern.ValuePattern, 0, len(valuePatterns))
+ for _, valuePattern := range valuePatterns {
+ valueMatchers = append(valueMatchers, valuePattern())
+ }
+
+ base.SortValuePattern(valueMatchers)
+
+ conditionMatcher := &ConditionMatcher{
+ base.ConditionMatcher{
+ Key: key,
+ Matches: map[string]struct{}{},
+ Mismatches: map[string]struct{}{},
+ ValueMatchers: valueMatchers,
+ },
+ }
+
+ conditionMatcher.Matcher = conditionMatcher
+ return conditionMatcher
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
Review Comment:
Please add some unit tests.
##########
cluster/router/condition/matcher/argument/factory.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 argument
+
+import (
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+)
+
+func init() {
+ extension.SetMatcherFactory("argument", NewArgumentMatcherFactory)
+}
+
+// MatcherFactory matcher factory
+type MatcherFactory struct {
+}
+
+// NewArgumentMatcherFactory constructs a new argument.MatcherFactory
+func NewArgumentMatcherFactory() matcher.ConditionMatcherFactory {
+ return &MatcherFactory{}
+}
+
+func (m *MatcherFactory) ShouldMatch(key string) bool {
+ return strings.HasPrefix(key, constant.ARGUMENTS)
+}
+
+// NewMatcher construct a new matcher
+func (m *MatcherFactory) NewMatcher(key string) matcher.ConditionMatcher {
+ return NewConditionMatcher(key)
+}
+
+func (c *MatcherFactory) Priority() int64 {
+ return 300
Review Comment:
Does a larger value mean that the matcher will perform earlier?
##########
cluster/router/condition/matcher/argument/matcher.go:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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 argument
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/base"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+var (
+ ArgumentsPattern = regexp.MustCompile("arguments\\[([0-9]+)\\]")
+)
+
+/*
+ * 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 ConditionMatcher struct {
+ base.ConditionMatcher
+}
+
+func NewConditionMatcher(key string) *ConditionMatcher {
+ valuePatterns := extension.GetValuePatterns()
+ valueMatchers := make([]pattern.ValuePattern, 0, len(valuePatterns))
+ for _, valuePattern := range valuePatterns {
+ valueMatchers = append(valueMatchers, valuePattern())
+ }
+
+ base.SortValuePattern(valueMatchers)
+
+ conditionMatcher := &ConditionMatcher{
+ base.ConditionMatcher{
+ Key: key,
+ Matches: map[string]struct{}{},
+ Mismatches: map[string]struct{}{},
+ ValueMatchers: valueMatchers,
+ },
+ }
+
+ conditionMatcher.Matcher = conditionMatcher
+ return conditionMatcher
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
Review Comment:
Please add some unit tests.
##########
cluster/router/condition/factory.go:
##########
@@ -0,0 +1,41 @@
+/*
+ * 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 condition
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+)
+
+func init() {
+ extension.SetRouterFactory(constant.ConditionRouterFactoryKey, NewConditionRouterFactory)
+}
+
+// RouteFactory router factory
+type RouteFactory struct{}
+
+// NewConditionRouterFactory constructs a new PriorityRouterFactory
+func NewConditionRouterFactory() router.PriorityRouterFactory {
+ return &RouteFactory{}
+}
+
+// NewPriorityRouter construct a new ConditionDynamicRouter
+func (f *RouteFactory) NewPriorityRouter() (router.PriorityRouter, error) {
Review Comment:
Using `route.PriorityRouter` only as the returned value is fine.
##########
cluster/router/condition/matcher/attachment/matcher.go:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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 attachment
+
+import (
+ "regexp"
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/base"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+var (
+ AttachmentsPattern = regexp.MustCompile("attachments\\[(.+)\\]")
+)
+
+/*
+ * analysis the attachments in the rule.
+ * Examples would be like this:
+ * "attachments[foo]=bar", whenCondition is that the attachment value of 'foo' is equal to 'bar'.
+ */
+
+type ConditionMatcher struct {
+ base.ConditionMatcher
+}
+
+func NewConditionMatcher(key string) *ConditionMatcher {
+ valuePatterns := extension.GetValuePatterns()
+ valueMatchers := make([]pattern.ValuePattern, 0, len(valuePatterns))
+ for _, valuePattern := range valuePatterns {
+ valueMatchers = append(valueMatchers, valuePattern())
+ }
+
+ base.SortValuePattern(valueMatchers)
+
+ conditionMatcher := &ConditionMatcher{
+ base.ConditionMatcher{
+ Key: key,
+ Matches: map[string]struct{}{},
+ Mismatches: map[string]struct{}{},
+ ValueMatchers: valueMatchers,
+ },
+ }
+
+ conditionMatcher.Matcher = conditionMatcher
+ return conditionMatcher
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ // split the rule
+ expressArray := strings.Split(c.Key, "\\.")
+ argumentExpress := expressArray[0]
+ matcher := AttachmentsPattern.FindStringSubmatch(argumentExpress)
+ if len(matcher) == 0 {
+ return "dubbo internal not found attachments condition value"
+ }
+
+ //extract the attachment index
+ attachmentKey := matcher[1]
+ if attachmentKey == "" {
+ return "dubbo internal not found attachments condition value"
+ }
+
+ //extract the attachment value
Review Comment:
```suggestion
// extract the attachment value
```
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) GetSampleValueFromUrl(conditionKey string, sample map[string]string, param *common.URL, invocation protocol.Invocation) string {
+ var sampleValue string
+ //get real invoked method name from invocation
Review Comment:
```suggestion
// get real invoked method name from invocation
```
##########
cluster/router/condition/matcher/attachment/matcher.go:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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 attachment
+
+import (
+ "regexp"
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/base"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+var (
+ AttachmentsPattern = regexp.MustCompile("attachments\\[(.+)\\]")
+)
+
+/*
+ * analysis the attachments in the rule.
+ * Examples would be like this:
+ * "attachments[foo]=bar", whenCondition is that the attachment value of 'foo' is equal to 'bar'.
+ */
+
+type ConditionMatcher struct {
+ base.ConditionMatcher
+}
+
+func NewConditionMatcher(key string) *ConditionMatcher {
+ valuePatterns := extension.GetValuePatterns()
+ valueMatchers := make([]pattern.ValuePattern, 0, len(valuePatterns))
+ for _, valuePattern := range valuePatterns {
+ valueMatchers = append(valueMatchers, valuePattern())
+ }
+
+ base.SortValuePattern(valueMatchers)
+
+ conditionMatcher := &ConditionMatcher{
+ base.ConditionMatcher{
+ Key: key,
+ Matches: map[string]struct{}{},
+ Mismatches: map[string]struct{}{},
+ ValueMatchers: valueMatchers,
+ },
+ }
+
+ conditionMatcher.Matcher = conditionMatcher
+ return conditionMatcher
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ // split the rule
+ expressArray := strings.Split(c.Key, "\\.")
+ argumentExpress := expressArray[0]
+ matcher := AttachmentsPattern.FindStringSubmatch(argumentExpress)
+ if len(matcher) == 0 {
+ return "dubbo internal not found attachments condition value"
+ }
+
+ //extract the attachment index
Review Comment:
```suggestion
// extract the attachment index
```
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
+ ShouldMatch(key string) bool
+ //NewMatcher return a matcher instance for the key.
+ NewMatcher(key string) ConditionMatcher
+ // Priority Return Priority in ConditionMatcherFactory
+ // 0 to ^int(0) is better
+ Priority() int64
+}
+
+/*
+ConditionMatcher represents a specific match condition of a condition rule.
+The following condition rule 'foo=bar&arguments[0]=hello* => region=hangzhou' consists of three ConditionMatchers:
+1. param.ConditionMatcher represented by 'foo=bar'
+2. argument.ConditionMatcher represented by 'arguments[0]=hello*'
+3. param.ConditionMatcher represented by 'region=hangzhou'
+*/
+type ConditionMatcher interface {
+ // IsMatch return weather the patterns of this matcher matches with request context.
+ IsMatch(sample map[string]string, param *common.URL, invocation protocol.Invocation, isWhenCondition bool) bool
+ // GetMatches return Matches
+ // match patterns extracted from when condition
+ GetMatches() map[string]struct{}
+ // GetMismatches return Mismatches
Review Comment:
Btw, do you assign some new values to the matches or mismatches? I only find you assign them when some structs implemented ConditionMatcher interface are constructing.
```go
conditionMatcher := &ConditionMatcher{
base.ConditionMatcher{
Key: key,
Matches: map[string]struct{}{},
Mismatches: map[string]struct{}{},
ValueMatchers: valueMatchers,
},
}
```
But you don't assign any new value to them, like: `conditionMatcher.Matches["aa"] = struct{}{}`.
##########
cluster/router/condition/matcher/base/matcher.go:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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 base
+
+import (
+ "sort"
+)
+
+import (
+ "github.com/dubbogo/gost/log/logger"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher"
+ "dubbo.apache.org/dubbo-go/v3/cluster/router/condition/matcher/pattern"
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+// ConditionMatcher records the match and mismatch patterns of this matcher while at the same time
+// provides the common match logics.
+type ConditionMatcher struct {
+ Matches map[string]struct{}
+ Mismatches map[string]struct{}
+ ValueMatchers []pattern.ValuePattern
+
+ Matcher matcher.ConditionMatcher
+ Key string
+}
+
+func (c *ConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
+ return ""
+}
+
+func (c *ConditionMatcher) GetSampleValueFromUrl(conditionKey string, sample map[string]string, param *common.URL, invocation protocol.Invocation) string {
Review Comment:
It seems that the sample is a map of url. So I'm confused: what is a sample?
I think what you want is getting value from an the url of invoker. To make more clearly, please consider rename your method to:
```
func (c *ConditionMatcher) GetValueFromInvoker(conditionKey string, invokerURL *common.URL, param *common.URL, invocation protocol.Invocation) string {}
```
Btw, you don't need to convert the URL to map too early.
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
+ ShouldMatch(key string) bool
+ //NewMatcher return a matcher instance for the key.
Review Comment:
```suggestion
// NewMatcher returns a matcher instance for the key.
```
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
Review Comment:
```suggestion
// ShouldMatch indicates whether the key is of the form of the current matcher type which this factory instance represents.
```
##########
cluster/router/condition/matcher/matcher.go:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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 (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/protocol"
+)
+
+type ConditionMatcherFactory interface {
+ //ShouldMatch return whether the key is of the form of the current matcher type which this factory instance represents..
+ ShouldMatch(key string) bool
+ //NewMatcher return a matcher instance for the key.
+ NewMatcher(key string) ConditionMatcher
+ // Priority Return Priority in ConditionMatcherFactory
+ // 0 to ^int(0) is better
+ Priority() int64
+}
+
+/*
+ConditionMatcher represents a specific match condition of a condition rule.
+The following condition rule 'foo=bar&arguments[0]=hello* => region=hangzhou' consists of three ConditionMatchers:
+1. param.ConditionMatcher represented by 'foo=bar'
+2. argument.ConditionMatcher represented by 'arguments[0]=hello*'
+3. param.ConditionMatcher represented by 'region=hangzhou'
+*/
+type ConditionMatcher interface {
+ // IsMatch return weather the patterns of this matcher matches with request context.
Review Comment:
```suggestion
// IsMatch indicates whether this matcher matches the patterns with request context.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@dubbo.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@dubbo.apache.org
For additional commands, e-mail: notifications-help@dubbo.apache.org