From 536245aae468907636125d0c640d1fbc7ed75ac0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 5 Sep 2026 15:39:47 +0800 Subject: [PATCH 01/21] feat(router): support affinity and script config centers --- pkg/core/discovery/subscriber/zk_config.go | 22 +++++ pkg/core/governor/governor.go | 8 +- pkg/discovery/nacos2/factory.go | 26 ++++++ pkg/discovery/zk/factory.go | 35 ++++++-- pkg/discovery/zk/factory_test.go | 38 ++++++++ .../zk/listerwatcher/listerwatcher.go | 22 ++++- pkg/governor/nacos2/governor.go | 17 +++- pkg/governor/zk/governor.go | 90 +++++++++++++++++-- pkg/governor/zk/governor_test.go | 36 ++++++++ 9 files changed, 278 insertions(+), 16 deletions(-) create mode 100644 pkg/discovery/zk/factory_test.go create mode 100644 pkg/governor/zk/governor_test.go diff --git a/pkg/core/discovery/subscriber/zk_config.go b/pkg/core/discovery/subscriber/zk_config.go index f4173db4f..bd9104c3f 100644 --- a/pkg/core/discovery/subscriber/zk_config.go +++ b/pkg/core/discovery/subscriber/zk_config.go @@ -116,6 +116,12 @@ func (z *ZKConfigEventSubscriber) processUpsert(configRes *meshresource.ZKConfig case constants.ConfiguratorsSuffix: return processConfigUpsert[*meshresource.DynamicConfigResource]( configRes, meshresource.ToDynamicConfigResource, z.storeRouter, z.emitter) + case constants.AffinityRuleSuffix: + return processConfigUpsert[*meshresource.AffinityRouteResource]( + configRes, meshresource.ToAffinityRouteResource, z.storeRouter, z.emitter) + case constants.ScriptRuleSuffix: + return processConfigUpsert[*meshresource.ScriptRouteResource]( + configRes, meshresource.ToScriptRouteResource, z.storeRouter, z.emitter) default: return bizerror.New(bizerror.UnknownError, fmt.Sprintf("unknown rule type in mesh %s, skipped processing, path: %s, raw content: %s", @@ -141,6 +147,12 @@ func (z *ZKConfigEventSubscriber) processDelete(configRes *meshresource.ZKConfig case constants.ConfiguratorsSuffix: return processConfigDelete[*meshresource.DynamicConfigResource]( configRes, meshresource.DynamicConfigKind, z.storeRouter, z.emitter) + case constants.AffinityRuleSuffix: + return processConfigDelete[*meshresource.AffinityRouteResource]( + configRes, meshresource.AffinityRouteKind, z.storeRouter, z.emitter) + case constants.ScriptRuleSuffix: + return processConfigDelete[*meshresource.ScriptRouteResource]( + configRes, meshresource.ScriptRouteKind, z.storeRouter, z.emitter) default: return bizerror.New(bizerror.UnknownError, fmt.Sprintf("unknown rule type in mesh %s, skipped processing, node: %s", @@ -273,6 +285,16 @@ func extractRuleEventContext(res coremodel.Resource) (string, string) { return "", "" } return item.Spec.Key, "dynamic-config" + case *meshresource.AffinityRouteResource: + if item.Spec == nil { + return "", "" + } + return item.Spec.Key, "affinity-route" + case *meshresource.ScriptRouteResource: + if item.Spec == nil { + return "", "" + } + return item.Spec.Key, "script-route" default: return "", "" } diff --git a/pkg/core/governor/governor.go b/pkg/core/governor/governor.go index d29fd156a..255124a12 100644 --- a/pkg/core/governor/governor.go +++ b/pkg/core/governor/governor.go @@ -24,7 +24,13 @@ import ( "github.com/apache/dubbo-admin/pkg/core/resource/model" ) -var RuleResourceKinds = set.New(meshresource.DynamicConfigKind, meshresource.ConditionRouteKind, meshresource.TagRouteKind) +var RuleResourceKinds = set.New( + meshresource.DynamicConfigKind, + meshresource.ConditionRouteKind, + meshresource.TagRouteKind, + meshresource.AffinityRouteKind, + meshresource.ScriptRouteKind, +) // RuleGovernor makes the rule operations effective type RuleGovernor interface { diff --git a/pkg/discovery/nacos2/factory.go b/pkg/discovery/nacos2/factory.go index 65d391a56..04649dcb1 100644 --- a/pkg/discovery/nacos2/factory.go +++ b/pkg/discovery/nacos2/factory.go @@ -127,6 +127,30 @@ func (f *Factory) initListerWatchers( if err != nil { return nil, err } + affinityRouteLW, err := listerwatcher.NewConfigListerWatcher( + meshresource.AffinityRouteKind, + cfg, + nacosConfigClient, + meshresource.ToAffinityRouteResource, + true, + constants.WildcardCharacter+constants.AffinityRuleDotSuffix, + constants.NacosConfigGroup, + ) + if err != nil { + return nil, err + } + scriptRouteLW, err := listerwatcher.NewConfigListerWatcher( + meshresource.ScriptRouteKind, + cfg, + nacosConfigClient, + meshresource.ToScriptRouteResource, + true, + constants.WildcardCharacter+constants.ScriptRuleDotSuffix, + constants.NacosConfigGroup, + ) + if err != nil { + return nil, err + } serviceProviderMetadataLW, err := listerwatcher.NewConfigListerWatcher( meshresource.ServiceProviderMetadataKind, cfg, @@ -156,6 +180,8 @@ func (f *Factory) initListerWatchers( dynamicConfigLW, conditionRouteLW, tagRouteLW, + affinityRouteLW, + scriptRouteLW, serviceProviderMetadataLW, serviceProviderMappingLW, }, nil diff --git a/pkg/discovery/zk/factory.go b/pkg/discovery/zk/factory.go index 7518af8f0..a12d28fa7 100644 --- a/pkg/discovery/zk/factory.go +++ b/pkg/discovery/zk/factory.go @@ -67,12 +67,15 @@ func (f *Factory) NewListWatchers(config *discoverycfg.Config) ([]controller.Res if err != nil { return nil, err } - configLW, err := listerwatcher.NewListerWatcher( + // Keep the config watcher connected to the configured config-center + // endpoint. Registry and config-center addresses are allowed to differ. + configLW, err := listerwatcher.NewListerWatcherWithAddress( meshresource.ZKConfigKind, toUpsertZKConfigResource, toDeleteZKConfigResource, "/dubbo/config", config, + config.Address.ConfigCenter, ) if err != nil { return nil, err @@ -116,11 +119,10 @@ func toDeleteMappingResource(mesh, nodePath string) coremodel.Resource { } func toUpsertZKConfigResource(mesh, nodePath, nodeData string) coremodel.Resource { - paths := strings.Split(nodePath, constants.PathSeparator) - if len(paths) != 4 { + configName, ok := zkConfigName(nodePath) + if !ok { return nil } - configName := paths[3] res := meshresource.NewZKConfigResourceWithAttributes(configName, mesh) res.Spec = &meshproto.ZKConfig{ NodeName: configName, @@ -130,11 +132,10 @@ func toUpsertZKConfigResource(mesh, nodePath, nodeData string) coremodel.Resourc } func toDeleteZKConfigResource(mesh, nodePath string) coremodel.Resource { - paths := strings.Split(nodePath, constants.PathSeparator) - if len(paths) != 4 { + configName, ok := zkConfigName(nodePath) + if !ok { return nil } - configName := paths[3] res := meshresource.NewZKConfigResourceWithAttributes(configName, mesh) res.Spec = &meshproto.ZKConfig{ NodeName: configName, @@ -142,6 +143,26 @@ func toDeleteZKConfigResource(mesh, nodePath string) coremodel.Resource { return res } +// zkConfigName accepts the Dubbo 3 grouped config path +// /dubbo/config/dubbo/ and the legacy flat path +// /dubbo/config/. Group/root nodes are not rules. +func zkConfigName(nodePath string) (string, bool) { + paths := strings.Split(strings.Trim(nodePath, constants.PathSeparator), constants.PathSeparator) + // Trim above removes the leading slash, therefore the grouped form has + // [dubbo config dubbo rule] and the legacy form [dubbo config rule]. + switch len(paths) { + case 3: + if paths[2] != "" && paths[2] != constants.RuleConfigGroup { + return paths[2], true + } + case 4: + if paths[2] == constants.RuleConfigGroup && paths[3] != "" { + return paths[3], true + } + } + return "", false +} + func toUpsertZKMetadataResource(mesh, nodePath, nodeData string) coremodel.Resource { paths := strings.Split(nodePath, constants.PathSeparator) if len(paths) < 5 { diff --git a/pkg/discovery/zk/factory_test.go b/pkg/discovery/zk/factory_test.go new file mode 100644 index 000000000..dce75d57e --- /dev/null +++ b/pkg/discovery/zk/factory_test.go @@ -0,0 +1,38 @@ +/* + * 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 + */ + +package zk + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestZKConfigNameSupportsGroupedAndLegacyPaths(t *testing.T) { + tests := []struct { + path string + name string + ok bool + }{ + {"/dubbo/config/dubbo/provider.affinity-router", "provider.affinity-router", true}, + {"/dubbo/config/dubbo/provider.script-router", "provider.script-router", true}, + {"/dubbo/config/provider.tag-router", "provider.tag-router", true}, + {"/dubbo/config", "", false}, + {"/dubbo/config/dubbo", "", false}, + {"/dubbo/config/other/group", "", false}, + } + for _, tt := range tests { + name, ok := zkConfigName(tt.path) + require.Equal(t, tt.ok, ok, tt.path) + require.Equal(t, tt.name, name, tt.path) + } +} diff --git a/pkg/discovery/zk/listerwatcher/listerwatcher.go b/pkg/discovery/zk/listerwatcher/listerwatcher.go index 61b0f1581..a9d0d2f44 100644 --- a/pkg/discovery/zk/listerwatcher/listerwatcher.go +++ b/pkg/discovery/zk/listerwatcher/listerwatcher.go @@ -44,6 +44,7 @@ type ListerWatcher[T coremodel.Resource] struct { rk coremodel.ResourceKind conn *zk.Conn cfg *discoverycfg.Config + zkAddress string toUpsertResourceFunc ToUpsertResourceFunc toDeleteResourceFunc ToDeleteResourceFunc newResourceFunc coremodel.NewResourceFunc @@ -59,6 +60,21 @@ func NewListerWatcher( toDeleteResourceFunc ToDeleteResourceFunc, basePath string, cfg *discoverycfg.Config) (*ListerWatcher[coremodel.Resource], error) { + return NewListerWatcherWithAddress(rk, toResourceFunc, toDeleteResourceFunc, basePath, cfg, cfg.Address.Registry) +} + +// NewListerWatcherWithAddress is used when a resource lives in a dedicated +// config-center endpoint instead of the service registry endpoint. +func NewListerWatcherWithAddress( + rk coremodel.ResourceKind, + toResourceFunc ToUpsertResourceFunc, + toDeleteResourceFunc ToDeleteResourceFunc, + basePath string, + cfg *discoverycfg.Config, + zkAddress string) (*ListerWatcher[coremodel.Resource], error) { + if zkAddress == "" { + zkAddress = cfg.Address.Registry + } newResourceFunc, err := coremodel.ResourceSchemaRegistry().NewResourceFunc(rk) if err != nil { return nil, err @@ -67,7 +83,7 @@ func NewListerWatcher( if err != nil { return nil, err } - conn, err := clients.NewZKConnection(cfg.Address.Registry) + conn, err := clients.NewZKConnection(zkAddress) if err != nil { return nil, err } @@ -78,6 +94,7 @@ func NewListerWatcher( basePath: basePath, conn: conn, cfg: cfg, + zkAddress: zkAddress, newResourceFunc: newResourceFunc, newResListFunc: newResListFunc, resultChan: make(chan watch.Event, 1000), @@ -198,6 +215,9 @@ func (lw *ListerWatcher[T]) handleEvent(event zkwatcher.ZookeeperEvent) { } func (lw *ListerWatcher[T]) zkAddr() string { + if lw.zkAddress != "" { + return lw.zkAddress + } return lw.cfg.Address.Registry } diff --git a/pkg/governor/nacos2/governor.go b/pkg/governor/nacos2/governor.go index 4c3bf80fe..7d781b568 100644 --- a/pkg/governor/nacos2/governor.go +++ b/pkg/governor/nacos2/governor.go @@ -64,7 +64,7 @@ func NewNacos2Governor( } func (g *RuleGovernor) CreateRule(r coremodel.Resource) error { - rawContent, err := meshresource.MarshalRuleSpec(r.ResourceSpec()) + rawContent, err := marshalRule(r) if err != nil { return bizerror.Wrap(err, bizerror.NacosError, fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) @@ -139,6 +139,14 @@ func (g *RuleGovernor) GetConfigAndUpdateStore(r coremodel.Resource) { res = meshresource.ToConditionRouteResource(r.ResourceMesh(), r.ResourceMeta().Name, content) case meshresource.TagRouteKind: res = meshresource.ToTagRouteResource(r.ResourceMesh(), r.ResourceMeta().Name, content) + case meshresource.AffinityRouteKind: + res = meshresource.ToAffinityRouteResource(r.ResourceMesh(), r.ResourceMeta().Name, content) + case meshresource.ScriptRouteKind: + res = meshresource.ToScriptRouteResource(r.ResourceMesh(), r.ResourceMeta().Name, content) + } + if res == nil { + logger.Errorf("failed to decode config in %s, res: %s", r.String(), r.ResourceMesh()) + return } obj, exists, err := st.GetByKey(r.ResourceKey()) if err != nil { @@ -169,6 +177,13 @@ func (g *RuleGovernor) GetConfigAndUpdateStore(r coremodel.Resource) { g.emitter.Send(events.NewResourceChangedEvent(cache.Added, nil, res)) } +func marshalRule(r coremodel.Resource) ([]byte, error) { + if r.ResourceKind() == meshresource.AffinityRouteKind || r.ResourceKind() == meshresource.ScriptRouteKind { + return meshresource.EncodeRule(r) + } + return yaml.Marshal(r.ResourceSpec()) +} + func (g *RuleGovernor) mesh() string { return g.cfg.ID } diff --git a/pkg/governor/zk/governor.go b/pkg/governor/zk/governor.go index e408d6f98..c324f8ba8 100644 --- a/pkg/governor/zk/governor.go +++ b/pkg/governor/zk/governor.go @@ -19,10 +19,13 @@ package zk import ( "fmt" + "strings" "github.com/dubbogo/go-zookeeper/zk" + "sigs.k8s.io/yaml" "github.com/apache/dubbo-admin/pkg/common/bizerror" + "github.com/apache/dubbo-admin/pkg/common/constants" discoverycfg "github.com/apache/dubbo-admin/pkg/config/discovery" "github.com/apache/dubbo-admin/pkg/core/clients" "github.com/apache/dubbo-admin/pkg/core/events" @@ -32,6 +35,8 @@ import ( "github.com/apache/dubbo-admin/pkg/core/store" ) +const zkConfigRootPath = "/dubbo/config" + type RuleGovernor struct { cfg *discoverycfg.Config storeRouter store.Router @@ -40,7 +45,9 @@ type RuleGovernor struct { } func NewZKRuleGovernor(cfg *discoverycfg.Config, router store.Router, emitter events.Emitter) (*RuleGovernor, error) { - address := cfg.Address.Registry + // Runtime dynamic configuration is stored in the config-center endpoint; + // it may intentionally differ from the service registry endpoint. + address := cfg.Address.ConfigCenter conn, err := clients.NewZKConnection(address) if err != nil { return nil, err @@ -54,12 +61,17 @@ func NewZKRuleGovernor(cfg *discoverycfg.Config, router store.Router, emitter ev } func (g *RuleGovernor) CreateRule(r coremodel.Resource) error { - path := "/dubbo/config/" + r.ResourceMeta().Name - content, err := meshresource.MarshalRuleSpec(r.ResourceSpec()) + path := ruleConfigPath(r) + content, err := marshalRule(r) if err != nil { return bizerror.Wrap(err, bizerror.YamlError, fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) } + if usesDubboConfigGroup(r) { + if err := g.ensurePath(ruleConfigGroupPath()); err != nil { + return err + } + } _, err = g.conn.Create(path, content, 0, zk.WorldACL(zk.PermAll)) if err != nil { return bizerror.Wrap(err, bizerror.ZKError, @@ -81,13 +93,19 @@ func (g *RuleGovernor) CreateRule(r coremodel.Resource) error { } func (g *RuleGovernor) UpdateRule(r coremodel.Resource) error { - path := "/dubbo/config/" + r.ResourceMeta().Name - content, err := meshresource.MarshalRuleSpec(r.ResourceSpec()) + path := ruleConfigPath(r) + content, err := marshalRule(r) if err != nil { return bizerror.Wrap(err, bizerror.YamlError, fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) } _, err = g.conn.Set(path, content, -1) + if err == zk.ErrNoNode && usesDubboConfigGroup(r) { + if ensureErr := g.ensurePath(ruleConfigGroupPath()); ensureErr != nil { + return ensureErr + } + _, err = g.conn.Create(path, content, 0, zk.WorldACL(zk.PermAll)) + } if err != nil { return bizerror.Wrap(err, bizerror.ZKError, fmt.Sprintf("failed to update zk node, path: %s", path)) @@ -105,8 +123,13 @@ func (g *RuleGovernor) UpdateRule(r coremodel.Resource) error { } func (g *RuleGovernor) DeleteRule(r coremodel.Resource) error { - path := "/dubbo/config/" + r.ResourceMeta().Name + path := ruleConfigPath(r) err := g.conn.Delete(path, -1) + if err == zk.ErrNoNode && usesDubboConfigGroup(r) { + // Rules created by older Admin versions used the flat path. Remove it + // as a compatibility fallback while all new writes use the grouped path. + err = g.conn.Delete(legacyRuleConfigPath(r.ResourceMeta().Name), -1) + } if err != nil { return bizerror.Wrap(err, bizerror.ZKError, fmt.Sprintf("failed to delete zk node, path: %s", path)) @@ -121,3 +144,58 @@ func (g *RuleGovernor) DeleteRule(r coremodel.Resource) error { } return nil } + +func marshalRule(r coremodel.Resource) ([]byte, error) { + if r.ResourceKind() == meshresource.AffinityRouteKind || r.ResourceKind() == meshresource.ScriptRouteKind { + return meshresource.EncodeRule(r) + } + return yaml.Marshal(r.ResourceSpec()) +} + +func ruleConfigPath(r coremodel.Resource) string { + if usesDubboConfigGroup(r) { + return ruleConfigGroupPath() + "/" + r.ResourceMeta().Name + } + return legacyRuleConfigPath(r.ResourceMeta().Name) +} + +// usesDubboConfigGroup deliberately scopes the new key layout to Affinity and +// Script. Existing Configurator, Condition, and Tag rules retain their legacy +// paths so this alignment work does not change their control-plane contract. +func usesDubboConfigGroup(r coremodel.Resource) bool { + return r != nil && (r.ResourceKind() == meshresource.AffinityRouteKind || r.ResourceKind() == meshresource.ScriptRouteKind) +} + +func ruleConfigGroupPath() string { + return zkConfigRootPath + "/" + constants.RuleConfigGroup +} + +func legacyRuleConfigPath(ruleName string) string { + return zkConfigRootPath + "/" + ruleName +} + +// ensurePath creates every component of a grouped config path. ZooKeeper's +// Create operation is not recursive, and a fresh config center may not yet +// contain /dubbo/config/dubbo. +func (g *RuleGovernor) ensurePath(targetPath string) error { + parts := strings.Split(strings.Trim(targetPath, "/"), "/") + current := "" + for _, part := range parts { + if part == "" { + continue + } + current += "/" + part + exists, _, err := g.conn.Exists(current) + if err != nil { + return bizerror.Wrap(err, bizerror.ZKError, fmt.Sprintf("failed to check zk node, path: %s", current)) + } + if exists { + continue + } + _, err = g.conn.Create(current, nil, 0, zk.WorldACL(zk.PermAll)) + if err != nil && err != zk.ErrNodeExists { + return bizerror.Wrap(err, bizerror.ZKError, fmt.Sprintf("failed to create zk node, path: %s", current)) + } + } + return nil +} diff --git a/pkg/governor/zk/governor_test.go b/pkg/governor/zk/governor_test.go new file mode 100644 index 000000000..24d8fd0bf --- /dev/null +++ b/pkg/governor/zk/governor_test.go @@ -0,0 +1,36 @@ +/* + * 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 + */ + +package zk + +import ( + "testing" + + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" +) + +func TestRuleConfigPathsPreserveExistingRuleContracts(t *testing.T) { + paths := []struct { + name string + res coremodel.Resource + want string + }{ + {"affinity", meshresource.NewAffinityRouteResourceWithAttributes("provider.affinity-router", "mesh"), "/dubbo/config/dubbo/provider.affinity-router"}, + {"script", meshresource.NewScriptRouteResourceWithAttributes("provider.script-router", "mesh"), "/dubbo/config/dubbo/provider.script-router"}, + {"condition", meshresource.NewConditionRouteResourceWithAttributes("provider.condition-router", "mesh"), "/dubbo/config/provider.condition-router"}, + } + for _, tt := range paths { + if got := ruleConfigPath(tt.res); got != tt.want { + t.Fatalf("%s ruleConfigPath() = %q, want %q", tt.name, got, tt.want) + } + } +} From 8be85698c2349fdef9f7aa5f4c43eefb35d6534f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 12 Sep 2026 22:41:53 +0800 Subject: [PATCH 02/21] test(router): add missing license headers --- pkg/discovery/zk/factory_test.go | 5 +++++ pkg/governor/zk/governor_test.go | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/pkg/discovery/zk/factory_test.go b/pkg/discovery/zk/factory_test.go index dce75d57e..564ca3380 100644 --- a/pkg/discovery/zk/factory_test.go +++ b/pkg/discovery/zk/factory_test.go @@ -7,6 +7,11 @@ * 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 zk diff --git a/pkg/governor/zk/governor_test.go b/pkg/governor/zk/governor_test.go index 24d8fd0bf..de55967be 100644 --- a/pkg/governor/zk/governor_test.go +++ b/pkg/governor/zk/governor_test.go @@ -7,6 +7,11 @@ * 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 zk From 2be080f876ae1209fda7043ca1f84d6903a17a51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 17 Oct 2026 16:53:36 +0800 Subject: [PATCH 03/21] fix(router): unify ZooKeeper rule paths --- pkg/discovery/zk/factory.go | 21 ++++++---------- pkg/discovery/zk/factory_test.go | 43 -------------------------------- pkg/governor/zk/governor.go | 29 +++------------------ pkg/governor/zk/governor_test.go | 41 ------------------------------ 4 files changed, 11 insertions(+), 123 deletions(-) delete mode 100644 pkg/discovery/zk/factory_test.go delete mode 100644 pkg/governor/zk/governor_test.go diff --git a/pkg/discovery/zk/factory.go b/pkg/discovery/zk/factory.go index a12d28fa7..ae20c8b9f 100644 --- a/pkg/discovery/zk/factory.go +++ b/pkg/discovery/zk/factory.go @@ -143,22 +143,15 @@ func toDeleteZKConfigResource(mesh, nodePath string) coremodel.Resource { return res } -// zkConfigName accepts the Dubbo 3 grouped config path -// /dubbo/config/dubbo/ and the legacy flat path -// /dubbo/config/. Group/root nodes are not rules. +// zkConfigName accepts only the Dubbo 3 grouped config path +// /dubbo/config/dubbo/. Group/root nodes and legacy flat paths are +// not rules. func zkConfigName(nodePath string) (string, bool) { paths := strings.Split(strings.Trim(nodePath, constants.PathSeparator), constants.PathSeparator) - // Trim above removes the leading slash, therefore the grouped form has - // [dubbo config dubbo rule] and the legacy form [dubbo config rule]. - switch len(paths) { - case 3: - if paths[2] != "" && paths[2] != constants.RuleConfigGroup { - return paths[2], true - } - case 4: - if paths[2] == constants.RuleConfigGroup && paths[3] != "" { - return paths[3], true - } + // Trim above removes the leading slash, therefore the grouped form is + // [dubbo config dubbo rule]. + if len(paths) == 4 && paths[2] == constants.RuleConfigGroup && paths[3] != "" { + return paths[3], true } return "", false } diff --git a/pkg/discovery/zk/factory_test.go b/pkg/discovery/zk/factory_test.go deleted file mode 100644 index 564ca3380..000000000 --- a/pkg/discovery/zk/factory_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 zk - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestZKConfigNameSupportsGroupedAndLegacyPaths(t *testing.T) { - tests := []struct { - path string - name string - ok bool - }{ - {"/dubbo/config/dubbo/provider.affinity-router", "provider.affinity-router", true}, - {"/dubbo/config/dubbo/provider.script-router", "provider.script-router", true}, - {"/dubbo/config/provider.tag-router", "provider.tag-router", true}, - {"/dubbo/config", "", false}, - {"/dubbo/config/dubbo", "", false}, - {"/dubbo/config/other/group", "", false}, - } - for _, tt := range tests { - name, ok := zkConfigName(tt.path) - require.Equal(t, tt.ok, ok, tt.path) - require.Equal(t, tt.name, name, tt.path) - } -} diff --git a/pkg/governor/zk/governor.go b/pkg/governor/zk/governor.go index c324f8ba8..3f2895e70 100644 --- a/pkg/governor/zk/governor.go +++ b/pkg/governor/zk/governor.go @@ -67,10 +67,8 @@ func (g *RuleGovernor) CreateRule(r coremodel.Resource) error { return bizerror.Wrap(err, bizerror.YamlError, fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) } - if usesDubboConfigGroup(r) { - if err := g.ensurePath(ruleConfigGroupPath()); err != nil { - return err - } + if err := g.ensurePath(ruleConfigGroupPath()); err != nil { + return err } _, err = g.conn.Create(path, content, 0, zk.WorldACL(zk.PermAll)) if err != nil { @@ -100,7 +98,7 @@ func (g *RuleGovernor) UpdateRule(r coremodel.Resource) error { fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) } _, err = g.conn.Set(path, content, -1) - if err == zk.ErrNoNode && usesDubboConfigGroup(r) { + if err == zk.ErrNoNode { if ensureErr := g.ensurePath(ruleConfigGroupPath()); ensureErr != nil { return ensureErr } @@ -125,11 +123,6 @@ func (g *RuleGovernor) UpdateRule(r coremodel.Resource) error { func (g *RuleGovernor) DeleteRule(r coremodel.Resource) error { path := ruleConfigPath(r) err := g.conn.Delete(path, -1) - if err == zk.ErrNoNode && usesDubboConfigGroup(r) { - // Rules created by older Admin versions used the flat path. Remove it - // as a compatibility fallback while all new writes use the grouped path. - err = g.conn.Delete(legacyRuleConfigPath(r.ResourceMeta().Name), -1) - } if err != nil { return bizerror.Wrap(err, bizerror.ZKError, fmt.Sprintf("failed to delete zk node, path: %s", path)) @@ -153,27 +146,13 @@ func marshalRule(r coremodel.Resource) ([]byte, error) { } func ruleConfigPath(r coremodel.Resource) string { - if usesDubboConfigGroup(r) { - return ruleConfigGroupPath() + "/" + r.ResourceMeta().Name - } - return legacyRuleConfigPath(r.ResourceMeta().Name) -} - -// usesDubboConfigGroup deliberately scopes the new key layout to Affinity and -// Script. Existing Configurator, Condition, and Tag rules retain their legacy -// paths so this alignment work does not change their control-plane contract. -func usesDubboConfigGroup(r coremodel.Resource) bool { - return r != nil && (r.ResourceKind() == meshresource.AffinityRouteKind || r.ResourceKind() == meshresource.ScriptRouteKind) + return ruleConfigGroupPath() + "/" + r.ResourceMeta().Name } func ruleConfigGroupPath() string { return zkConfigRootPath + "/" + constants.RuleConfigGroup } -func legacyRuleConfigPath(ruleName string) string { - return zkConfigRootPath + "/" + ruleName -} - // ensurePath creates every component of a grouped config path. ZooKeeper's // Create operation is not recursive, and a fresh config center may not yet // contain /dubbo/config/dubbo. diff --git a/pkg/governor/zk/governor_test.go b/pkg/governor/zk/governor_test.go deleted file mode 100644 index de55967be..000000000 --- a/pkg/governor/zk/governor_test.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 zk - -import ( - "testing" - - meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" - coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" -) - -func TestRuleConfigPathsPreserveExistingRuleContracts(t *testing.T) { - paths := []struct { - name string - res coremodel.Resource - want string - }{ - {"affinity", meshresource.NewAffinityRouteResourceWithAttributes("provider.affinity-router", "mesh"), "/dubbo/config/dubbo/provider.affinity-router"}, - {"script", meshresource.NewScriptRouteResourceWithAttributes("provider.script-router", "mesh"), "/dubbo/config/dubbo/provider.script-router"}, - {"condition", meshresource.NewConditionRouteResourceWithAttributes("provider.condition-router", "mesh"), "/dubbo/config/provider.condition-router"}, - } - for _, tt := range paths { - if got := ruleConfigPath(tt.res); got != tt.want { - t.Fatalf("%s ruleConfigPath() = %q, want %q", tt.name, got, tt.want) - } - } -} From 9b4062f17f759866f3a18fd413ed6397254550d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 17 Oct 2026 16:59:41 +0800 Subject: [PATCH 04/21] fix(router): restore Nacos rule encoding import --- pkg/governor/nacos2/governor.go | 1 + 1 file changed, 1 insertion(+) diff --git a/pkg/governor/nacos2/governor.go b/pkg/governor/nacos2/governor.go index 7d781b568..f964fc149 100644 --- a/pkg/governor/nacos2/governor.go +++ b/pkg/governor/nacos2/governor.go @@ -26,6 +26,7 @@ import ( nacosnamingclient "github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client" nacosvo "github.com/nacos-group/nacos-sdk-go/v2/vo" "k8s.io/client-go/tools/cache" + "sigs.k8s.io/yaml" "github.com/apache/dubbo-admin/pkg/common/bizerror" "github.com/apache/dubbo-admin/pkg/common/constants" From 05fc9424012de67e2c6b89fd0c6345f7a430f9da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 5 Sep 2026 15:44:39 +0800 Subject: [PATCH 05/21] feat(console): manage affinity and script router rules (cherry picked from commit a7364bc3f09209a6f5f141708c398cb1d240c0a4) --- pkg/console/handler/router_rule.go | 233 ++++++++++++++++++ pkg/console/handler/router_rule_test.go | 71 ++++++ pkg/console/model/router_rule.go | 99 ++++++++ pkg/console/router/router.go | 26 ++ pkg/console/service/affinity_rule.go | 89 +++++-- pkg/console/service/router_rule_test.go | 117 +++++++++ pkg/console/service/rule_version.go | 6 + .../service/rule_version_rollback_test.go | 6 +- pkg/console/service/script_rule.go | 100 ++++++++ pkg/core/versioning/normalize.go | 16 ++ 10 files changed, 747 insertions(+), 16 deletions(-) create mode 100644 pkg/console/handler/router_rule.go create mode 100644 pkg/console/handler/router_rule_test.go create mode 100644 pkg/console/model/router_rule.go create mode 100644 pkg/console/service/router_rule_test.go create mode 100644 pkg/console/service/script_rule.go diff --git a/pkg/console/handler/router_rule.go b/pkg/console/handler/router_rule.go new file mode 100644 index 000000000..be24163df --- /dev/null +++ b/pkg/console/handler/router_rule.go @@ -0,0 +1,233 @@ +/* + * 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 handler + +import ( + "fmt" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + + "github.com/apache/dubbo-admin/pkg/common/bizerror" + "github.com/apache/dubbo-admin/pkg/common/constants" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/console/service" + "github.com/apache/dubbo-admin/pkg/console/util" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" +) + +func AffinityRuleSearch(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := model.NewSearchConditionRuleReq() + if err := c.ShouldBindQuery(req); err != nil { + util.HandleArgumentError(c, err) + return + } + result, err := service.SearchAffinityRules(ctx, req) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(result)) + } +} + +func GetAffinityRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + if !validRouterRuleName(c, constants.AffinityRuleDotSuffix) { + return + } + name, mesh := c.Param("ruleName"), c.Query("mesh") + res, err := service.GetAffinityRule(ctx, name, mesh) + if err != nil { + util.HandleServiceError(c, err) + return + } + if res == nil { + util.HandleNotFoundError(c, name) + return + } + c.JSON(http.StatusOK, model.GenAffinityRuleResp(res.Spec)) + } +} + +func PostAffinityRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return mutateAffinityRule(ctx, false) +} + +func PutAffinityRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return mutateAffinityRule(ctx, true) +} + +func mutateAffinityRule(ctx consolectx.Context, update bool) gin.HandlerFunc { + return func(c *gin.Context) { + if !validRouterRuleName(c, constants.AffinityRuleDotSuffix) { + return + } + input := &model.AffinityRuleInput{} + if err := c.ShouldBindJSON(input); err != nil { + util.HandleArgumentError(c, err) + return + } + name, mesh := c.Param("ruleName"), c.Query("mesh") + res := meshresource.NewAffinityRouteResourceWithAttributes(name, mesh) + res.Spec = input.ToProto() + if err := meshresource.ValidateRule(res); err != nil { + util.HandleArgumentError(c, err) + return + } + if update { + existing, err := service.GetAffinityRule(ctx, name, mesh) + if err != nil { + util.HandleServiceError(c, err) + return + } + if existing == nil { + util.HandleNotFoundError(c, name) + return + } + if err := service.UpdateAffinityRuleWithOptions(ctx, res, mutationOptions(c)); err != nil { + util.HandleServiceError(c, err) + return + } + } else if err := service.CreateAffinityRuleWithOptions(ctx, res, mutationOptions(c)); err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.GenAffinityRuleResp(res.Spec)) + } +} + +func DeleteAffinityRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + if !validRouterRuleName(c, constants.AffinityRuleDotSuffix) { + return + } + if err := service.DeleteAffinityRuleWithOptions(ctx, c.Param("ruleName"), c.Query("mesh"), mutationOptions(c)); err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp("")) + } +} + +func ScriptRuleSearch(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + req := model.NewSearchConditionRuleReq() + if err := c.ShouldBindQuery(req); err != nil { + util.HandleArgumentError(c, err) + return + } + result, err := service.SearchScriptRules(ctx, req) + if err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp(result)) + } +} + +func GetScriptRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + if !validRouterRuleName(c, constants.ScriptRuleDotSuffix) { + return + } + name, mesh := c.Param("ruleName"), c.Query("mesh") + res, err := service.GetScriptRule(ctx, name, mesh) + if err != nil { + util.HandleServiceError(c, err) + return + } + if res == nil { + util.HandleNotFoundError(c, name) + return + } + c.JSON(http.StatusOK, model.GenScriptRuleResp(res.Spec)) + } +} + +func PostScriptRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return mutateScriptRule(ctx, false) +} + +func PutScriptRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return mutateScriptRule(ctx, true) +} + +func mutateScriptRule(ctx consolectx.Context, update bool) gin.HandlerFunc { + return func(c *gin.Context) { + if !validRouterRuleName(c, constants.ScriptRuleDotSuffix) { + return + } + input := &model.ScriptRuleInput{} + if err := c.ShouldBindJSON(input); err != nil { + util.HandleArgumentError(c, err) + return + } + name, mesh := c.Param("ruleName"), c.Query("mesh") + res := meshresource.NewScriptRouteResourceWithAttributes(name, mesh) + res.Spec = input.ToProto() + if err := meshresource.ValidateRule(res); err != nil { + util.HandleArgumentError(c, err) + return + } + if update { + existing, err := service.GetScriptRule(ctx, name, mesh) + if err != nil { + util.HandleServiceError(c, err) + return + } + if existing == nil { + util.HandleNotFoundError(c, name) + return + } + if err := service.UpdateScriptRuleWithOptions(ctx, res, mutationOptions(c)); err != nil { + util.HandleServiceError(c, err) + return + } + } else if err := service.CreateScriptRuleWithOptions(ctx, res, mutationOptions(c)); err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.GenScriptRuleResp(res.Spec)) + } +} + +func DeleteScriptRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { + return func(c *gin.Context) { + if !validRouterRuleName(c, constants.ScriptRuleDotSuffix) { + return + } + if err := service.DeleteScriptRuleWithOptions(ctx, c.Param("ruleName"), c.Query("mesh"), mutationOptions(c)); err != nil { + util.HandleServiceError(c, err) + return + } + c.JSON(http.StatusOK, model.NewSuccessResp("")) + } +} + +func validRouterRuleName(c *gin.Context, suffix string) bool { + if strings.HasSuffix(c.Param("ruleName"), suffix) { + return true + } + err := bizerror.New(bizerror.InvalidArgument, fmt.Sprintf("ruleName must end with %s", suffix)) + c.JSON(http.StatusBadRequest, model.NewBizErrorResp(err)) + return false +} diff --git a/pkg/console/handler/router_rule_test.go b/pkg/console/handler/router_rule_test.go new file mode 100644 index 000000000..1147d72c6 --- /dev/null +++ b/pkg/console/handler/router_rule_test.go @@ -0,0 +1,71 @@ +/* + * 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 handler + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + + "github.com/apache/dubbo-admin/pkg/common/bizerror" +) + +func TestPostAffinityRuleRejectsInvalidRuntimeContract(t *testing.T) { + ctx, recorder := testGinContext() + ctx.Request = httptest.NewRequest(http.MethodPost, "/affinity-rule/demo.affinity-router", strings.NewReader(`{ + "configVersion":"v3.1", "scope":"application", "key":"demo", "enabled":true, + "runtime":true, "affinityAware":{"key":"region", "ratio":101} + }`)) + ctx.Request.Header.Set("Content-Type", "application/json") + ctx.Params = gin.Params{{Key: "ruleName", Value: "demo.affinity-router"}} + + PostAffinityRuleWithRuleName(ruleVersionHandlerTestContext{})(ctx) + + assert.Equal(t, http.StatusOK, recorder.Code) + assert.Equal(t, string(bizerror.InvalidArgument), decodeCommonResp(t, recorder).Code) +} + +func TestPostScriptRuleRejectsUnsupportedScriptType(t *testing.T) { + ctx, recorder := testGinContext() + ctx.Request = httptest.NewRequest(http.MethodPost, "/script-rule/demo.script-router", strings.NewReader(`{ + "configVersion":"v3.0", "scope":"application", "key":"demo", "enabled":true, + "type":"groovy", "script":"return invokers;" + }`)) + ctx.Request.Header.Set("Content-Type", "application/json") + ctx.Params = gin.Params{{Key: "ruleName", Value: "demo.script-router"}} + + PostScriptRuleWithRuleName(ruleVersionHandlerTestContext{})(ctx) + + assert.Equal(t, http.StatusOK, recorder.Code) + assert.Equal(t, string(bizerror.InvalidArgument), decodeCommonResp(t, recorder).Code) +} + +func TestRouterRuleHandlersRejectWrongRuleSuffix(t *testing.T) { + ctx, recorder := testGinContext() + ctx.Request = httptest.NewRequest(http.MethodPost, "/script-rule/demo.affinity-router", nil) + ctx.Params = gin.Params{{Key: "ruleName", Value: "demo.affinity-router"}} + + PostScriptRuleWithRuleName(ruleVersionHandlerTestContext{})(ctx) + + assert.Equal(t, http.StatusBadRequest, recorder.Code) + assert.Equal(t, string(bizerror.InvalidArgument), decodeCommonResp(t, recorder).Code) +} diff --git a/pkg/console/model/router_rule.go b/pkg/console/model/router_rule.go new file mode 100644 index 000000000..71ec8720e --- /dev/null +++ b/pkg/console/model/router_rule.go @@ -0,0 +1,99 @@ +/* + * 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 model + +import meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + +// RouterRuleSearchResp is intentionally body-free; script text is returned +// only by the detail endpoint. +type RouterRuleSearchResp struct { + CreateTime string `json:"createTime"` + Enabled bool `json:"enabled"` + RuleName string `json:"ruleName"` + Scope string `json:"scope"` +} + +// AffinityRuleInput is the public Console representation. affinityAware is +// mapped to the internal protobuf field named affinity. +type AffinityRuleInput struct { + ConfigVersion string `json:"configVersion"` + Scope string `json:"scope"` + Key string `json:"key"` + Runtime bool `json:"runtime"` + Enabled bool `json:"enabled"` + AffinityAware *meshproto.AffinityAware `json:"affinityAware"` +} + +func (i *AffinityRuleInput) ToProto() *meshproto.AffinityRoute { + return &meshproto.AffinityRoute{ + ConfigVersion: i.ConfigVersion, + Scope: i.Scope, + Key: i.Key, + Runtime: i.Runtime, + Enabled: i.Enabled, + Affinity: i.AffinityAware, + } +} + +func GenAffinityRuleResp(data *meshproto.AffinityRoute) *CommonResp { + if data == nil { + return NewSuccessResp(nil) + } + return NewSuccessResp(AffinityRuleInput{ + ConfigVersion: data.ConfigVersion, + Scope: data.Scope, + Key: data.Key, + Runtime: data.Runtime, + Enabled: data.Enabled, + AffinityAware: data.Affinity, + }) +} + +type ScriptRuleInput struct { + ConfigVersion string `json:"configVersion"` + Scope string `json:"scope"` + Key string `json:"key"` + Enabled bool `json:"enabled"` + Type string `json:"type"` + Script string `json:"script"` +} + +func (i *ScriptRuleInput) ToProto() *meshproto.ScriptRoute { + return &meshproto.ScriptRoute{ + ConfigVersion: i.ConfigVersion, + Scope: i.Scope, + Key: i.Key, + Enabled: i.Enabled, + Type: i.Type, + Script: i.Script, + } +} + +func GenScriptRuleResp(data *meshproto.ScriptRoute) *CommonResp { + if data == nil { + return NewSuccessResp(nil) + } + return NewSuccessResp(ScriptRuleInput{ + ConfigVersion: data.ConfigVersion, + Scope: data.Scope, + Key: data.Key, + Enabled: data.Enabled, + Type: data.Type, + Script: data.Script, + }) +} diff --git a/pkg/console/router/router.go b/pkg/console/router/router.go index 67b90fb0f..0a6ba0efb 100644 --- a/pkg/console/router/router.go +++ b/pkg/console/router/router.go @@ -167,6 +167,32 @@ func InitRouter(r *gin.Engine, ctx consolectx.Context) error { tagRule.DELETE("/:ruleName", handler.DeleteTagRuleWithRuleName(ctx)) } + { + affinityRule := protected.Group("/affinity-rule") + affinityRule.GET("/search", handler.AffinityRuleSearch(ctx)) + affinityRule.GET("/:ruleName/versions", handler.ListRuleVersions(ctx, meshresource.AffinityRouteKind)) + affinityRule.GET("/:ruleName/versions/:versionNo", handler.GetRuleVersion(ctx, meshresource.AffinityRouteKind)) + affinityRule.GET("/:ruleName/versions/:versionNo/diff", handler.DiffRuleVersion(ctx, meshresource.AffinityRouteKind)) + affinityRule.POST("/:ruleName/versions/:versionNo/rollback", handler.RollbackRuleVersion(ctx, meshresource.AffinityRouteKind)) + affinityRule.GET("/:ruleName", handler.GetAffinityRuleWithRuleName(ctx)) + affinityRule.PUT("/:ruleName", handler.PutAffinityRuleWithRuleName(ctx)) + affinityRule.POST("/:ruleName", handler.PostAffinityRuleWithRuleName(ctx)) + affinityRule.DELETE("/:ruleName", handler.DeleteAffinityRuleWithRuleName(ctx)) + } + + { + scriptRule := protected.Group("/script-rule") + scriptRule.GET("/search", handler.ScriptRuleSearch(ctx)) + scriptRule.GET("/:ruleName/versions", handler.ListRuleVersions(ctx, meshresource.ScriptRouteKind)) + scriptRule.GET("/:ruleName/versions/:versionNo", handler.GetRuleVersion(ctx, meshresource.ScriptRouteKind)) + scriptRule.GET("/:ruleName/versions/:versionNo/diff", handler.DiffRuleVersion(ctx, meshresource.ScriptRouteKind)) + scriptRule.POST("/:ruleName/versions/:versionNo/rollback", handler.RollbackRuleVersion(ctx, meshresource.ScriptRouteKind)) + scriptRule.GET("/:ruleName", handler.GetScriptRuleWithRuleName(ctx)) + scriptRule.PUT("/:ruleName", handler.PutScriptRuleWithRuleName(ctx)) + scriptRule.POST("/:ruleName", handler.PostScriptRuleWithRuleName(ctx)) + scriptRule.DELETE("/:ruleName", handler.DeleteScriptRuleWithRuleName(ctx)) + } + protected.GET("/prometheus", handler.GetPrometheus(ctx)) protected.GET("/search", handler.BannerGlobalSearch(ctx)) protected.GET("/overview", handler.ClusterOverview(ctx)) diff --git a/pkg/console/service/affinity_rule.go b/pkg/console/service/affinity_rule.go index c7d5f2b2d..602902907 100644 --- a/pkg/console/service/affinity_rule.go +++ b/pkg/console/service/affinity_rule.go @@ -18,18 +18,22 @@ package service import ( + "github.com/duke-git/lancet/v2/slice" + "github.com/duke-git/lancet/v2/strutil" + + "github.com/apache/dubbo-admin/pkg/common/bizerror" consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" "github.com/apache/dubbo-admin/pkg/core/logger" "github.com/apache/dubbo-admin/pkg/core/manager" meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" ) -func GetAffinityRule(ctx consolectx.Context, name string, mesh string) (*meshresource.AffinityRouteResource, error) { +func GetAffinityRule(ctx consolectx.Context, name, mesh string) (*meshresource.AffinityRouteResource, error) { res, _, err := manager.GetByKey[*meshresource.AffinityRouteResource]( - ctx.ResourceManager(), - meshresource.AffinityRouteKind, - coremodel.BuildResourceKey(mesh, name)) + ctx.ResourceManager(), meshresource.AffinityRouteKind, coremodel.BuildResourceKey(mesh, name)) if err != nil { logger.Warnf("get affinity rule %s error: %v", name, err) return nil, err @@ -37,27 +41,82 @@ func GetAffinityRule(ctx consolectx.Context, name string, mesh string) (*meshres return res, nil } -func UpdateAffinityRule(ctx consolectx.Context, res *meshresource.AffinityRouteResource) error { - if err := ctx.ResourceManager().Update(res); err != nil { - logger.Warnf("update %s affinity rule failed with error: %s", res.Name, err.Error()) +func SearchAffinityRules(ctx consolectx.Context, req *model.SearchConditionRuleReq) (*model.SearchPaginationResult, error) { + if strutil.IsNotBlank(req.Keywords) { + res, exists, err := manager.GetByKey[*meshresource.AffinityRouteResource]( + ctx.ResourceManager(), meshresource.AffinityRouteKind, + coremodel.BuildResourceKey(req.Mesh, req.Keywords)) + if err != nil { + return nil, err + } + if !exists || res == nil { + return emptyRouterRuleSearch(req.PageReq), nil + } + return &model.SearchPaginationResult{ + List: []*model.RouterRuleSearchResp{affinitySearchItem(res)}, + PageInfo: coremodel.Pagination{Total: 1, PageSize: req.PageSize, PageOffset: req.PageOffset}, + }, nil + } + page, err := manager.PageListByIndexes[*meshresource.AffinityRouteResource]( + ctx.ResourceManager(), meshresource.AffinityRouteKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: req.Mesh, Operator: index.Equals}}, req.PageReq) + if err != nil { + logger.Errorf("search affinity route error: %v", err) + return nil, bizerror.New(bizerror.InternalError, "search affinity route failed, please try again") + } + list := slice.FilterMap(page.Data, func(_ int, item *meshresource.AffinityRouteResource) (*model.RouterRuleSearchResp, bool) { + if item == nil || item.Spec == nil { + return nil, false + } + return affinitySearchItem(item), true + }) + return &model.SearchPaginationResult{List: list, PageInfo: page.Pagination}, nil +} + +func affinitySearchItem(r *meshresource.AffinityRouteResource) *model.RouterRuleSearchResp { + scope := "" + enabled := false + if r.Spec != nil { + scope, enabled = r.Spec.Scope, r.Spec.Enabled + } + return &model.RouterRuleSearchResp{CreateTime: r.CreationTimestamp.String(), Enabled: enabled, RuleName: r.Name, Scope: scope} +} + +func emptyRouterRuleSearch(page coremodel.PageReq) *model.SearchPaginationResult { + return &model.SearchPaginationResult{List: nil, PageInfo: coremodel.Pagination{PageSize: page.PageSize, PageOffset: page.PageOffset}} +} + +func CreateAffinityRule(ctx consolectx.Context, res *meshresource.AffinityRouteResource) error { + return CreateAffinityRuleWithOptions(ctx, res, RuleMutationOptions{}) +} + +func CreateAffinityRuleWithOptions(ctx consolectx.Context, res *meshresource.AffinityRouteResource, opts RuleMutationOptions) error { + if err := createRule(ctx, res, opts); err != nil { + logger.Warnf("create %s affinity rule failed with error: %s", res.Name, err.Error()) return err } return nil } -func CreateAffinityRule(ctx consolectx.Context, res *meshresource.AffinityRouteResource) error { - if err := ctx.ResourceManager().Add(res); err != nil { - logger.Warnf("create %s condition failed with error: %s", res.Name, err.Error()) +func UpdateAffinityRule(ctx consolectx.Context, res *meshresource.AffinityRouteResource) error { + return UpdateAffinityRuleWithOptions(ctx, res, RuleMutationOptions{}) +} + +func UpdateAffinityRuleWithOptions(ctx consolectx.Context, res *meshresource.AffinityRouteResource, opts RuleMutationOptions) error { + if err := updateRule(ctx, res, opts); err != nil { + logger.Warnf("update %s affinity rule failed with error: %s", res.Name, err.Error()) return err } return nil } -func DeleteAffinityRule(ctx consolectx.Context, name string, mesh string) error { - if err := ctx.ResourceManager().DeleteByKey( - meshresource.AffinityRouteKind, - mesh, - coremodel.BuildResourceKey(mesh, name)); err != nil { +func DeleteAffinityRule(ctx consolectx.Context, name, mesh string) error { + return DeleteAffinityRuleWithOptions(ctx, name, mesh, RuleMutationOptions{}) +} + +func DeleteAffinityRuleWithOptions(ctx consolectx.Context, name, mesh string, opts RuleMutationOptions) error { + if err := deleteRule(ctx, RuleRef{Kind: meshresource.AffinityRouteKind, Mesh: mesh, Name: name}, opts); err != nil { + logger.Warnf("delete %s affinity rule failed with error: %s", name, err.Error()) return err } return nil diff --git a/pkg/console/service/router_rule_test.go b/pkg/console/service/router_rule_test.go new file mode 100644 index 000000000..14ed788fe --- /dev/null +++ b/pkg/console/service/router_rule_test.go @@ -0,0 +1,117 @@ +/* + * 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 service + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/core/versioning" +) + +func TestAffinityRuleLifecycleAndRollback(t *testing.T) { + ctx := setupRollbackTestEnv(t) + key := "demo-provider" + name := key + ".affinity-router" + initial := affinityRouterRule(key, 50) + + require.NoError(t, CreateAffinityRuleWithOptions(ctx, initial, RuleMutationOptions{Author: "admin"})) + require.NoError(t, UpdateAffinityRuleWithOptions(ctx, affinityRouterRule(key, 80), RuleMutationOptions{Author: "admin"})) + + versions, err := ListRuleVersions(ctx, RuleRef{Kind: meshresource.AffinityRouteKind, Name: name}) + require.NoError(t, err) + require.Len(t, versions.Items, 2) + assert.Equal(t, versioning.OperationUpdate, versions.Items[0].Operation) + assert.Equal(t, versioning.OperationCreate, versions.Items[1].Operation) + + _, err = RollbackRuleVersion(ctx, RuleRef{Kind: meshresource.AffinityRouteKind, Name: name}, versions.Items[1].VersionNo, "restore affinity", "admin") + require.NoError(t, err) + actual, err := GetAffinityRule(ctx, name, "") + require.NoError(t, err) + require.NotNil(t, actual) + assert.EqualValues(t, 50, actual.Spec.Affinity.Ratio) + + require.NoError(t, DeleteAffinityRuleWithOptions(ctx, name, "", RuleMutationOptions{Author: "admin"})) +} + +func TestScriptRuleLifecycleAndRollback(t *testing.T) { + ctx := setupRollbackTestEnv(t) + key := "demo-provider" + name := key + ".script-router" + initial := scriptRouterRule(key, "return [invokers[0]];") + + require.NoError(t, CreateScriptRuleWithOptions(ctx, initial, RuleMutationOptions{Author: "admin"})) + require.NoError(t, UpdateScriptRuleWithOptions(ctx, scriptRouterRule(key, "return [invokers[1]];"), RuleMutationOptions{Author: "admin"})) + + versions, err := ListRuleVersions(ctx, RuleRef{Kind: meshresource.ScriptRouteKind, Name: name}) + require.NoError(t, err) + require.Len(t, versions.Items, 2) + assert.Equal(t, versioning.OperationUpdate, versions.Items[0].Operation) + assert.Equal(t, versioning.OperationCreate, versions.Items[1].Operation) + + _, err = RollbackRuleVersion(ctx, RuleRef{Kind: meshresource.ScriptRouteKind, Name: name}, versions.Items[1].VersionNo, "restore script", "admin") + require.NoError(t, err) + actual, err := GetScriptRule(ctx, name, "") + require.NoError(t, err) + require.NotNil(t, actual) + assert.Equal(t, initial.Spec.Script, actual.Spec.Script) + + require.NoError(t, DeleteScriptRuleWithOptions(ctx, name, "", RuleMutationOptions{Author: "admin"})) +} + +func TestRouterRuleMutationRejectsInvalidRuntimeContract(t *testing.T) { + ctx := setupRollbackTestEnv(t) + invalid := scriptRouterRule("demo-provider", "return invokers;") + invalid.Spec.Type = "groovy" + + err := CreateScriptRuleWithOptions(ctx, invalid, RuleMutationOptions{Author: "admin"}) + require.Error(t, err) + versions, historyErr := ListRuleVersions(ctx, RuleRef{Kind: meshresource.ScriptRouteKind, Name: invalid.Name}) + require.NoError(t, historyErr) + assert.Empty(t, versions.Items) +} + +func affinityRouterRule(key string, ratio int32) *meshresource.AffinityRouteResource { + res := meshresource.NewAffinityRouteResourceWithAttributes(key+".affinity-router", "") + res.Spec = &meshproto.AffinityRoute{ + ConfigVersion: "v3.1", + Scope: "application", + Key: key, + Runtime: true, + Enabled: true, + Affinity: &meshproto.AffinityAware{Key: "region", Ratio: ratio}, + } + return res +} + +func scriptRouterRule(key, script string) *meshresource.ScriptRouteResource { + res := meshresource.NewScriptRouteResourceWithAttributes(key+".script-router", "") + res.Spec = &meshproto.ScriptRoute{ + ConfigVersion: "v3.0", + Scope: "application", + Key: key, + Enabled: true, + Type: "javascript", + Script: script, + } + return res +} diff --git a/pkg/console/service/rule_version.go b/pkg/console/service/rule_version.go index bbe5cf7b5..39233e4da 100644 --- a/pkg/console/service/rule_version.go +++ b/pkg/console/service/rule_version.go @@ -132,6 +132,9 @@ func ruleLockKey(ruleRef RuleRef) string { } func createRule(ctx consolectx.Context, res coremodel.Resource, opts RuleMutationOptions) error { + if err := meshresource.ValidateRule(res); err != nil { + return err + } ruleRef := RuleRef{Kind: res.ResourceKind(), Mesh: res.ResourceMesh(), Name: res.ResourceMeta().Name} return withRuleLock(ctx, ruleRef, func() error { if _, err := appendRuleHistory(ctx, res, versioning.OperationCreate, versioning.SourceAdmin, opts.Author, "", nil); err != nil { @@ -145,6 +148,9 @@ func createRule(ctx consolectx.Context, res coremodel.Resource, opts RuleMutatio } func updateRule(ctx consolectx.Context, res coremodel.Resource, opts RuleMutationOptions) error { + if err := meshresource.ValidateRule(res); err != nil { + return err + } ruleRef := RuleRef{Kind: res.ResourceKind(), Mesh: res.ResourceMesh(), Name: res.ResourceMeta().Name} return withRuleLock(ctx, ruleRef, func() error { existing, err := getExistingRule(ctx, ruleRef) diff --git a/pkg/console/service/rule_version_rollback_test.go b/pkg/console/service/rule_version_rollback_test.go index c0e1f50bc..c667d6cb7 100644 --- a/pkg/console/service/rule_version_rollback_test.go +++ b/pkg/console/service/rule_version_rollback_test.go @@ -227,11 +227,13 @@ func (s *failingResourceStore) Add(obj interface{}) error { } func setupRollbackTestEnv(t *testing.T, wrapVersionStore ...func(store.ResourceStore) store.ResourceStore) *testContext { + affinityStore := memoryst.NewMemoryResourceStore(meshresource.AffinityRouteKind) conditionStore := memoryst.NewMemoryResourceStore(meshresource.ConditionRouteKind) dynamicConfigStore := memoryst.NewMemoryResourceStore(meshresource.DynamicConfigKind) + scriptStore := memoryst.NewMemoryResourceStore(meshresource.ScriptRouteKind) tagStore := memoryst.NewMemoryResourceStore(meshresource.TagRouteKind) versionStore := memoryst.NewMemoryResourceStore(meshresource.RuleVersionKind) - for _, s := range []store.ManagedResourceStore{conditionStore, dynamicConfigStore, tagStore, versionStore} { + for _, s := range []store.ManagedResourceStore{affinityStore, conditionStore, dynamicConfigStore, scriptStore, tagStore, versionStore} { require.NoError(t, s.Init(nil)) } @@ -240,8 +242,10 @@ func setupRollbackTestEnv(t *testing.T, wrapVersionStore ...func(store.ResourceS versioningVersionStore = wrapVersionStore[0](versionStore) } stores := map[coremodel.ResourceKind]store.ResourceStore{ + meshresource.AffinityRouteKind: affinityStore, meshresource.ConditionRouteKind: conditionStore, meshresource.DynamicConfigKind: dynamicConfigStore, + meshresource.ScriptRouteKind: scriptStore, meshresource.TagRouteKind: tagStore, meshresource.RuleVersionKind: versioningVersionStore, } diff --git a/pkg/console/service/script_rule.go b/pkg/console/service/script_rule.go new file mode 100644 index 000000000..10c316901 --- /dev/null +++ b/pkg/console/service/script_rule.go @@ -0,0 +1,100 @@ +/* + * 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 service + +import ( + "github.com/duke-git/lancet/v2/slice" + "github.com/duke-git/lancet/v2/strutil" + + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store/index" +) + +func GetScriptRule(ctx consolectx.Context, name, mesh string) (*meshresource.ScriptRouteResource, error) { + res, _, err := manager.GetByKey[*meshresource.ScriptRouteResource]( + ctx.ResourceManager(), meshresource.ScriptRouteKind, coremodel.BuildResourceKey(mesh, name)) + return res, err +} + +func SearchScriptRules(ctx consolectx.Context, req *model.SearchConditionRuleReq) (*model.SearchPaginationResult, error) { + if strutil.IsNotBlank(req.Keywords) { + res, exists, err := manager.GetByKey[*meshresource.ScriptRouteResource]( + ctx.ResourceManager(), meshresource.ScriptRouteKind, + coremodel.BuildResourceKey(req.Mesh, req.Keywords)) + if err != nil { + return nil, err + } + if !exists || res == nil { + return emptyRouterRuleSearch(req.PageReq), nil + } + return &model.SearchPaginationResult{ + List: []*model.RouterRuleSearchResp{scriptSearchItem(res)}, + PageInfo: coremodel.Pagination{Total: 1, PageSize: req.PageSize, PageOffset: req.PageOffset}, + }, nil + } + page, err := manager.PageListByIndexes[*meshresource.ScriptRouteResource]( + ctx.ResourceManager(), meshresource.ScriptRouteKind, + []index.IndexCondition{{IndexName: index.ByMeshIndex, Value: req.Mesh, Operator: index.Equals}}, req.PageReq) + if err != nil { + return nil, err + } + list := slice.FilterMap(page.Data, func(_ int, item *meshresource.ScriptRouteResource) (*model.RouterRuleSearchResp, bool) { + if item == nil || item.Spec == nil { + return nil, false + } + return scriptSearchItem(item), true + }) + return &model.SearchPaginationResult{List: list, PageInfo: page.Pagination}, nil +} + +func scriptSearchItem(r *meshresource.ScriptRouteResource) *model.RouterRuleSearchResp { + scope := "" + enabled := false + if r.Spec != nil { + scope, enabled = r.Spec.Scope, r.Spec.Enabled + } + return &model.RouterRuleSearchResp{CreateTime: r.CreationTimestamp.String(), Enabled: enabled, RuleName: r.Name, Scope: scope} +} + +func CreateScriptRule(ctx consolectx.Context, res *meshresource.ScriptRouteResource) error { + return CreateScriptRuleWithOptions(ctx, res, RuleMutationOptions{}) +} + +func CreateScriptRuleWithOptions(ctx consolectx.Context, res *meshresource.ScriptRouteResource, opts RuleMutationOptions) error { + return createRule(ctx, res, opts) +} + +func UpdateScriptRule(ctx consolectx.Context, res *meshresource.ScriptRouteResource) error { + return UpdateScriptRuleWithOptions(ctx, res, RuleMutationOptions{}) +} + +func UpdateScriptRuleWithOptions(ctx consolectx.Context, res *meshresource.ScriptRouteResource, opts RuleMutationOptions) error { + return updateRule(ctx, res, opts) +} + +func DeleteScriptRule(ctx consolectx.Context, name, mesh string) error { + return DeleteScriptRuleWithOptions(ctx, name, mesh, RuleMutationOptions{}) +} + +func DeleteScriptRuleWithOptions(ctx consolectx.Context, name, mesh string, opts RuleMutationOptions) error { + return deleteRule(ctx, RuleRef{Kind: meshresource.ScriptRouteKind, Mesh: mesh, Name: name}, opts) +} diff --git a/pkg/core/versioning/normalize.go b/pkg/core/versioning/normalize.go index 34cfce72b..85c70d566 100644 --- a/pkg/core/versioning/normalize.go +++ b/pkg/core/versioning/normalize.go @@ -115,6 +115,22 @@ func ResourceFromSpecJSON(kind coremodel.ResourceKind, mesh, ruleName, specJSON } res.Spec = &spec return res, nil + case meshresource.AffinityRouteKind: + res := meshresource.NewAffinityRouteResourceWithAttributes(ruleName, mesh) + var spec meshproto.AffinityRoute + if err := unmarshalSpec(specJSON, &spec); err != nil { + return nil, err + } + res.Spec = &spec + return res, nil + case meshresource.ScriptRouteKind: + res := meshresource.NewScriptRouteResourceWithAttributes(ruleName, mesh) + var spec meshproto.ScriptRoute + if err := unmarshalSpec(specJSON, &spec); err != nil { + return nil, err + } + res.Spec = &spec + return res, nil default: return nil, bizerror.New(bizerror.InvalidArgument, "unsupported rule kind") } From ff2e02b14d61f121f1244ed5d3cd9ecd10b5e95b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 17 Oct 2026 18:02:13 +0800 Subject: [PATCH 06/21] fix(router): preserve optional rule boolean presence (cherry picked from commit 4a2ea0987291d9f95284e02b522e0a6c1bf8a221) --- pkg/console/handler/router_rule.go | 10 +- pkg/console/model/router_rule.go | 38 ++-- pkg/console/model/router_rule_test.go | 102 ++++++++++ pkg/console/service/router_rule_test.go | 35 ++++ .../apis/mesh/v1alpha1/router_rule_codec.go | 50 +++++ pkg/core/versioning/normalize.go | 180 +++++++++++++++++- pkg/core/versioning/normalize_test.go | 126 ++++++++++++ 7 files changed, 515 insertions(+), 26 deletions(-) create mode 100644 pkg/console/model/router_rule_test.go create mode 100644 pkg/core/versioning/normalize_test.go diff --git a/pkg/console/handler/router_rule.go b/pkg/console/handler/router_rule.go index be24163df..4da19d98d 100644 --- a/pkg/console/handler/router_rule.go +++ b/pkg/console/handler/router_rule.go @@ -64,7 +64,7 @@ func GetAffinityRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { util.HandleNotFoundError(c, name) return } - c.JSON(http.StatusOK, model.GenAffinityRuleResp(res.Spec)) + c.JSON(http.StatusOK, model.GenAffinityRuleResp(res)) } } @@ -89,6 +89,7 @@ func mutateAffinityRule(ctx consolectx.Context, update bool) gin.HandlerFunc { name, mesh := c.Param("ruleName"), c.Query("mesh") res := meshresource.NewAffinityRouteResourceWithAttributes(name, mesh) res.Spec = input.ToProto() + meshresource.SetAffinityRuleOptionalFields(res, input.Runtime, input.Enabled) if err := meshresource.ValidateRule(res); err != nil { util.HandleArgumentError(c, err) return @@ -111,7 +112,7 @@ func mutateAffinityRule(ctx consolectx.Context, update bool) gin.HandlerFunc { util.HandleServiceError(c, err) return } - c.JSON(http.StatusOK, model.GenAffinityRuleResp(res.Spec)) + c.JSON(http.StatusOK, model.GenAffinityRuleResp(res)) } } @@ -159,7 +160,7 @@ func GetScriptRuleWithRuleName(ctx consolectx.Context) gin.HandlerFunc { util.HandleNotFoundError(c, name) return } - c.JSON(http.StatusOK, model.GenScriptRuleResp(res.Spec)) + c.JSON(http.StatusOK, model.GenScriptRuleResp(res)) } } @@ -184,6 +185,7 @@ func mutateScriptRule(ctx consolectx.Context, update bool) gin.HandlerFunc { name, mesh := c.Param("ruleName"), c.Query("mesh") res := meshresource.NewScriptRouteResourceWithAttributes(name, mesh) res.Spec = input.ToProto() + meshresource.SetScriptRuleOptionalEnabled(res, input.Enabled) if err := meshresource.ValidateRule(res); err != nil { util.HandleArgumentError(c, err) return @@ -206,7 +208,7 @@ func mutateScriptRule(ctx consolectx.Context, update bool) gin.HandlerFunc { util.HandleServiceError(c, err) return } - c.JSON(http.StatusOK, model.GenScriptRuleResp(res.Spec)) + c.JSON(http.StatusOK, model.GenScriptRuleResp(res)) } } diff --git a/pkg/console/model/router_rule.go b/pkg/console/model/router_rule.go index 71ec8720e..fedb873c0 100644 --- a/pkg/console/model/router_rule.go +++ b/pkg/console/model/router_rule.go @@ -17,7 +17,10 @@ package model -import meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" +import ( + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" +) // RouterRuleSearchResp is intentionally body-free; script text is returned // only by the detail endpoint. @@ -34,8 +37,8 @@ type AffinityRuleInput struct { ConfigVersion string `json:"configVersion"` Scope string `json:"scope"` Key string `json:"key"` - Runtime bool `json:"runtime"` - Enabled bool `json:"enabled"` + Runtime *bool `json:"runtime,omitempty"` + Enabled *bool `json:"enabled,omitempty"` AffinityAware *meshproto.AffinityAware `json:"affinityAware"` } @@ -44,22 +47,24 @@ func (i *AffinityRuleInput) ToProto() *meshproto.AffinityRoute { ConfigVersion: i.ConfigVersion, Scope: i.Scope, Key: i.Key, - Runtime: i.Runtime, - Enabled: i.Enabled, + Runtime: optionalBoolValue(i.Runtime), + Enabled: optionalBoolValue(i.Enabled), Affinity: i.AffinityAware, } } -func GenAffinityRuleResp(data *meshproto.AffinityRoute) *CommonResp { - if data == nil { +func GenAffinityRuleResp(res *meshresource.AffinityRouteResource) *CommonResp { + if res == nil || res.Spec == nil { return NewSuccessResp(nil) } + data := res.Spec + runtime, enabled := meshresource.AffinityRuleOptionalFields(res) return NewSuccessResp(AffinityRuleInput{ ConfigVersion: data.ConfigVersion, Scope: data.Scope, Key: data.Key, - Runtime: data.Runtime, - Enabled: data.Enabled, + Runtime: runtime, + Enabled: enabled, AffinityAware: data.Affinity, }) } @@ -68,7 +73,7 @@ type ScriptRuleInput struct { ConfigVersion string `json:"configVersion"` Scope string `json:"scope"` Key string `json:"key"` - Enabled bool `json:"enabled"` + Enabled *bool `json:"enabled,omitempty"` Type string `json:"type"` Script string `json:"script"` } @@ -78,22 +83,27 @@ func (i *ScriptRuleInput) ToProto() *meshproto.ScriptRoute { ConfigVersion: i.ConfigVersion, Scope: i.Scope, Key: i.Key, - Enabled: i.Enabled, + Enabled: optionalBoolValue(i.Enabled), Type: i.Type, Script: i.Script, } } -func GenScriptRuleResp(data *meshproto.ScriptRoute) *CommonResp { - if data == nil { +func GenScriptRuleResp(res *meshresource.ScriptRouteResource) *CommonResp { + if res == nil || res.Spec == nil { return NewSuccessResp(nil) } + data := res.Spec return NewSuccessResp(ScriptRuleInput{ ConfigVersion: data.ConfigVersion, Scope: data.Scope, Key: data.Key, - Enabled: data.Enabled, + Enabled: meshresource.ScriptRuleOptionalEnabled(res), Type: data.Type, Script: data.Script, }) } + +func optionalBoolValue(value *bool) bool { + return value != nil && *value +} diff --git a/pkg/console/model/router_rule_test.go b/pkg/console/model/router_rule_test.go new file mode 100644 index 000000000..34744edc5 --- /dev/null +++ b/pkg/console/model/router_rule_test.go @@ -0,0 +1,102 @@ +/* + * 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 model + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" +) + +func TestScriptRuleDetailRoundTripPreservesOmittedEnabled(t *testing.T) { + source, err := meshresource.DecodeRule(meshresource.ScriptRouteKind, "mesh", "demo.script-router", ` +configVersion: v3.0 +scope: application +key: demo +type: javascript +script: return invokers; +`) + require.NoError(t, err) + + input := GenScriptRuleResp(source.(*meshresource.ScriptRouteResource)).Data.(ScriptRuleInput) + require.Nil(t, input.Enabled) + body, err := json.Marshal(input) + require.NoError(t, err) + require.NotContains(t, string(body), `"enabled"`) + + restored := meshresource.NewScriptRouteResourceWithAttributes("demo.script-router", "mesh") + restored.Spec = input.ToProto() + meshresource.SetScriptRuleOptionalEnabled(restored, input.Enabled) + raw, err := meshresource.EncodeRule(restored) + require.NoError(t, err) + require.NotContains(t, string(raw), "enabled:") +} + +func TestAffinityRuleDetailRoundTripPreservesOptionalBooleans(t *testing.T) { + source, err := meshresource.DecodeRule(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", ` +configVersion: v3.1 +scope: application +key: demo +affinityAware: + key: region + ratio: 50 +`) + require.NoError(t, err) + + input := GenAffinityRuleResp(source.(*meshresource.AffinityRouteResource)).Data.(AffinityRuleInput) + require.Nil(t, input.Runtime) + require.Nil(t, input.Enabled) + body, err := json.Marshal(input) + require.NoError(t, err) + require.NotContains(t, string(body), `"runtime"`) + require.NotContains(t, string(body), `"enabled"`) + + restored := meshresource.NewAffinityRouteResourceWithAttributes("demo.affinity-router", "mesh") + restored.Spec = input.ToProto() + meshresource.SetAffinityRuleOptionalFields(restored, input.Runtime, input.Enabled) + raw, err := meshresource.EncodeRule(restored) + require.NoError(t, err) + require.NotContains(t, string(raw), "runtime:") + require.NotContains(t, string(raw), "enabled:") +} + +func TestScriptRuleDetailRoundTripPreservesExplicitFalse(t *testing.T) { + source, err := meshresource.DecodeRule(meshresource.ScriptRouteKind, "mesh", "demo.script-router", ` +configVersion: v3.0 +scope: application +key: demo +enabled: false +type: javascript +script: return invokers; +`) + require.NoError(t, err) + + input := GenScriptRuleResp(source.(*meshresource.ScriptRouteResource)).Data.(ScriptRuleInput) + require.NotNil(t, input.Enabled) + require.False(t, *input.Enabled) + + restored := meshresource.NewScriptRouteResourceWithAttributes("demo.script-router", "mesh") + restored.Spec = input.ToProto() + meshresource.SetScriptRuleOptionalEnabled(restored, input.Enabled) + raw, err := meshresource.EncodeRule(restored) + require.NoError(t, err) + require.Contains(t, string(raw), "enabled: false") +} diff --git a/pkg/console/service/router_rule_test.go b/pkg/console/service/router_rule_test.go index 14ed788fe..83c6e1154 100644 --- a/pkg/console/service/router_rule_test.go +++ b/pkg/console/service/router_rule_test.go @@ -78,6 +78,41 @@ func TestScriptRuleLifecycleAndRollback(t *testing.T) { require.NoError(t, DeleteScriptRuleWithOptions(ctx, name, "", RuleMutationOptions{Author: "admin"})) } +func TestScriptRuleRollbackPreservesOmittedEnabled(t *testing.T) { + ctx := setupRollbackTestEnv(t) + const ( + key = "demo-provider" + name = key + ".script-router" + ) + omitted, err := meshresource.DecodeRule(meshresource.ScriptRouteKind, "", name, ` +configVersion: v3.0 +scope: application +key: demo-provider +type: javascript +script: return invokers; +`) + require.NoError(t, err) + require.NoError(t, CreateScriptRuleWithOptions(ctx, omitted.(*meshresource.ScriptRouteResource), RuleMutationOptions{Author: "admin"})) + + explicitFalse := scriptRouterRule(key, "return invokers;") + explicitFalse.Spec.Enabled = false + require.NoError(t, UpdateScriptRuleWithOptions(ctx, explicitFalse, RuleMutationOptions{Author: "admin"})) + + versions, err := ListRuleVersions(ctx, RuleRef{Kind: meshresource.ScriptRouteKind, Name: name}) + require.NoError(t, err) + require.Len(t, versions.Items, 2) + require.NotEqual(t, versions.Items[0].ContentHash, versions.Items[1].ContentHash) + + _, err = RollbackRuleVersion(ctx, RuleRef{Kind: meshresource.ScriptRouteKind, Name: name}, versions.Items[1].VersionNo, "restore default-enabled script", "admin") + require.NoError(t, err) + + actual, err := GetScriptRule(ctx, name, "") + require.NoError(t, err) + raw, err := meshresource.EncodeRule(actual) + require.NoError(t, err) + require.NotContains(t, string(raw), "enabled:") +} + func TestRouterRuleMutationRejectsInvalidRuntimeContract(t *testing.T) { ctx := setupRollbackTestEnv(t) invalid := scriptRouterRule("demo-provider", "return invokers;") diff --git a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go index e1a29f978..7ca1462f7 100644 --- a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go +++ b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go @@ -193,6 +193,56 @@ func optionalRuleBool(value bool, annotations map[string]string, omittedAnnotati return &value } +// AffinityRuleOptionalFields returns the public values for Affinity's two +// optional booleans. A nil value means that the original config omitted the +// field, rather than that it explicitly set the field to false. +func AffinityRuleOptionalFields(res *AffinityRouteResource) (runtime *bool, enabled *bool) { + if res == nil || res.Spec == nil { + return nil, nil + } + return optionalRuleBool(res.Spec.Runtime, res.Annotations, affinityRuntimeOmittedAnnotation), + optionalRuleBool(res.Spec.Enabled, res.Annotations, affinityEnabledOmittedAnnotation) +} + +// SetAffinityRuleOptionalFields applies public optional values without losing +// the field-presence metadata required to faithfully write the rule back to a +// configuration center. +func SetAffinityRuleOptionalFields(res *AffinityRouteResource, runtime, enabled *bool) { + if res == nil || res.Spec == nil { + return + } + setOptionalRuleBool(&res.Spec.Runtime, &res.Annotations, affinityRuntimeOmittedAnnotation, runtime) + setOptionalRuleBool(&res.Spec.Enabled, &res.Annotations, affinityEnabledOmittedAnnotation, enabled) +} + +// ScriptRuleOptionalEnabled returns nil when enabled was omitted from the +// original Script rule; otherwise it returns the explicit boolean value. +func ScriptRuleOptionalEnabled(res *ScriptRouteResource) *bool { + if res == nil || res.Spec == nil { + return nil + } + return optionalRuleBool(res.Spec.Enabled, res.Annotations, scriptEnabledOmittedAnnotation) +} + +// SetScriptRuleOptionalEnabled applies the public optional enabled field while +// preserving whether it was omitted or explicitly set to false. +func SetScriptRuleOptionalEnabled(res *ScriptRouteResource, enabled *bool) { + if res == nil || res.Spec == nil { + return + } + setOptionalRuleBool(&res.Spec.Enabled, &res.Annotations, scriptEnabledOmittedAnnotation, enabled) +} + +func setOptionalRuleBool(value *bool, annotations *map[string]string, omittedAnnotation string, input *bool) { + if input == nil { + *value = false + markRuleBooleanOmitted(annotations, omittedAnnotation) + return + } + *value = *input + clearRuleBooleanOmitted(annotations, omittedAnnotation) +} + func markRuleBooleanOmitted(annotations *map[string]string, key string) { if *annotations == nil { *annotations = make(map[string]string) diff --git a/pkg/core/versioning/normalize.go b/pkg/core/versioning/normalize.go index 85c70d566..cc10796ce 100644 --- a/pkg/core/versioning/normalize.go +++ b/pkg/core/versioning/normalize.go @@ -35,6 +35,18 @@ import ( // DeleteSpecJSON is the canonical snapshot stored for a rule delete marker. const DeleteSpecJSON = "{}" +const routerRuleSnapshotFormat = "router-rule/v1" + +// routerRuleSnapshot keeps the scalar protobuf spec separate from the +// field-presence information that proto3 cannot represent for optional bools. +// Both members are included in the canonical JSON and therefore in the +// content hash used by diff and rollback checks. +type routerRuleSnapshot struct { + Format string `json:"format"` + Spec json.RawMessage `json:"spec"` + OmittedFields []string `json:"omittedFields,omitempty"` +} + // NormalizeSpec returns the spec hash followed by canonical JSON for stable comparisons. // It does not validate whether the spec is acceptable to the registry. func NormalizeSpec(spec coremodel.ResourceSpec) (specHash string, specJSON string, err error) { @@ -58,15 +70,10 @@ func NormalizeSpec(spec coremodel.ResourceSpec) (specHash string, specJSON strin return "", "", err } } - var v any - if err := json.Unmarshal(raw, &v); err != nil { - return "", "", err - } - canonical, err := json.Marshal(v) + specJSON, err = canonicalJSON(raw) if err != nil { return "", "", err } - specJSON = string(canonical) return HashSpecJSON(specJSON), specJSON, nil } @@ -81,13 +88,27 @@ func NormalizeResource(res coremodel.Resource) (string, string, error) { if res == nil { return "", "", fmt.Errorf("resource is nil") } + if snapshot, ok, err := normalizeRouterRuleSnapshot(res); err != nil { + return "", "", err + } else if ok { + raw, err := json.Marshal(snapshot) + if err != nil { + return "", "", err + } + specJSON, err := canonicalJSON(raw) + if err != nil { + return "", "", err + } + return HashSpecJSON(specJSON), specJSON, nil + } return NormalizeSpec(res.ResourceSpec()) } // ResourceFromSpecJSON rebuilds a typed rule Resource from a stored version's // spec JSON. Used by rollback to re-publish a historical snapshot through the -// normal ResourceManager mutation path. Only the three governor-managed rule -// kinds are supported. protojson is tried first (matching how specs are +// normal ResourceManager mutation path. The special Router rule snapshots also +// restore the field-presence metadata required by their codecs. protojson is +// tried first (matching how specs are // normalized), falling back to plain JSON for resilience. func ResourceFromSpecJSON(kind coremodel.ResourceKind, mesh, ruleName, specJSON string) (coremodel.Resource, error) { switch kind { @@ -116,6 +137,9 @@ func ResourceFromSpecJSON(kind coremodel.ResourceKind, mesh, ruleName, specJSON res.Spec = &spec return res, nil case meshresource.AffinityRouteKind: + if res, handled, err := affinityResourceFromSnapshot(mesh, ruleName, specJSON); handled || err != nil { + return res, err + } res := meshresource.NewAffinityRouteResourceWithAttributes(ruleName, mesh) var spec meshproto.AffinityRoute if err := unmarshalSpec(specJSON, &spec); err != nil { @@ -124,6 +148,9 @@ func ResourceFromSpecJSON(kind coremodel.ResourceKind, mesh, ruleName, specJSON res.Spec = &spec return res, nil case meshresource.ScriptRouteKind: + if res, handled, err := scriptResourceFromSnapshot(mesh, ruleName, specJSON); handled || err != nil { + return res, err + } res := meshresource.NewScriptRouteResourceWithAttributes(ruleName, mesh) var spec meshproto.ScriptRoute if err := unmarshalSpec(specJSON, &spec); err != nil { @@ -136,6 +163,143 @@ func ResourceFromSpecJSON(kind coremodel.ResourceKind, mesh, ruleName, specJSON } } +func normalizeRouterRuleSnapshot(res coremodel.Resource) (routerRuleSnapshot, bool, error) { + var ( + specJSON string + omittedFields []string + err error + ) + switch typed := res.(type) { + case *meshresource.AffinityRouteResource: + if typed == nil || typed.Spec == nil { + return routerRuleSnapshot{}, false, nil + } + _, specJSON, err = NormalizeSpec(typed.Spec) + if err != nil { + return routerRuleSnapshot{}, true, err + } + runtime, enabled := meshresource.AffinityRuleOptionalFields(typed) + if runtime == nil { + omittedFields = append(omittedFields, "runtime") + } + if enabled == nil { + omittedFields = append(omittedFields, "enabled") + } + case *meshresource.ScriptRouteResource: + if typed == nil || typed.Spec == nil { + return routerRuleSnapshot{}, false, nil + } + _, specJSON, err = NormalizeSpec(typed.Spec) + if err != nil { + return routerRuleSnapshot{}, true, err + } + if meshresource.ScriptRuleOptionalEnabled(typed) == nil { + omittedFields = append(omittedFields, "enabled") + } + default: + return routerRuleSnapshot{}, false, nil + } + return routerRuleSnapshot{ + Format: routerRuleSnapshotFormat, + Spec: json.RawMessage(specJSON), + OmittedFields: omittedFields, + }, true, nil +} + +func affinityResourceFromSnapshot(mesh, ruleName, specJSON string) (coremodel.Resource, bool, error) { + snapshot, handled, err := parseRouterRuleSnapshot(specJSON) + if !handled || err != nil { + return nil, handled, err + } + if err := validateOmittedFields(snapshot.OmittedFields, "runtime", "enabled"); err != nil { + return nil, true, err + } + res := meshresource.NewAffinityRouteResourceWithAttributes(ruleName, mesh) + var spec meshproto.AffinityRoute + if err := unmarshalSpec(string(snapshot.Spec), &spec); err != nil { + return nil, true, err + } + res.Spec = &spec + runtime, enabled := &res.Spec.Runtime, &res.Spec.Enabled + if contains(snapshot.OmittedFields, "runtime") { + runtime = nil + } + if contains(snapshot.OmittedFields, "enabled") { + enabled = nil + } + meshresource.SetAffinityRuleOptionalFields(res, runtime, enabled) + return res, true, nil +} + +func scriptResourceFromSnapshot(mesh, ruleName, specJSON string) (coremodel.Resource, bool, error) { + snapshot, handled, err := parseRouterRuleSnapshot(specJSON) + if !handled || err != nil { + return nil, handled, err + } + if err := validateOmittedFields(snapshot.OmittedFields, "enabled"); err != nil { + return nil, true, err + } + res := meshresource.NewScriptRouteResourceWithAttributes(ruleName, mesh) + var spec meshproto.ScriptRoute + if err := unmarshalSpec(string(snapshot.Spec), &spec); err != nil { + return nil, true, err + } + res.Spec = &spec + enabled := &res.Spec.Enabled + if contains(snapshot.OmittedFields, "enabled") { + enabled = nil + } + meshresource.SetScriptRuleOptionalEnabled(res, enabled) + return res, true, nil +} + +func parseRouterRuleSnapshot(specJSON string) (routerRuleSnapshot, bool, error) { + var snapshot routerRuleSnapshot + if err := json.Unmarshal([]byte(specJSON), &snapshot); err != nil { + return routerRuleSnapshot{}, false, err + } + if snapshot.Format == "" { + return routerRuleSnapshot{}, false, nil + } + if snapshot.Format != routerRuleSnapshotFormat { + return routerRuleSnapshot{}, true, fmt.Errorf("unsupported router rule snapshot format %q", snapshot.Format) + } + if len(snapshot.Spec) == 0 || string(snapshot.Spec) == "null" { + return routerRuleSnapshot{}, true, fmt.Errorf("router rule snapshot spec is required") + } + return snapshot, true, nil +} + +func validateOmittedFields(fields []string, allowed ...string) error { + for _, field := range fields { + if !contains(allowed, field) { + return fmt.Errorf("unsupported omitted router rule field %q", field) + } + } + return nil +} + +func contains(fields []string, candidate string) bool { + for _, field := range fields { + if field == candidate { + return true + } + } + return false +} + +func canonicalJSON(raw []byte) (string, error) { + var value any + if err := json.Unmarshal(raw, &value); err != nil { + return "", err + } + canonical, err := json.Marshal(value) + if err != nil { + return "", err + } + return string(canonical), nil +} + func unmarshalSpec(specJSON string, spec proto.Message) error { if err := protojson.Unmarshal([]byte(specJSON), spec); err != nil { if jsonErr := json.Unmarshal([]byte(specJSON), spec); jsonErr != nil { diff --git a/pkg/core/versioning/normalize_test.go b/pkg/core/versioning/normalize_test.go new file mode 100644 index 000000000..1f883e490 --- /dev/null +++ b/pkg/core/versioning/normalize_test.go @@ -0,0 +1,126 @@ +/* + * 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 versioning + +import ( + "testing" + + "github.com/stretchr/testify/require" + + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" +) + +func TestNormalizeResourceDistinguishesOmittedAndExplicitFalseScriptEnabled(t *testing.T) { + omitted := decodeScriptRule(t, ` +configVersion: v3.0 +scope: application +key: demo +type: javascript +script: return invokers; +`) + explicitFalse := decodeScriptRule(t, ` +configVersion: v3.0 +scope: application +key: demo +enabled: false +type: javascript +script: return invokers; +`) + + omittedHash, omittedSnapshot, err := NormalizeResource(omitted) + require.NoError(t, err) + explicitHash, explicitSnapshot, err := NormalizeResource(explicitFalse) + require.NoError(t, err) + require.NotEqual(t, omittedHash, explicitHash) + require.Contains(t, omittedSnapshot, `"omittedFields":["enabled"]`) + require.NotContains(t, explicitSnapshot, `"omittedFields"`) + + restored, err := ResourceFromSpecJSON(meshresource.ScriptRouteKind, "mesh", "demo.script-router", omittedSnapshot) + require.NoError(t, err) + raw, err := meshresource.EncodeRule(restored) + require.NoError(t, err) + require.NotContains(t, string(raw), "enabled:") + + restored, err = ResourceFromSpecJSON(meshresource.ScriptRouteKind, "mesh", "demo.script-router", explicitSnapshot) + require.NoError(t, err) + raw, err = meshresource.EncodeRule(restored) + require.NoError(t, err) + require.Contains(t, string(raw), "enabled: false") +} + +func TestAffinitySnapshotPreservesOptionalRuntimeAndEnabled(t *testing.T) { + omitted, err := meshresource.DecodeRule(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", ` +configVersion: v3.1 +scope: application +key: demo +affinityAware: + key: region + ratio: 50 +`) + require.NoError(t, err) + explicitFalse, err := meshresource.DecodeRule(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", ` +configVersion: v3.1 +scope: application +key: demo +runtime: false +enabled: false +affinityAware: + key: region + ratio: 50 +`) + require.NoError(t, err) + + omittedHash, snapshot, err := NormalizeResource(omitted) + require.NoError(t, err) + explicitHash, explicitSnapshot, err := NormalizeResource(explicitFalse) + require.NoError(t, err) + require.NotEqual(t, omittedHash, explicitHash) + require.Contains(t, snapshot, `"omittedFields":["runtime","enabled"]`) + require.NotContains(t, explicitSnapshot, `"omittedFields"`) + + restored, err := ResourceFromSpecJSON(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", snapshot) + require.NoError(t, err) + raw, err := meshresource.EncodeRule(restored) + require.NoError(t, err) + require.NotContains(t, string(raw), "runtime:") + require.NotContains(t, string(raw), "enabled:") + + restored, err = ResourceFromSpecJSON(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", explicitSnapshot) + require.NoError(t, err) + raw, err = meshresource.EncodeRule(restored) + require.NoError(t, err) + require.Contains(t, string(raw), "runtime: false") + require.Contains(t, string(raw), "enabled: false") +} + +func TestResourceFromSpecJSONAcceptsLegacyScriptSnapshots(t *testing.T) { + resource, err := ResourceFromSpecJSON(meshresource.ScriptRouteKind, "mesh", "demo.script-router", `{ +"configVersion":"v3.0","scope":"application","key":"demo","type":"javascript","script":"return invokers;" +}`) + require.NoError(t, err) + raw, err := meshresource.EncodeRule(resource) + require.NoError(t, err) + require.Contains(t, string(raw), "enabled: false") +} + +func decodeScriptRule(t *testing.T, rule string) *meshresource.ScriptRouteResource { + t.Helper() + resource, err := meshresource.DecodeRule(meshresource.ScriptRouteKind, "mesh", "demo.script-router", rule) + require.NoError(t, err) + return resource.(*meshresource.ScriptRouteResource) +} From b9a63e6b8ae0259ce5235ccf5def2b6dba3848ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Mon, 19 Oct 2026 13:35:17 +0800 Subject: [PATCH 07/21] test(router): cover console API and grouped ZooKeeper paths --- pkg/console/router/router_rule_api_test.go | 337 +++++++++++++++++++++ pkg/discovery/zk/factory_test.go | 56 ++++ pkg/governor/zk/governor_test.go | 42 +++ 3 files changed, 435 insertions(+) create mode 100644 pkg/console/router/router_rule_api_test.go create mode 100644 pkg/discovery/zk/factory_test.go create mode 100644 pkg/governor/zk/governor_test.go diff --git a/pkg/console/router/router_rule_api_test.go b/pkg/console/router/router_rule_api_test.go new file mode 100644 index 000000000..ac40987f8 --- /dev/null +++ b/pkg/console/router/router_rule_api_test.go @@ -0,0 +1,337 @@ +/* + * 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 router + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-contrib/sessions" + "github.com/gin-contrib/sessions/cookie" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + + "github.com/apache/dubbo-admin/pkg/common/bizerror" + appcfg "github.com/apache/dubbo-admin/pkg/config/app" + consolecfg "github.com/apache/dubbo-admin/pkg/config/console" + configauth "github.com/apache/dubbo-admin/pkg/config/console/auth" + versioningcfg "github.com/apache/dubbo-admin/pkg/config/versioning" + consoleauth "github.com/apache/dubbo-admin/pkg/console/auth" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/console/counter" + "github.com/apache/dubbo-admin/pkg/core/governor" + "github.com/apache/dubbo-admin/pkg/core/lock" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store" + "github.com/apache/dubbo-admin/pkg/core/versioning" + memoryst "github.com/apache/dubbo-admin/pkg/store/memory" +) + +type routerRuleAPITestContext struct { + rm manager.ResourceManager + config appcfg.AdminConfig + versioning *versioning.Service +} + +func (c *routerRuleAPITestContext) ResourceManager() manager.ResourceManager { return c.rm } +func (*routerRuleAPITestContext) CounterManager() counter.CounterManager { return nil } +func (c *routerRuleAPITestContext) Config() appcfg.AdminConfig { return c.config } +func (*routerRuleAPITestContext) AppContext() context.Context { return context.Background() } +func (*routerRuleAPITestContext) LockManager() lock.Lock { return nil } +func (c *routerRuleAPITestContext) RuleVersioning() *versioning.Service { return c.versioning } + +var _ consolectx.Context = (*routerRuleAPITestContext)(nil) + +type routerRuleAPITestStoreRouter struct { + stores map[coremodel.ResourceKind]store.ResourceStore +} + +func (r *routerRuleAPITestStoreRouter) ResourceRoute(resource coremodel.Resource) (store.ResourceStore, error) { + return r.ResourceKindRoute(resource.ResourceKind()) +} + +func (r *routerRuleAPITestStoreRouter) ResourceKindRoute(kind coremodel.ResourceKind) (store.ResourceStore, error) { + resourceStore, ok := r.stores[kind] + if !ok { + return nil, fmt.Errorf("resource store not found for %s", kind) + } + return resourceStore, nil +} + +type routerRuleAPITestGovernor struct { + stores map[coremodel.ResourceKind]store.ResourceStore +} + +func (g *routerRuleAPITestGovernor) CreateRule(resource coremodel.Resource) error { + return g.stores[resource.ResourceKind()].Add(resource) +} + +func (g *routerRuleAPITestGovernor) UpdateRule(resource coremodel.Resource) error { + return g.stores[resource.ResourceKind()].Update(resource) +} + +func (g *routerRuleAPITestGovernor) DeleteRule(resource coremodel.Resource) error { + return g.stores[resource.ResourceKind()].Delete(resource) +} + +type routerRuleAPITestGovernorRouter struct { + governor governor.RuleGovernor +} + +func (r *routerRuleAPITestGovernorRouter) ResourceRoute(coremodel.Resource) (governor.RuleGovernor, error) { + return r.governor, nil +} + +func (r *routerRuleAPITestGovernorRouter) ResourceMeshRoute(string) (governor.RuleGovernor, error) { + return r.governor, nil +} + +type routerRuleAPIResponse struct { + Code string `json:"code"` + Data json.RawMessage `json:"data"` +} + +func TestRouterRuleAPIContractPreservesScriptOptionalEnabled(t *testing.T) { + router, sessionCookie := newRouterRuleAPI(t) + const ( + mesh = "api-contract-mesh" + name = "demo.script-router" + ) + path := "/api/v1/script-rule/" + name + "?mesh=" + mesh + + create := mustRouterRuleJSON(t, map[string]any{ + "configVersion": "v3.0", + "scope": "application", + "key": "demo", + "type": "javascript", + "script": "return [invokers[1]];", + }) + created := callRouterRuleAPI(t, router, sessionCookie, http.MethodPost, path, create) + require.NotContains(t, string(created.Data), `"enabled"`) + + detail := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) + require.JSONEq(t, string(created.Data), string(detail.Data)) + require.NotContains(t, string(detail.Data), `"enabled"`) + + search := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, + "/api/v1/script-rule/search?mesh="+mesh+"&keywords="+name, nil) + var searchData struct { + List []struct { + RuleName string `json:"ruleName"` + } `json:"list"` + } + require.NoError(t, json.Unmarshal(search.Data, &searchData)) + require.Len(t, searchData.List, 1) + require.Equal(t, name, searchData.List[0].RuleName) + + updatedPayload := replaceJSONField(t, detail.Data, "script", "return [invokers[0]];") + updated := callRouterRuleAPI(t, router, sessionCookie, http.MethodPut, path, updatedPayload) + require.NotContains(t, string(updated.Data), `"enabled"`) + + versionPath := "/api/v1/script-rule/" + name + "/versions?mesh=" + mesh + versionList := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, versionPath, nil) + var versionData struct { + Items []struct { + VersionNo int64 `json:"versionNo"` + } `json:"items"` + } + require.NoError(t, json.Unmarshal(versionList.Data, &versionData)) + require.Len(t, versionData.Items, 2) + createVersion := versionData.Items[1].VersionNo + + callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, + fmt.Sprintf("/api/v1/script-rule/%s/versions/%d?mesh=%s", name, createVersion, mesh), nil) + callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, + fmt.Sprintf("/api/v1/script-rule/%s/versions/%d/diff?mesh=%s", name, createVersion, mesh), nil) + callRouterRuleAPI(t, router, sessionCookie, http.MethodPost, + fmt.Sprintf("/api/v1/script-rule/%s/versions/%d/rollback?mesh=%s", name, createVersion, mesh), + mustRouterRuleJSON(t, map[string]string{"reason": "verify omitted enabled"})) + + restored := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) + require.NotContains(t, string(restored.Data), `"enabled"`) + var restoredData map[string]any + require.NoError(t, json.Unmarshal(restored.Data, &restoredData)) + require.Equal(t, "return [invokers[1]];", restoredData["script"]) + + deleted := callRouterRuleAPI(t, router, sessionCookie, http.MethodDelete, path, nil) + require.JSONEq(t, `""`, string(deleted.Data)) +} + +func TestRouterRuleAPIContractPreservesAffinityOptionalBooleans(t *testing.T) { + router, sessionCookie := newRouterRuleAPI(t) + const ( + mesh = "api-contract-mesh" + name = "demo.affinity-router" + ) + path := "/api/v1/affinity-rule/" + name + "?mesh=" + mesh + + create := mustRouterRuleJSON(t, map[string]any{ + "configVersion": "v3.1", + "scope": "application", + "key": "demo", + "affinityAware": map[string]any{"key": "region", "ratio": 50}, + }) + created := callRouterRuleAPI(t, router, sessionCookie, http.MethodPost, path, create) + require.NotContains(t, string(created.Data), `"runtime"`) + require.NotContains(t, string(created.Data), `"enabled"`) + + detail := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) + require.JSONEq(t, string(created.Data), string(detail.Data)) + + updatedPayload := replaceJSONField(t, detail.Data, "affinityAware", map[string]any{"key": "region", "ratio": 60}) + updated := callRouterRuleAPI(t, router, sessionCookie, http.MethodPut, path, updatedPayload) + require.NotContains(t, string(updated.Data), `"runtime"`) + require.NotContains(t, string(updated.Data), `"enabled"`) + + versionPath := "/api/v1/affinity-rule/" + name + "/versions?mesh=" + mesh + versionList := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, versionPath, nil) + var versionData struct { + Items []struct { + VersionNo int64 `json:"versionNo"` + } `json:"items"` + } + require.NoError(t, json.Unmarshal(versionList.Data, &versionData)) + require.Len(t, versionData.Items, 2) + callRouterRuleAPI(t, router, sessionCookie, http.MethodPost, + fmt.Sprintf("/api/v1/affinity-rule/%s/versions/%d/rollback?mesh=%s", name, versionData.Items[1].VersionNo, mesh), + mustRouterRuleJSON(t, map[string]string{"reason": "verify optional affinity fields"})) + + restored := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) + require.NotContains(t, string(restored.Data), `"runtime"`) + require.NotContains(t, string(restored.Data), `"enabled"`) + var restoredData struct { + AffinityAware struct { + Ratio int `json:"ratio"` + } `json:"affinityAware"` + } + require.NoError(t, json.Unmarshal(restored.Data, &restoredData)) + require.Equal(t, 50, restoredData.AffinityAware.Ratio) + + callRouterRuleAPI(t, router, sessionCookie, http.MethodDelete, path, nil) +} + +func TestRouterRuleAPIContractRejectsInvalidRuleRequests(t *testing.T) { + router, sessionCookie := newRouterRuleAPI(t) + + wrongSuffix := callRouterRuleAPIExpect(t, router, sessionCookie, http.MethodPost, + "/api/v1/script-rule/demo.affinity-router", mustRouterRuleJSON(t, map[string]any{}), http.StatusBadRequest) + require.Equal(t, string(bizerror.InvalidArgument), wrongSuffix.Code) + + invalidScript := callRouterRuleAPIExpect(t, router, sessionCookie, http.MethodPost, + "/api/v1/script-rule/demo.script-router", mustRouterRuleJSON(t, map[string]any{ + "configVersion": "v3.0", + "scope": "application", + "key": "demo", + "type": "groovy", + "script": "return invokers;", + }), http.StatusOK) + require.Equal(t, string(bizerror.InvalidArgument), invalidScript.Code) +} + +func newRouterRuleAPI(t *testing.T) (*gin.Engine, *http.Cookie) { + t.Helper() + gin.SetMode(gin.TestMode) + affinityStore := memoryst.NewMemoryResourceStore(meshresource.AffinityRouteKind) + scriptStore := memoryst.NewMemoryResourceStore(meshresource.ScriptRouteKind) + versionStore := memoryst.NewMemoryResourceStore(meshresource.RuleVersionKind) + for _, resourceStore := range []store.ManagedResourceStore{affinityStore, scriptStore, versionStore} { + require.NoError(t, resourceStore.Init(nil)) + } + stores := map[coremodel.ResourceKind]store.ResourceStore{ + meshresource.AffinityRouteKind: affinityStore, + meshresource.ScriptRouteKind: scriptStore, + meshresource.RuleVersionKind: versionStore, + } + storeRouter := &routerRuleAPITestStoreRouter{stores: stores} + resourceManager := manager.NewResourceManager( + storeRouter, + &routerRuleAPITestGovernorRouter{governor: &routerRuleAPITestGovernor{stores: stores}}, + ) + ctx := &routerRuleAPITestContext{ + rm: resourceManager, + config: appcfg.AdminConfig{ + Console: &consolecfg.Config{Auth: &configauth.Config{ + Methods: []string{configauth.MethodPassword}, + User: "admin", + Password: "secret", + ExpirationTime: 3600, + Providers: map[string]configauth.ProviderConfig{}, + }}, + RuleVersioning: &versioningcfg.Config{MaxVersionsPerRule: 5}, + }, + versioning: versioning.NewService(5, versioning.NewResourceStoreAdapter(versionStore)), + } + + router := gin.New() + router.Use(sessions.Sessions("session", cookie.NewStore([]byte("router-rule-api-test-secret")))) + router.Use(consoleauth.SessionMiddleware()) + require.NoError(t, InitRouter(router, ctx)) + + login := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewBufferString("user=admin&password=secret")) + login.Header.Set("Content-Type", "application/x-www-form-urlencoded") + loginRecorder := httptest.NewRecorder() + router.ServeHTTP(loginRecorder, login) + require.Equal(t, http.StatusOK, loginRecorder.Code, loginRecorder.Body.String()) + require.NotEmpty(t, loginRecorder.Result().Cookies()) + return router, loginRecorder.Result().Cookies()[0] +} + +func callRouterRuleAPI(t *testing.T, router http.Handler, sessionCookie *http.Cookie, method, path string, body []byte) routerRuleAPIResponse { + t.Helper() + response := callRouterRuleAPIExpect(t, router, sessionCookie, method, path, body, http.StatusOK) + require.Equal(t, "Success", response.Code, "%s %s returned %s", method, path, response.Code) + return response +} + +func callRouterRuleAPIExpect(t *testing.T, router http.Handler, sessionCookie *http.Cookie, method, path string, body []byte, status int) routerRuleAPIResponse { + t.Helper() + request := httptest.NewRequest(method, path, bytes.NewReader(body)) + request.AddCookie(sessionCookie) + if len(body) > 0 { + request.Header.Set("Content-Type", "application/json") + } + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + require.Equal(t, status, recorder.Code, "%s %s: %s", method, path, recorder.Body.String()) + + var response routerRuleAPIResponse + require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &response)) + return response +} + +func mustRouterRuleJSON(t *testing.T, value any) []byte { + t.Helper() + encoded, err := json.Marshal(value) + require.NoError(t, err) + return encoded +} + +func replaceJSONField(t *testing.T, raw json.RawMessage, field string, value any) []byte { + t.Helper() + var object map[string]any + require.NoError(t, json.Unmarshal(raw, &object)) + object[field] = value + return mustRouterRuleJSON(t, object) +} diff --git a/pkg/discovery/zk/factory_test.go b/pkg/discovery/zk/factory_test.go new file mode 100644 index 000000000..059088501 --- /dev/null +++ b/pkg/discovery/zk/factory_test.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 zk + +import ( + "testing" + + "github.com/stretchr/testify/require" + + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" +) + +func TestZKConfigResourcesAcceptOnlyGroupedRulePaths(t *testing.T) { + const ( + mesh = "test-mesh" + name = "demo.affinity-router" + ) + + upsert := toUpsertZKConfigResource(mesh, "/dubbo/config/dubbo/"+name, "rule-content") + require.NotNil(t, upsert) + upsertConfig, ok := upsert.(*meshresource.ZKConfigResource) + require.True(t, ok) + require.Equal(t, name, upsertConfig.Name) + require.Equal(t, "rule-content", upsertConfig.Spec.NodeData) + + deleted := toDeleteZKConfigResource(mesh, "/dubbo/config/dubbo/"+name) + require.NotNil(t, deleted) + deleteConfig, ok := deleted.(*meshresource.ZKConfigResource) + require.True(t, ok) + require.Equal(t, name, deleteConfig.Name) + + for _, path := range []string{ + "/dubbo/config/" + name, + "/dubbo/config/dubbo", + "/dubbo/config/other/" + name, + "/dubbo/config/dubbo/", + } { + require.Nil(t, toUpsertZKConfigResource(mesh, path, "rule-content"), path) + require.Nil(t, toDeleteZKConfigResource(mesh, path), path) + } +} diff --git a/pkg/governor/zk/governor_test.go b/pkg/governor/zk/governor_test.go new file mode 100644 index 000000000..3c669c86b --- /dev/null +++ b/pkg/governor/zk/governor_test.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 zk + +import ( + "testing" + + "github.com/stretchr/testify/require" + + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" +) + +func TestRuleConfigPathUsesGroupedPathForEveryRuleKind(t *testing.T) { + require.Equal(t, "/dubbo/config/dubbo", ruleConfigGroupPath()) + + resources := []coremodel.Resource{ + meshresource.NewDynamicConfigResourceWithAttributes("demo.configurators", "mesh"), + meshresource.NewConditionRouteResourceWithAttributes("demo.condition-router", "mesh"), + meshresource.NewTagRouteResourceWithAttributes("demo.tag-router", "mesh"), + meshresource.NewAffinityRouteResourceWithAttributes("demo.affinity-router", "mesh"), + meshresource.NewScriptRouteResourceWithAttributes("demo.script-router", "mesh"), + } + for _, resource := range resources { + require.Equal(t, "/dubbo/config/dubbo/"+resource.ResourceMeta().Name, ruleConfigPath(resource)) + } +} From c05a1d35eba81832debf2a83182950686f42743a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Mon, 19 Oct 2026 14:00:51 +0800 Subject: [PATCH 08/21] fix(nacos): disable scripts before deletion --- pkg/governor/nacos2/governor.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/pkg/governor/nacos2/governor.go b/pkg/governor/nacos2/governor.go index f964fc149..1fa7aab96 100644 --- a/pkg/governor/nacos2/governor.go +++ b/pkg/governor/nacos2/governor.go @@ -91,6 +91,32 @@ func (g *RuleGovernor) UpdateRule(r coremodel.Resource) error { } func (g *RuleGovernor) DeleteRule(r coremodel.Resource) error { + if script, ok := r.(*meshresource.ScriptRouteResource); ok { + // The Nacos SDK reports DeleteConfig to listeners as an Update with an + // empty payload. Dubbo-Go's ScriptRouter only clears an active script + // when it receives a valid disabled rule, so publish that transition + // before removing the dataId. The subsequent delete still makes the + // configuration absent for new consumers. + disabled := script.DeepCopyObject().(*meshresource.ScriptRouteResource) + disabled.Spec.Enabled = false + rawContent, err := marshalRule(disabled) + if err != nil { + return bizerror.Wrap(err, bizerror.NacosError, + fmt.Sprintf("failed to marshal disabled script rule, res: %s", r.String())) + } + ok, err := g.configClient.PublishConfig(nacosvo.ConfigParam{ + DataId: r.ResourceMeta().Name, + Group: constants.NacosConfigGroup, + Content: string(rawContent), + }) + if err != nil || !ok { + logger.Errorf("failed to disable script rule in %s, res: %s", r.String(), r.ResourceMesh()) + return bizerror.Wrap(err, bizerror.NacosError, + fmt.Sprintf("failed to disable script rule before deletion, res: %s", r.String())) + } + // Keep the ordering deterministic for existing config-center listeners. + <-time.After(2 * time.Second) + } ok, err := g.configClient.DeleteConfig(nacosvo.ConfigParam{ DataId: r.ResourceMeta().Name, Group: constants.NacosConfigGroup, From 3ea537cea45a6f9df4005bb42b984e2e50650ddd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Mon, 19 Oct 2026 14:04:04 +0800 Subject: [PATCH 09/21] fix(router): preserve legacy rule booleans --- .../apis/mesh/v1alpha1/router_rule_codec.go | 9 +++--- .../apis/mesh/v1alpha1/rule_spec_yaml_test.go | 31 +++++++++++++++++++ pkg/governor/nacos2/governor.go | 12 ++----- pkg/governor/zk/governor.go | 12 ++----- 4 files changed, 40 insertions(+), 24 deletions(-) diff --git a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go index 7ca1462f7..f3f10c931 100644 --- a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go +++ b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go @@ -65,9 +65,10 @@ type scriptRouteYAML struct { } // EncodeRule serializes a rule resource using the public Dubbo YAML contract. -// Existing rule kinds fall back to their historical protobuf/YAML encoding; -// Affinity and Script use explicit codecs because their public field names and -// boolean defaults differ from the internal protobuf shape. +// Existing rule kinds use MarshalRuleSpec so their explicit router booleans +// survive protobuf's omitempty tags. Affinity and Script use explicit codecs +// because their public field names and boolean defaults differ from the +// internal protobuf shape. func EncodeRule(r coremodel.Resource) ([]byte, error) { if err := ValidateRule(r); err != nil { return nil, err @@ -100,7 +101,7 @@ func EncodeRule(r coremodel.Resource) ([]byte, error) { if r == nil || r.ResourceSpec() == nil { return nil, invalidRule("rule spec is required") } - value = r.ResourceSpec() + return MarshalRuleSpec(r.ResourceSpec()) } data, err := yaml.Marshal(value) if err != nil { diff --git a/pkg/core/resource/apis/mesh/v1alpha1/rule_spec_yaml_test.go b/pkg/core/resource/apis/mesh/v1alpha1/rule_spec_yaml_test.go index be07a9bc9..56d4a746f 100644 --- a/pkg/core/resource/apis/mesh/v1alpha1/rule_spec_yaml_test.go +++ b/pkg/core/resource/apis/mesh/v1alpha1/rule_spec_yaml_test.go @@ -73,6 +73,37 @@ func TestMarshalRuleSpecPreservesRouterBooleans(t *testing.T) { } } +func TestEncodeRulePreservesExistingRouterBooleans(t *testing.T) { + condition := NewConditionRouteResourceWithAttributes("demo.condition-router", "mesh") + condition.Spec = &meshproto.ConditionRoute{ + ConfigVersion: "v3.0", Key: "demo", Scope: "application", + Enabled: false, Force: false, Runtime: false, + Conditions: []string{"=>host!=192.0.2.1"}, + } + tag := NewTagRouteResourceWithAttributes("demo.tag-router", "mesh") + tag.Spec = &meshproto.TagRoute{ + ConfigVersion: "v3.0", Key: "demo", + Enabled: false, Force: false, Runtime: false, + Tags: []*meshproto.Tag{{Name: "gray", Addresses: []string{"192.0.2.1:20880"}}}, + } + + for name, resource := range map[string]coremodel.Resource{ + "condition": condition, + "tag": tag, + } { + t.Run(name, func(t *testing.T) { + raw, err := EncodeRule(resource) + require.NoError(t, err) + var fields map[string]any + require.NoError(t, yaml.Unmarshal(raw, &fields)) + for _, field := range []string{"enabled", "force", "runtime"} { + require.Contains(t, fields, field, "%s must not be omitted: %s", field, raw) + require.Equal(t, false, fields[field]) + } + }) + } +} + func TestMarshalRuleSpecOtherKindsUnchanged(t *testing.T) { spec := &meshproto.AffinityRoute{ConfigVersion: "v3.1", Enabled: false, Runtime: false} want, err := yaml.Marshal(spec) diff --git a/pkg/governor/nacos2/governor.go b/pkg/governor/nacos2/governor.go index 1fa7aab96..8d78a6fed 100644 --- a/pkg/governor/nacos2/governor.go +++ b/pkg/governor/nacos2/governor.go @@ -26,7 +26,6 @@ import ( nacosnamingclient "github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client" nacosvo "github.com/nacos-group/nacos-sdk-go/v2/vo" "k8s.io/client-go/tools/cache" - "sigs.k8s.io/yaml" "github.com/apache/dubbo-admin/pkg/common/bizerror" "github.com/apache/dubbo-admin/pkg/common/constants" @@ -65,7 +64,7 @@ func NewNacos2Governor( } func (g *RuleGovernor) CreateRule(r coremodel.Resource) error { - rawContent, err := marshalRule(r) + rawContent, err := meshresource.EncodeRule(r) if err != nil { return bizerror.Wrap(err, bizerror.NacosError, fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) @@ -99,7 +98,7 @@ func (g *RuleGovernor) DeleteRule(r coremodel.Resource) error { // configuration absent for new consumers. disabled := script.DeepCopyObject().(*meshresource.ScriptRouteResource) disabled.Spec.Enabled = false - rawContent, err := marshalRule(disabled) + rawContent, err := meshresource.EncodeRule(disabled) if err != nil { return bizerror.Wrap(err, bizerror.NacosError, fmt.Sprintf("failed to marshal disabled script rule, res: %s", r.String())) @@ -204,13 +203,6 @@ func (g *RuleGovernor) GetConfigAndUpdateStore(r coremodel.Resource) { g.emitter.Send(events.NewResourceChangedEvent(cache.Added, nil, res)) } -func marshalRule(r coremodel.Resource) ([]byte, error) { - if r.ResourceKind() == meshresource.AffinityRouteKind || r.ResourceKind() == meshresource.ScriptRouteKind { - return meshresource.EncodeRule(r) - } - return yaml.Marshal(r.ResourceSpec()) -} - func (g *RuleGovernor) mesh() string { return g.cfg.ID } diff --git a/pkg/governor/zk/governor.go b/pkg/governor/zk/governor.go index 3f2895e70..b92502690 100644 --- a/pkg/governor/zk/governor.go +++ b/pkg/governor/zk/governor.go @@ -22,7 +22,6 @@ import ( "strings" "github.com/dubbogo/go-zookeeper/zk" - "sigs.k8s.io/yaml" "github.com/apache/dubbo-admin/pkg/common/bizerror" "github.com/apache/dubbo-admin/pkg/common/constants" @@ -62,7 +61,7 @@ func NewZKRuleGovernor(cfg *discoverycfg.Config, router store.Router, emitter ev func (g *RuleGovernor) CreateRule(r coremodel.Resource) error { path := ruleConfigPath(r) - content, err := marshalRule(r) + content, err := meshresource.EncodeRule(r) if err != nil { return bizerror.Wrap(err, bizerror.YamlError, fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) @@ -92,7 +91,7 @@ func (g *RuleGovernor) CreateRule(r coremodel.Resource) error { func (g *RuleGovernor) UpdateRule(r coremodel.Resource) error { path := ruleConfigPath(r) - content, err := marshalRule(r) + content, err := meshresource.EncodeRule(r) if err != nil { return bizerror.Wrap(err, bizerror.YamlError, fmt.Sprintf("failed to marshal resource spec, res: %s", r.String())) @@ -138,13 +137,6 @@ func (g *RuleGovernor) DeleteRule(r coremodel.Resource) error { return nil } -func marshalRule(r coremodel.Resource) ([]byte, error) { - if r.ResourceKind() == meshresource.AffinityRouteKind || r.ResourceKind() == meshresource.ScriptRouteKind { - return meshresource.EncodeRule(r) - } - return yaml.Marshal(r.ResourceSpec()) -} - func ruleConfigPath(r coremodel.Resource) string { return ruleConfigGroupPath() + "/" + r.ResourceMeta().Name } From 64f05c898febd41815a878073f0517af6a886b69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Wed, 21 Oct 2026 13:52:22 +0800 Subject: [PATCH 10/21] fix: always publish script rule enabled --- pkg/console/handler/router_rule.go | 7 +++- pkg/console/model/router_rule_test.go | 9 ++--- pkg/console/router/router_rule_api_test.go | 10 +++--- pkg/console/service/router_rule_test.go | 4 +-- .../apis/mesh/v1alpha1/router_rule_codec.go | 34 ++++++++++++------- .../mesh/v1alpha1/router_rule_codec_test.go | 4 +-- pkg/core/versioning/normalize.go | 28 ++++++++++++--- pkg/core/versioning/normalize_test.go | 4 +-- pkg/governor/nacos2/governor.go | 3 +- 9 files changed, 69 insertions(+), 34 deletions(-) diff --git a/pkg/console/handler/router_rule.go b/pkg/console/handler/router_rule.go index 4da19d98d..3de8bb55e 100644 --- a/pkg/console/handler/router_rule.go +++ b/pkg/console/handler/router_rule.go @@ -185,7 +185,12 @@ func mutateScriptRule(ctx consolectx.Context, update bool) gin.HandlerFunc { name, mesh := c.Param("ruleName"), c.Query("mesh") res := meshresource.NewScriptRouteResourceWithAttributes(name, mesh) res.Spec = input.ToProto() - meshresource.SetScriptRuleOptionalEnabled(res, input.Enabled) + enabled := input.Enabled + if enabled == nil { + defaultEnabled := true + enabled = &defaultEnabled + } + meshresource.SetScriptRuleOptionalEnabled(res, enabled) if err := meshresource.ValidateRule(res); err != nil { util.HandleArgumentError(c, err) return diff --git a/pkg/console/model/router_rule_test.go b/pkg/console/model/router_rule_test.go index 34744edc5..4dcbcfe3e 100644 --- a/pkg/console/model/router_rule_test.go +++ b/pkg/console/model/router_rule_test.go @@ -26,7 +26,7 @@ import ( meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" ) -func TestScriptRuleDetailRoundTripPreservesOmittedEnabled(t *testing.T) { +func TestScriptRuleDetailRoundTripNormalizesOmittedEnabledToTrue(t *testing.T) { source, err := meshresource.DecodeRule(meshresource.ScriptRouteKind, "mesh", "demo.script-router", ` configVersion: v3.0 scope: application @@ -37,17 +37,18 @@ script: return invokers; require.NoError(t, err) input := GenScriptRuleResp(source.(*meshresource.ScriptRouteResource)).Data.(ScriptRuleInput) - require.Nil(t, input.Enabled) + require.NotNil(t, input.Enabled) + require.True(t, *input.Enabled) body, err := json.Marshal(input) require.NoError(t, err) - require.NotContains(t, string(body), `"enabled"`) + require.Contains(t, string(body), `"enabled":true`) restored := meshresource.NewScriptRouteResourceWithAttributes("demo.script-router", "mesh") restored.Spec = input.ToProto() meshresource.SetScriptRuleOptionalEnabled(restored, input.Enabled) raw, err := meshresource.EncodeRule(restored) require.NoError(t, err) - require.NotContains(t, string(raw), "enabled:") + require.Contains(t, string(raw), "enabled: true") } func TestAffinityRuleDetailRoundTripPreservesOptionalBooleans(t *testing.T) { diff --git a/pkg/console/router/router_rule_api_test.go b/pkg/console/router/router_rule_api_test.go index ac40987f8..a1f513cbe 100644 --- a/pkg/console/router/router_rule_api_test.go +++ b/pkg/console/router/router_rule_api_test.go @@ -113,7 +113,7 @@ type routerRuleAPIResponse struct { Data json.RawMessage `json:"data"` } -func TestRouterRuleAPIContractPreservesScriptOptionalEnabled(t *testing.T) { +func TestRouterRuleAPIContractNormalizesScriptEnabled(t *testing.T) { router, sessionCookie := newRouterRuleAPI(t) const ( mesh = "api-contract-mesh" @@ -129,11 +129,11 @@ func TestRouterRuleAPIContractPreservesScriptOptionalEnabled(t *testing.T) { "script": "return [invokers[1]];", }) created := callRouterRuleAPI(t, router, sessionCookie, http.MethodPost, path, create) - require.NotContains(t, string(created.Data), `"enabled"`) + require.Contains(t, string(created.Data), `"enabled":true`) detail := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) require.JSONEq(t, string(created.Data), string(detail.Data)) - require.NotContains(t, string(detail.Data), `"enabled"`) + require.Contains(t, string(detail.Data), `"enabled":true`) search := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, "/api/v1/script-rule/search?mesh="+mesh+"&keywords="+name, nil) @@ -148,7 +148,7 @@ func TestRouterRuleAPIContractPreservesScriptOptionalEnabled(t *testing.T) { updatedPayload := replaceJSONField(t, detail.Data, "script", "return [invokers[0]];") updated := callRouterRuleAPI(t, router, sessionCookie, http.MethodPut, path, updatedPayload) - require.NotContains(t, string(updated.Data), `"enabled"`) + require.Contains(t, string(updated.Data), `"enabled":true`) versionPath := "/api/v1/script-rule/" + name + "/versions?mesh=" + mesh versionList := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, versionPath, nil) @@ -170,7 +170,7 @@ func TestRouterRuleAPIContractPreservesScriptOptionalEnabled(t *testing.T) { mustRouterRuleJSON(t, map[string]string{"reason": "verify omitted enabled"})) restored := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) - require.NotContains(t, string(restored.Data), `"enabled"`) + require.Contains(t, string(restored.Data), `"enabled":true`) var restoredData map[string]any require.NoError(t, json.Unmarshal(restored.Data, &restoredData)) require.Equal(t, "return [invokers[1]];", restoredData["script"]) diff --git a/pkg/console/service/router_rule_test.go b/pkg/console/service/router_rule_test.go index 83c6e1154..7ebeb1728 100644 --- a/pkg/console/service/router_rule_test.go +++ b/pkg/console/service/router_rule_test.go @@ -78,7 +78,7 @@ func TestScriptRuleLifecycleAndRollback(t *testing.T) { require.NoError(t, DeleteScriptRuleWithOptions(ctx, name, "", RuleMutationOptions{Author: "admin"})) } -func TestScriptRuleRollbackPreservesOmittedEnabled(t *testing.T) { +func TestScriptRuleRollbackNormalizesOmittedEnabledToTrue(t *testing.T) { ctx := setupRollbackTestEnv(t) const ( key = "demo-provider" @@ -110,7 +110,7 @@ script: return invokers; require.NoError(t, err) raw, err := meshresource.EncodeRule(actual) require.NoError(t, err) - require.NotContains(t, string(raw), "enabled:") + require.Contains(t, string(raw), "enabled: true") } func TestRouterRuleMutationRejectsInvalidRuntimeContract(t *testing.T) { diff --git a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go index f3f10c931..d1b06a423 100644 --- a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go +++ b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go @@ -35,7 +35,6 @@ import ( const ( affinityRuntimeOmittedAnnotation = "dubbo.apache.org/affinity-runtime-omitted" affinityEnabledOmittedAnnotation = "dubbo.apache.org/affinity-enabled-omitted" - scriptEnabledOmittedAnnotation = "dubbo.apache.org/script-enabled-omitted" ) // The protobuf field is named affinity for historical/internal reasons. The @@ -93,9 +92,12 @@ func EncodeRule(r coremodel.Resource) ([]byte, error) { ConfigVersion: typed.Spec.ConfigVersion, Scope: typed.Spec.Scope, Key: typed.Spec.Key, - Enabled: optionalRuleBool(typed.Spec.Enabled, typed.Annotations, scriptEnabledOmittedAnnotation), - Type: typed.Spec.Type, - Script: typed.Spec.Script, + // Dubbo-Go's ScriptRouter dereferences Enabled, so Script rules must + // always publish this field. Unlike Affinity rules, enabled is not + // optional in the Script rule contract. + Enabled: &typed.Spec.Enabled, + Type: typed.Spec.Type, + Script: typed.Spec.Script, } default: if r == nil || r.ResourceSpec() == nil { @@ -162,11 +164,12 @@ func DecodeRule(kind coremodel.ResourceKind, mesh, name, data string) (coremodel res.Spec.ConfigVersion = external.ConfigVersion res.Spec.Scope = external.Scope res.Spec.Key = external.Key + // Treat old configurations which omit enabled as enabled. This keeps + // Console's next write compatible with ScriptRouter by making the + // normalized value explicit in the published YAML. + res.Spec.Enabled = true if external.Enabled != nil { res.Spec.Enabled = *external.Enabled - clearRuleBooleanOmitted(&res.Annotations, scriptEnabledOmittedAnnotation) - } else { - markRuleBooleanOmitted(&res.Annotations, scriptEnabledOmittedAnnotation) } res.Spec.Type = external.Type res.Spec.Script = external.Script @@ -216,22 +219,27 @@ func SetAffinityRuleOptionalFields(res *AffinityRouteResource, runtime, enabled setOptionalRuleBool(&res.Spec.Enabled, &res.Annotations, affinityEnabledOmittedAnnotation, enabled) } -// ScriptRuleOptionalEnabled returns nil when enabled was omitted from the -// original Script rule; otherwise it returns the explicit boolean value. +// ScriptRuleOptionalEnabled returns the normalized Script enabled value. +// ScriptRouter requires this field, so an omitted value is normalized to true. func ScriptRuleOptionalEnabled(res *ScriptRouteResource) *bool { if res == nil || res.Spec == nil { return nil } - return optionalRuleBool(res.Spec.Enabled, res.Annotations, scriptEnabledOmittedAnnotation) + return &res.Spec.Enabled } -// SetScriptRuleOptionalEnabled applies the public optional enabled field while -// preserving whether it was omitted or explicitly set to false. +// SetScriptRuleOptionalEnabled applies the public enabled field. A missing +// input is normalized to true so all Script rule writes remain safe for +// ScriptRouter consumers. func SetScriptRuleOptionalEnabled(res *ScriptRouteResource, enabled *bool) { if res == nil || res.Spec == nil { return } - setOptionalRuleBool(&res.Spec.Enabled, &res.Annotations, scriptEnabledOmittedAnnotation, enabled) + normalized := true + if enabled != nil { + normalized = *enabled + } + res.Spec.Enabled = normalized } func setOptionalRuleBool(value *bool, annotations *map[string]string, omittedAnnotation string, input *bool) { diff --git a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go index 8ff5d11d8..f9fdce51b 100644 --- a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go +++ b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go @@ -63,7 +63,7 @@ func TestScriptRuleCodecAndValidation(t *testing.T) { require.Error(t, ValidateRule(res)) } -func TestRouterRuleCodecPreservesOmittedBooleans(t *testing.T) { +func TestRouterRuleCodecPreservesOptionalAffinityBooleansAndNormalizesScriptEnabled(t *testing.T) { affinityYAML := "configVersion: v3.1\n" + "scope: application\n" + "key: demo\n" + @@ -90,7 +90,7 @@ func TestRouterRuleCodecPreservesOmittedBooleans(t *testing.T) { require.NoError(t, err) scriptRaw, err := EncodeRule(script) require.NoError(t, err) - require.NotContains(t, string(scriptRaw), "enabled:") + require.Contains(t, string(scriptRaw), "enabled: true") } func TestRouterRuleCodecPreservesExplicitFalseBooleans(t *testing.T) { diff --git a/pkg/core/versioning/normalize.go b/pkg/core/versioning/normalize.go index cc10796ce..5c9207aab 100644 --- a/pkg/core/versioning/normalize.go +++ b/pkg/core/versioning/normalize.go @@ -47,6 +47,18 @@ type routerRuleSnapshot struct { OmittedFields []string `json:"omittedFields,omitempty"` } +// scriptRouteSnapshotSpec deliberately does not use protojson because +// proto3 omits false scalars. Script enabled must retain an explicit false +// across history and rollback. +type scriptRouteSnapshotSpec struct { + ConfigVersion string `json:"configVersion"` + Scope string `json:"scope"` + Key string `json:"key"` + Enabled bool `json:"enabled"` + Type string `json:"type"` + Script string `json:"script"` +} + // NormalizeSpec returns the spec hash followed by canonical JSON for stable comparisons. // It does not validate whether the spec is acceptable to the registry. func NormalizeSpec(spec coremodel.ResourceSpec) (specHash string, specJSON string, err error) { @@ -189,13 +201,21 @@ func normalizeRouterRuleSnapshot(res coremodel.Resource) (routerRuleSnapshot, bo if typed == nil || typed.Spec == nil { return routerRuleSnapshot{}, false, nil } - _, specJSON, err = NormalizeSpec(typed.Spec) + raw, marshalErr := json.Marshal(scriptRouteSnapshotSpec{ + ConfigVersion: typed.Spec.ConfigVersion, + Scope: typed.Spec.Scope, + Key: typed.Spec.Key, + Enabled: typed.Spec.Enabled, + Type: typed.Spec.Type, + Script: typed.Spec.Script, + }) + if marshalErr != nil { + return routerRuleSnapshot{}, true, marshalErr + } + specJSON, err = canonicalJSON(raw) if err != nil { return routerRuleSnapshot{}, true, err } - if meshresource.ScriptRuleOptionalEnabled(typed) == nil { - omittedFields = append(omittedFields, "enabled") - } default: return routerRuleSnapshot{}, false, nil } diff --git a/pkg/core/versioning/normalize_test.go b/pkg/core/versioning/normalize_test.go index 1f883e490..64e8ab445 100644 --- a/pkg/core/versioning/normalize_test.go +++ b/pkg/core/versioning/normalize_test.go @@ -47,14 +47,14 @@ script: return invokers; explicitHash, explicitSnapshot, err := NormalizeResource(explicitFalse) require.NoError(t, err) require.NotEqual(t, omittedHash, explicitHash) - require.Contains(t, omittedSnapshot, `"omittedFields":["enabled"]`) + require.NotContains(t, omittedSnapshot, `"omittedFields"`) require.NotContains(t, explicitSnapshot, `"omittedFields"`) restored, err := ResourceFromSpecJSON(meshresource.ScriptRouteKind, "mesh", "demo.script-router", omittedSnapshot) require.NoError(t, err) raw, err := meshresource.EncodeRule(restored) require.NoError(t, err) - require.NotContains(t, string(raw), "enabled:") + require.Contains(t, string(raw), "enabled: true") restored, err = ResourceFromSpecJSON(meshresource.ScriptRouteKind, "mesh", "demo.script-router", explicitSnapshot) require.NoError(t, err) diff --git a/pkg/governor/nacos2/governor.go b/pkg/governor/nacos2/governor.go index 8d78a6fed..9df19b364 100644 --- a/pkg/governor/nacos2/governor.go +++ b/pkg/governor/nacos2/governor.go @@ -97,7 +97,8 @@ func (g *RuleGovernor) DeleteRule(r coremodel.Resource) error { // before removing the dataId. The subsequent delete still makes the // configuration absent for new consumers. disabled := script.DeepCopyObject().(*meshresource.ScriptRouteResource) - disabled.Spec.Enabled = false + disabledEnabled := false + meshresource.SetScriptRuleOptionalEnabled(disabled, &disabledEnabled) rawContent, err := meshresource.EncodeRule(disabled) if err != nil { return bizerror.Wrap(err, bizerror.NacosError, From bc4febc64931a673ede17627234dd2572c2e4916 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Wed, 21 Oct 2026 16:23:40 +0800 Subject: [PATCH 11/21] fix: normalize affinity rule enabled --- pkg/console/handler/router_rule.go | 17 ++++++----- pkg/console/model/router_rule_test.go | 9 +++--- pkg/console/router/router_rule_api_test.go | 8 ++--- .../apis/mesh/v1alpha1/router_rule_codec.go | 30 ++++++++++--------- .../mesh/v1alpha1/router_rule_codec_test.go | 6 ++-- pkg/core/versioning/normalize.go | 24 +++++++++++---- pkg/core/versioning/normalize_test.go | 4 +-- 7 files changed, 59 insertions(+), 39 deletions(-) diff --git a/pkg/console/handler/router_rule.go b/pkg/console/handler/router_rule.go index 3de8bb55e..479584ac1 100644 --- a/pkg/console/handler/router_rule.go +++ b/pkg/console/handler/router_rule.go @@ -89,7 +89,7 @@ func mutateAffinityRule(ctx consolectx.Context, update bool) gin.HandlerFunc { name, mesh := c.Param("ruleName"), c.Query("mesh") res := meshresource.NewAffinityRouteResourceWithAttributes(name, mesh) res.Spec = input.ToProto() - meshresource.SetAffinityRuleOptionalFields(res, input.Runtime, input.Enabled) + meshresource.SetAffinityRuleOptionalFields(res, input.Runtime, normalizedRuleEnabled(input.Enabled)) if err := meshresource.ValidateRule(res); err != nil { util.HandleArgumentError(c, err) return @@ -185,12 +185,7 @@ func mutateScriptRule(ctx consolectx.Context, update bool) gin.HandlerFunc { name, mesh := c.Param("ruleName"), c.Query("mesh") res := meshresource.NewScriptRouteResourceWithAttributes(name, mesh) res.Spec = input.ToProto() - enabled := input.Enabled - if enabled == nil { - defaultEnabled := true - enabled = &defaultEnabled - } - meshresource.SetScriptRuleOptionalEnabled(res, enabled) + meshresource.SetScriptRuleOptionalEnabled(res, normalizedRuleEnabled(input.Enabled)) if err := meshresource.ValidateRule(res); err != nil { util.HandleArgumentError(c, err) return @@ -238,3 +233,11 @@ func validRouterRuleName(c *gin.Context, suffix string) bool { c.JSON(http.StatusBadRequest, model.NewBizErrorResp(err)) return false } + +func normalizedRuleEnabled(enabled *bool) *bool { + if enabled != nil { + return enabled + } + defaultEnabled := true + return &defaultEnabled +} diff --git a/pkg/console/model/router_rule_test.go b/pkg/console/model/router_rule_test.go index 4dcbcfe3e..d6a74d82b 100644 --- a/pkg/console/model/router_rule_test.go +++ b/pkg/console/model/router_rule_test.go @@ -51,7 +51,7 @@ script: return invokers; require.Contains(t, string(raw), "enabled: true") } -func TestAffinityRuleDetailRoundTripPreservesOptionalBooleans(t *testing.T) { +func TestAffinityRuleDetailRoundTripPreservesOptionalRuntimeAndNormalizesEnabled(t *testing.T) { source, err := meshresource.DecodeRule(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", ` configVersion: v3.1 scope: application @@ -64,11 +64,12 @@ affinityAware: input := GenAffinityRuleResp(source.(*meshresource.AffinityRouteResource)).Data.(AffinityRuleInput) require.Nil(t, input.Runtime) - require.Nil(t, input.Enabled) + require.NotNil(t, input.Enabled) + require.True(t, *input.Enabled) body, err := json.Marshal(input) require.NoError(t, err) require.NotContains(t, string(body), `"runtime"`) - require.NotContains(t, string(body), `"enabled"`) + require.Contains(t, string(body), `"enabled":true`) restored := meshresource.NewAffinityRouteResourceWithAttributes("demo.affinity-router", "mesh") restored.Spec = input.ToProto() @@ -76,7 +77,7 @@ affinityAware: raw, err := meshresource.EncodeRule(restored) require.NoError(t, err) require.NotContains(t, string(raw), "runtime:") - require.NotContains(t, string(raw), "enabled:") + require.Contains(t, string(raw), "enabled: true") } func TestScriptRuleDetailRoundTripPreservesExplicitFalse(t *testing.T) { diff --git a/pkg/console/router/router_rule_api_test.go b/pkg/console/router/router_rule_api_test.go index a1f513cbe..6cefcfbcf 100644 --- a/pkg/console/router/router_rule_api_test.go +++ b/pkg/console/router/router_rule_api_test.go @@ -179,7 +179,7 @@ func TestRouterRuleAPIContractNormalizesScriptEnabled(t *testing.T) { require.JSONEq(t, `""`, string(deleted.Data)) } -func TestRouterRuleAPIContractPreservesAffinityOptionalBooleans(t *testing.T) { +func TestRouterRuleAPIContractNormalizesAffinityEnabled(t *testing.T) { router, sessionCookie := newRouterRuleAPI(t) const ( mesh = "api-contract-mesh" @@ -195,7 +195,7 @@ func TestRouterRuleAPIContractPreservesAffinityOptionalBooleans(t *testing.T) { }) created := callRouterRuleAPI(t, router, sessionCookie, http.MethodPost, path, create) require.NotContains(t, string(created.Data), `"runtime"`) - require.NotContains(t, string(created.Data), `"enabled"`) + require.Contains(t, string(created.Data), `"enabled":true`) detail := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) require.JSONEq(t, string(created.Data), string(detail.Data)) @@ -203,7 +203,7 @@ func TestRouterRuleAPIContractPreservesAffinityOptionalBooleans(t *testing.T) { updatedPayload := replaceJSONField(t, detail.Data, "affinityAware", map[string]any{"key": "region", "ratio": 60}) updated := callRouterRuleAPI(t, router, sessionCookie, http.MethodPut, path, updatedPayload) require.NotContains(t, string(updated.Data), `"runtime"`) - require.NotContains(t, string(updated.Data), `"enabled"`) + require.Contains(t, string(updated.Data), `"enabled":true`) versionPath := "/api/v1/affinity-rule/" + name + "/versions?mesh=" + mesh versionList := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, versionPath, nil) @@ -220,7 +220,7 @@ func TestRouterRuleAPIContractPreservesAffinityOptionalBooleans(t *testing.T) { restored := callRouterRuleAPI(t, router, sessionCookie, http.MethodGet, path, nil) require.NotContains(t, string(restored.Data), `"runtime"`) - require.NotContains(t, string(restored.Data), `"enabled"`) + require.Contains(t, string(restored.Data), `"enabled":true`) var restoredData struct { AffinityAware struct { Ratio int `json:"ratio"` diff --git a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go index d1b06a423..b9ce6cf30 100644 --- a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go +++ b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go @@ -34,7 +34,6 @@ import ( // is copied and persisted by the existing resource store implementations. const ( affinityRuntimeOmittedAnnotation = "dubbo.apache.org/affinity-runtime-omitted" - affinityEnabledOmittedAnnotation = "dubbo.apache.org/affinity-enabled-omitted" ) // The protobuf field is named affinity for historical/internal reasons. The @@ -67,7 +66,8 @@ type scriptRouteYAML struct { // Existing rule kinds use MarshalRuleSpec so their explicit router booleans // survive protobuf's omitempty tags. Affinity and Script use explicit codecs // because their public field names and boolean defaults differ from the -// internal protobuf shape. +// internal protobuf shape. Their Enabled fields are always written because +// consumers do not safely handle omitted values. func EncodeRule(r coremodel.Resource) ([]byte, error) { if err := ValidateRule(r); err != nil { return nil, err @@ -84,7 +84,7 @@ func EncodeRule(r coremodel.Resource) ([]byte, error) { Scope: typed.Spec.Scope, Key: typed.Spec.Key, Runtime: optionalRuleBool(typed.Spec.Runtime, typed.Annotations, affinityRuntimeOmittedAnnotation), - Enabled: optionalRuleBool(typed.Spec.Enabled, typed.Annotations, affinityEnabledOmittedAnnotation), + Enabled: &typed.Spec.Enabled, AffinityAware: aware, } case *ScriptRouteResource: @@ -139,6 +139,7 @@ func DecodeRule(kind coremodel.ResourceKind, mesh, name, data string) (coremodel res.Spec.ConfigVersion = external.ConfigVersion res.Spec.Scope = external.Scope res.Spec.Key = external.Key + res.Spec.Enabled = true if external.Runtime != nil { res.Spec.Runtime = *external.Runtime clearRuleBooleanOmitted(&res.Annotations, affinityRuntimeOmittedAnnotation) @@ -147,9 +148,6 @@ func DecodeRule(kind coremodel.ResourceKind, mesh, name, data string) (coremodel } if external.Enabled != nil { res.Spec.Enabled = *external.Enabled - clearRuleBooleanOmitted(&res.Annotations, affinityEnabledOmittedAnnotation) - } else { - markRuleBooleanOmitted(&res.Annotations, affinityEnabledOmittedAnnotation) } if err := ValidateRule(res); err != nil { return nil, err @@ -197,26 +195,30 @@ func optionalRuleBool(value bool, annotations map[string]string, omittedAnnotati return &value } -// AffinityRuleOptionalFields returns the public values for Affinity's two -// optional booleans. A nil value means that the original config omitted the -// field, rather than that it explicitly set the field to false. +// AffinityRuleOptionalFields returns the public Affinity values. Runtime is +// optional, while Enabled is normalized because an omitted enabled field can +// silently disable the rule in consumers. func AffinityRuleOptionalFields(res *AffinityRouteResource) (runtime *bool, enabled *bool) { if res == nil || res.Spec == nil { return nil, nil } return optionalRuleBool(res.Spec.Runtime, res.Annotations, affinityRuntimeOmittedAnnotation), - optionalRuleBool(res.Spec.Enabled, res.Annotations, affinityEnabledOmittedAnnotation) + &res.Spec.Enabled } -// SetAffinityRuleOptionalFields applies public optional values without losing -// the field-presence metadata required to faithfully write the rule back to a -// configuration center. +// SetAffinityRuleOptionalFields applies public Affinity values. Runtime keeps +// its field-presence metadata, but a missing Enabled value is normalized to +// true before the rule can be published. func SetAffinityRuleOptionalFields(res *AffinityRouteResource, runtime, enabled *bool) { if res == nil || res.Spec == nil { return } setOptionalRuleBool(&res.Spec.Runtime, &res.Annotations, affinityRuntimeOmittedAnnotation, runtime) - setOptionalRuleBool(&res.Spec.Enabled, &res.Annotations, affinityEnabledOmittedAnnotation, enabled) + normalizedEnabled := true + if enabled != nil { + normalizedEnabled = *enabled + } + res.Spec.Enabled = normalizedEnabled } // ScriptRuleOptionalEnabled returns the normalized Script enabled value. diff --git a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go index f9fdce51b..e49ccd60f 100644 --- a/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go +++ b/pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec_test.go @@ -63,7 +63,7 @@ func TestScriptRuleCodecAndValidation(t *testing.T) { require.Error(t, ValidateRule(res)) } -func TestRouterRuleCodecPreservesOptionalAffinityBooleansAndNormalizesScriptEnabled(t *testing.T) { +func TestRouterRuleCodecPreservesOptionalAffinityRuntimeAndNormalizesEnabled(t *testing.T) { affinityYAML := "configVersion: v3.1\n" + "scope: application\n" + "key: demo\n" + @@ -75,11 +75,11 @@ func TestRouterRuleCodecPreservesOptionalAffinityBooleansAndNormalizesScriptEnab affinityRaw, err := EncodeRule(affinity) require.NoError(t, err) require.NotContains(t, string(affinityRaw), "runtime:") - require.NotContains(t, string(affinityRaw), "enabled:") + require.Contains(t, string(affinityRaw), "enabled: true") copyRaw, err := EncodeRule(affinity.(*AffinityRouteResource).DeepCopyObject().(*AffinityRouteResource)) require.NoError(t, err) require.NotContains(t, string(copyRaw), "runtime:") - require.NotContains(t, string(copyRaw), "enabled:") + require.Contains(t, string(copyRaw), "enabled: true") scriptYAML := "configVersion: v3.0\n" + "scope: application\n" + diff --git a/pkg/core/versioning/normalize.go b/pkg/core/versioning/normalize.go index 5c9207aab..f01fe87da 100644 --- a/pkg/core/versioning/normalize.go +++ b/pkg/core/versioning/normalize.go @@ -186,17 +186,14 @@ func normalizeRouterRuleSnapshot(res coremodel.Resource) (routerRuleSnapshot, bo if typed == nil || typed.Spec == nil { return routerRuleSnapshot{}, false, nil } - _, specJSON, err = NormalizeSpec(typed.Spec) + specJSON, err = normalizeSpecWithExplicitEnabled(typed.Spec, typed.Spec.Enabled) if err != nil { return routerRuleSnapshot{}, true, err } - runtime, enabled := meshresource.AffinityRuleOptionalFields(typed) + runtime, _ := meshresource.AffinityRuleOptionalFields(typed) if runtime == nil { omittedFields = append(omittedFields, "runtime") } - if enabled == nil { - omittedFields = append(omittedFields, "enabled") - } case *meshresource.ScriptRouteResource: if typed == nil || typed.Spec == nil { return routerRuleSnapshot{}, false, nil @@ -226,6 +223,23 @@ func normalizeRouterRuleSnapshot(res coremodel.Resource) (routerRuleSnapshot, bo }, true, nil } +func normalizeSpecWithExplicitEnabled(spec coremodel.ResourceSpec, enabled bool) (string, error) { + _, specJSON, err := NormalizeSpec(spec) + if err != nil { + return "", err + } + var value map[string]any + if err := json.Unmarshal([]byte(specJSON), &value); err != nil { + return "", err + } + value["enabled"] = enabled + raw, err := json.Marshal(value) + if err != nil { + return "", err + } + return canonicalJSON(raw) +} + func affinityResourceFromSnapshot(mesh, ruleName, specJSON string) (coremodel.Resource, bool, error) { snapshot, handled, err := parseRouterRuleSnapshot(specJSON) if !handled || err != nil { diff --git a/pkg/core/versioning/normalize_test.go b/pkg/core/versioning/normalize_test.go index 64e8ab445..c1232b263 100644 --- a/pkg/core/versioning/normalize_test.go +++ b/pkg/core/versioning/normalize_test.go @@ -90,7 +90,7 @@ affinityAware: explicitHash, explicitSnapshot, err := NormalizeResource(explicitFalse) require.NoError(t, err) require.NotEqual(t, omittedHash, explicitHash) - require.Contains(t, snapshot, `"omittedFields":["runtime","enabled"]`) + require.Contains(t, snapshot, `"omittedFields":["runtime"]`) require.NotContains(t, explicitSnapshot, `"omittedFields"`) restored, err := ResourceFromSpecJSON(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", snapshot) @@ -98,7 +98,7 @@ affinityAware: raw, err := meshresource.EncodeRule(restored) require.NoError(t, err) require.NotContains(t, string(raw), "runtime:") - require.NotContains(t, string(raw), "enabled:") + require.Contains(t, string(raw), "enabled: true") restored, err = ResourceFromSpecJSON(meshresource.AffinityRouteKind, "mesh", "demo.affinity-router", explicitSnapshot) require.NoError(t, err) From f5f018d9d5179188c5c7af82fb8135bd8bb40e4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 5 Sep 2026 16:12:31 +0800 Subject: [PATCH 12/21] feat(frontend): manage affinity and script router rules (cherry picked from commit c56c42a119a7a30bde0d048ad311b5724a87fbc4) --- ui-vue3/src/api/service/traffic.ts | 41 +++- ui-vue3/src/base/i18n/en.ts | 24 ++ ui-vue3/src/base/i18n/zh.ts | 23 ++ ui-vue3/src/router/RouterMeta.ts | 1 + ui-vue3/src/router/defaultRoutes.ts | 24 ++ .../views/traffic/_shared/RouterRuleList.vue | 119 ++++++++++ .../traffic/_shared/RouterRuleYamlEditor.vue | 210 ++++++++++++++++++ .../src/views/traffic/affinityRule/editor.vue | 22 ++ .../src/views/traffic/affinityRule/index.vue | 22 ++ .../src/views/traffic/scriptRule/editor.vue | 22 ++ .../src/views/traffic/scriptRule/index.vue | 22 ++ 11 files changed, 528 insertions(+), 2 deletions(-) create mode 100644 ui-vue3/src/views/traffic/_shared/RouterRuleList.vue create mode 100644 ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.vue create mode 100644 ui-vue3/src/views/traffic/affinityRule/editor.vue create mode 100644 ui-vue3/src/views/traffic/affinityRule/index.vue create mode 100644 ui-vue3/src/views/traffic/scriptRule/editor.vue create mode 100644 ui-vue3/src/views/traffic/scriptRule/index.vue diff --git a/ui-vue3/src/api/service/traffic.ts b/ui-vue3/src/api/service/traffic.ts index 06dd41664..8993d44f2 100644 --- a/ui-vue3/src/api/service/traffic.ts +++ b/ui-vue3/src/api/service/traffic.ts @@ -17,7 +17,14 @@ import request from '@/base/http/request' -export type TrafficRuleKind = 'condition-rule' | 'tag-rule' | 'configurator' +export type TrafficRuleKind = + | 'condition-rule' + | 'tag-rule' + | 'configurator' + | 'affinity-rule' + | 'script-rule' + +export type RouterRuleKind = 'affinity-rule' | 'script-rule' export interface RuleVersion { ruleKind: string @@ -61,7 +68,9 @@ export interface RollbackRuleVersionResult { } const ruleNameForPath = (kind: TrafficRuleKind, ruleName: string): string => { - return kind === 'configurator' ? encodeURIComponent(ruleName) : ruleName + return ['configurator', 'affinity-rule', 'script-rule'].includes(kind) + ? encodeURIComponent(ruleName) + : ruleName } export const listRuleVersionsAPI = ( @@ -193,6 +202,34 @@ export const addTagRuleAPI = (ruleName: string, data: any): Promise => { }) } +export const searchRouterRuleAPI = (kind: RouterRuleKind, params: any): Promise => { + return request({ url: `/${kind}/search`, method: 'get', params }) +} + +export const getRouterRuleAPI = (kind: RouterRuleKind, ruleName: string): Promise => { + return request({ url: `/${kind}/${encodeURIComponent(ruleName)}`, method: 'get' }) +} + +export const addRouterRuleAPI = ( + kind: RouterRuleKind, + ruleName: string, + data: any +): Promise => { + return request({ url: `/${kind}/${encodeURIComponent(ruleName)}`, method: 'post', data }) +} + +export const updateRouterRuleAPI = ( + kind: RouterRuleKind, + ruleName: string, + data: any +): Promise => { + return request({ url: `/${kind}/${encodeURIComponent(ruleName)}`, method: 'put', data }) +} + +export const deleteRouterRuleAPI = (kind: RouterRuleKind, ruleName: string): Promise => { + return request({ url: `/${kind}/${encodeURIComponent(ruleName)}`, method: 'delete' }) +} + export const searchDynamicConfig = (params: any): Promise => { return request({ url: '/configurator/search', diff --git a/ui-vue3/src/base/i18n/en.ts b/ui-vue3/src/base/i18n/en.ts index 169aac1cc..8594d8b6c 100644 --- a/ui-vue3/src/base/i18n/en.ts +++ b/ui-vue3/src/base/i18n/en.ts @@ -91,6 +91,26 @@ const words: I18nType = { createNewRoutingRule: 'Create New Conditional Routing Rule', warnDeleteRouteRule: 'Are you sure to delete this conditional routing rule?' }, + routerRuleDomain: { + create: 'Create {rule}', + saveChanges: 'Save changes', + deleteConfirm: 'Delete {ruleName}? This removes the rule from the configuration center.', + affinityHint: + 'Affinity rules support application or service scope. For service scope, use interface:version:group as the key.', + scriptHint: 'Script rules support application scope and the registered javascript type only.', + yamlMustBeObject: 'The YAML document must be an object.', + keyRequired: 'A rule key is required.', + loadFailed: 'Could not load the rule. Please retry.', + saveFailed: 'Could not save the rule. Please retry.', + deleteFailed: 'Could not delete the rule. Please retry.', + createSuccess: '{rule} created', + updateSuccess: '{rule} updated', + deleteSuccess: '{rule} deleted', + unsavedChangesTitle: 'Discard unsaved changes?', + unsavedChangesBody: 'Your YAML changes have not been saved.', + keepEditing: 'Keep editing', + discardChanges: 'Discard changes' + }, addRoutingRuleDomain: { YAMLView: 'YAML view', formView: 'Form view' @@ -262,6 +282,10 @@ const words: I18nType = { trafficManagement: 'Traffic Management', routingRule: 'Condition Rule', tagRule: 'Tag Rule', + affinityRule: 'Affinity Rule', + affinityRuleEditor: 'Edit Affinity Rule', + scriptRule: 'Script Rule', + scriptRuleEditor: 'Edit Script Rule', meshRule: 'Mesh Rule', dynamicConfig: 'Dynamic Config', accessControl: 'Black White List', diff --git a/ui-vue3/src/base/i18n/zh.ts b/ui-vue3/src/base/i18n/zh.ts index 557a5401f..74c8c3435 100644 --- a/ui-vue3/src/base/i18n/zh.ts +++ b/ui-vue3/src/base/i18n/zh.ts @@ -97,6 +97,25 @@ const words: I18nType = { createNewRoutingRule: '新增条件路由规则', warnDeleteRouteRule: '确认删除该条件路由规则?' }, + routerRuleDomain: { + create: '新建{rule}', + saveChanges: '保存修改', + deleteConfirm: '确认删除 {ruleName} 吗?该规则将从配置中心移除。', + affinityHint: '亲和路由支持应用或服务粒度;服务粒度的 key 格式为 interface:version:group。', + scriptHint: '脚本路由仅支持应用粒度和已注册的 javascript 脚本类型。', + yamlMustBeObject: 'YAML 文档必须是对象。', + keyRequired: '必须填写规则 key。', + loadFailed: '无法加载规则,请重试。', + saveFailed: '无法保存规则,请重试。', + deleteFailed: '无法删除规则,请重试。', + createSuccess: '{rule}已创建', + updateSuccess: '{rule}已更新', + deleteSuccess: '{rule}已删除', + unsavedChangesTitle: '放弃未保存的修改?', + unsavedChangesBody: 'YAML 修改尚未保存。', + keepEditing: '继续编辑', + discardChanges: '放弃修改' + }, updateRoutingRuleDomain: { YAMLView: 'YAML视图', formView: '表单视图' @@ -243,6 +262,10 @@ const words: I18nType = { serviceRelation: '服务关系', routingRule: '条件路由', tagRule: '标签路由', + affinityRule: '亲和路由', + affinityRuleEditor: '编辑亲和路由', + scriptRule: '脚本路由', + scriptRuleEditor: '编辑脚本路由', meshRule: 'Mesh路由', dynamicConfig: '动态配置', accessControl: '黑白名单', diff --git a/ui-vue3/src/router/RouterMeta.ts b/ui-vue3/src/router/RouterMeta.ts index fbda6db09..86c258e6c 100644 --- a/ui-vue3/src/router/RouterMeta.ts +++ b/ui-vue3/src/router/RouterMeta.ts @@ -26,6 +26,7 @@ export interface RouterMeta extends RouteMeta { tab?: boolean _router_key?: string parent?: RouteRecordType + back?: string slots?: { [key: string]: Component } headerParamKey?: string } diff --git a/ui-vue3/src/router/defaultRoutes.ts b/ui-vue3/src/router/defaultRoutes.ts index ccb2146ac..5c42cba4d 100644 --- a/ui-vue3/src/router/defaultRoutes.ts +++ b/ui-vue3/src/router/defaultRoutes.ts @@ -619,6 +619,30 @@ export const routes: Readonly = [ } } ] + }, + { + path: '/affinityRule', + name: 'affinityRule', + component: () => import('../views/traffic/affinityRule/index.vue'), + meta: {} + }, + { + path: '/affinityRule/edit/:ruleName?', + name: 'affinityRuleEditor', + component: () => import('../views/traffic/affinityRule/editor.vue'), + meta: { hidden: true, back: '/traffic/affinityRule' } + }, + { + path: '/scriptRule', + name: 'scriptRule', + component: () => import('../views/traffic/scriptRule/index.vue'), + meta: {} + }, + { + path: '/scriptRule/edit/:ruleName?', + name: 'scriptRuleEditor', + component: () => import('../views/traffic/scriptRule/editor.vue'), + meta: { hidden: true, back: '/traffic/scriptRule' } } // { // path: '/meshRule', diff --git a/ui-vue3/src/views/traffic/_shared/RouterRuleList.vue b/ui-vue3/src/views/traffic/_shared/RouterRuleList.vue new file mode 100644 index 000000000..cb02fc3de --- /dev/null +++ b/ui-vue3/src/views/traffic/_shared/RouterRuleList.vue @@ -0,0 +1,119 @@ + + + + + + diff --git a/ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.vue b/ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.vue new file mode 100644 index 000000000..a66f77efd --- /dev/null +++ b/ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.vue @@ -0,0 +1,210 @@ + + + + + + diff --git a/ui-vue3/src/views/traffic/affinityRule/editor.vue b/ui-vue3/src/views/traffic/affinityRule/editor.vue new file mode 100644 index 000000000..4f6b9822a --- /dev/null +++ b/ui-vue3/src/views/traffic/affinityRule/editor.vue @@ -0,0 +1,22 @@ + + + + diff --git a/ui-vue3/src/views/traffic/affinityRule/index.vue b/ui-vue3/src/views/traffic/affinityRule/index.vue new file mode 100644 index 000000000..a8629a992 --- /dev/null +++ b/ui-vue3/src/views/traffic/affinityRule/index.vue @@ -0,0 +1,22 @@ + + + + diff --git a/ui-vue3/src/views/traffic/scriptRule/editor.vue b/ui-vue3/src/views/traffic/scriptRule/editor.vue new file mode 100644 index 000000000..33c6ec7de --- /dev/null +++ b/ui-vue3/src/views/traffic/scriptRule/editor.vue @@ -0,0 +1,22 @@ + + + + diff --git a/ui-vue3/src/views/traffic/scriptRule/index.vue b/ui-vue3/src/views/traffic/scriptRule/index.vue new file mode 100644 index 000000000..a69087ec1 --- /dev/null +++ b/ui-vue3/src/views/traffic/scriptRule/index.vue @@ -0,0 +1,22 @@ + + + + From 890906c811e7bb2e95859fc882bbeb14b0c511a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD?= <575121043@qq.com> Date: Sat, 5 Sep 2026 16:12:45 +0800 Subject: [PATCH 13/21] test(frontend): cover affinity and script YAML rule creation (cherry picked from commit da159e6d915f482fba81b1169ea2e22c3c7c017e) --- .../_shared/RouterRuleYamlEditor.spec.ts | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.spec.ts diff --git a/ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.spec.ts b/ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.spec.ts new file mode 100644 index 000000000..baee1bc0a --- /dev/null +++ b/ui-vue3/src/views/traffic/_shared/RouterRuleYamlEditor.spec.ts @@ -0,0 +1,188 @@ +/* + * 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. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h } from 'vue' +import yaml from 'js-yaml' +import { HTTP_STATUS } from '@/base/http/constants' +import type RouterRuleYamlEditorType from './RouterRuleYamlEditor.vue' + +const mocks = vi.hoisted(() => ({ + addRouterRuleAPI: vi.fn(), + getRouterRuleAPI: vi.fn(), + updateRouterRuleAPI: vi.fn(), + push: vi.fn(), + route: { params: {} as Record } +})) + +vi.mock('vue-router', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useRoute: () => mocks.route, + useRouter: () => ({ push: mocks.push }), + onBeforeRouteLeave: vi.fn() + } +}) + +vi.mock('@/api/service/traffic', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + addRouterRuleAPI: mocks.addRouterRuleAPI, + getRouterRuleAPI: mocks.getRouterRuleAPI, + updateRouterRuleAPI: mocks.updateRouterRuleAPI + } +}) + +vi.mock('ant-design-vue', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + message: { + error: vi.fn(), + success: vi.fn() + }, + Modal: { confirm: vi.fn() } + } +}) + +vi.mock('@/components/editor/MonacoEditor.vue', () => ({ + default: { + name: 'MonacoEditor', + template: '