AsperforMias commented on code in PR #1552:
URL: https://github.com/apache/dubbo-admin/pull/1552#discussion_r4245478570


##########
pkg/core/resource/apis/mesh/v1alpha1/router_rule_codec.go:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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 v1alpha1
+
+import (
+       "fmt"
+       "strings"
+
+       "sigs.k8s.io/yaml"
+
+       meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+       "github.com/apache/dubbo-admin/pkg/common/bizerror"
+       "github.com/apache/dubbo-admin/pkg/common/constants"
+       coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model"
+)
+
+// The rule protobufs use scalar bools, so annotations retain field presence
+// from config-center YAML without changing generated resource types. Metadata
+// 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"
+       scriptEnabledOmittedAnnotation   = 
"dubbo.apache.org/script-enabled-omitted"
+)
+
+// The protobuf field is named affinity for historical/internal reasons. The
+// public Dubbo 3 contract is affinityAware, so never marshal the protobuf
+// message directly for these resources.
+type affinityRouteYAML struct {
+       ConfigVersion string             `json:"configVersion"`
+       Scope         string             `json:"scope"`
+       Key           string             `json:"key"`
+       Runtime       *bool              `json:"runtime,omitempty"`
+       Enabled       *bool              `json:"enabled,omitempty"`
+       AffinityAware *affinityAwareYAML `json:"affinityAware"`
+}
+
+type affinityAwareYAML struct {
+       Key   string `json:"key"`
+       Ratio int32  `json:"ratio"`
+}
+
+type scriptRouteYAML struct {
+       ConfigVersion string `json:"configVersion"`
+       Scope         string `json:"scope"`
+       Key           string `json:"key"`
+       Enabled       *bool  `json:"enabled,omitempty"`
+       Type          string `json:"type"`
+       Script        string `json:"script"`
+}
+
+// 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.
+func EncodeRule(r coremodel.Resource) ([]byte, error) {
+       if err := ValidateRule(r); err != nil {
+               return nil, err
+       }
+       var value any
+       switch typed := r.(type) {
+       case *AffinityRouteResource:
+               var aware *affinityAwareYAML
+               if typed.Spec.Affinity != nil {
+                       aware = &affinityAwareYAML{Key: 
typed.Spec.Affinity.Key, Ratio: typed.Spec.Affinity.Ratio}
+               }
+               value = affinityRouteYAML{
+                       ConfigVersion: typed.Spec.ConfigVersion,
+                       Scope:         typed.Spec.Scope,
+                       Key:           typed.Spec.Key,
+                       Runtime:       optionalRuleBool(typed.Spec.Runtime, 
typed.Annotations, affinityRuntimeOmittedAnnotation),
+                       Enabled:       optionalRuleBool(typed.Spec.Enabled, 
typed.Annotations, affinityEnabledOmittedAnnotation),
+                       AffinityAware: aware,
+               }
+       case *ScriptRouteResource:
+               value = scriptRouteYAML{
+                       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,
+               }
+       default:
+               if r == nil || r.ResourceSpec() == nil {
+                       return nil, invalidRule("rule spec is required")
+               }
+               value = r.ResourceSpec()
+       }
+       data, err := yaml.Marshal(value)
+       if err != nil {
+               return nil, bizerror.Wrap(err, bizerror.YamlError, "failed to 
marshal rule")
+       }
+       return data, nil
+}
+
+// DecodeRule parses a public rule YAML document into a typed resource. It is
+// used by both registry subscribers and governor read-back paths.
+func DecodeRule(kind coremodel.ResourceKind, mesh, name, data string) 
(coremodel.Resource, error) {
+       if strings.TrimSpace(data) == "" {
+               switch kind {
+               case AffinityRouteKind:
+                       return NewAffinityRouteResourceWithAttributes(name, 
mesh), nil
+               case ScriptRouteKind:
+                       return NewScriptRouteResourceWithAttributes(name, 
mesh), nil
+               }
+       }
+       switch kind {
+       case AffinityRouteKind:
+               external := affinityRouteYAML{}
+               if err := yaml.Unmarshal([]byte(data), &external); err != nil {
+                       return nil, ruleYAMLError(name, err)
+               }
+               res := NewAffinityRouteResourceWithAttributes(name, mesh)
+               if external.AffinityAware != nil {
+                       res.Spec.Affinity = &meshproto.AffinityAware{
+                               Key:   external.AffinityAware.Key,
+                               Ratio: external.AffinityAware.Ratio,
+                       }
+               }
+               res.Spec.ConfigVersion = external.ConfigVersion
+               res.Spec.Scope = external.Scope
+               res.Spec.Key = external.Key
+               if external.Runtime != nil {
+                       res.Spec.Runtime = *external.Runtime
+                       clearRuleBooleanOmitted(&res.Annotations, 
affinityRuntimeOmittedAnnotation)
+               } else {
+                       markRuleBooleanOmitted(&res.Annotations, 
affinityRuntimeOmittedAnnotation)
+               }
+               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
+               }
+               return res, nil
+       case ScriptRouteKind:
+               external := scriptRouteYAML{}
+               if err := yaml.Unmarshal([]byte(data), &external); err != nil {
+                       return nil, ruleYAMLError(name, err)
+               }
+               res := NewScriptRouteResourceWithAttributes(name, mesh)
+               res.Spec.ConfigVersion = external.ConfigVersion
+               res.Spec.Scope = external.Scope
+               res.Spec.Key = external.Key
+               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
+               if err := ValidateRule(res); err != nil {
+                       return nil, err
+               }
+               return res, nil
+       default:
+               res, err := 
coremodel.ResourceSchemaRegistry().NewResourceFunc(kind)
+               if err != nil {
+                       return nil, bizerror.New(bizerror.InvalidArgument, 
fmt.Sprintf("unsupported rule kind %s", kind))
+               }
+               r := res()
+               if err := yaml.Unmarshal([]byte(data), r.ResourceSpec()); err 
!= nil {
+                       return nil, ruleYAMLError(name, err)
+               }
+               return r, nil
+       }
+}
+
+func optionalRuleBool(value bool, annotations map[string]string, 
omittedAnnotation string) *bool {
+       if !value && annotations[omittedAnnotation] == "true" {
+               return nil
+       }
+       return &value
+}
+
+func markRuleBooleanOmitted(annotations *map[string]string, key string) {
+       if *annotations == nil {
+               *annotations = make(map[string]string)
+       }
+       (*annotations)[key] = "true"
+}
+
+func clearRuleBooleanOmitted(annotations *map[string]string, key string) {
+       delete(*annotations, key)
+       if len(*annotations) == 0 {
+               *annotations = nil
+       }
+}
+
+func ruleYAMLError(name string, err error) error {
+       return bizerror.Wrap(err, bizerror.YamlError, fmt.Sprintf("invalid rule 
YAML %s", name))
+}
+
+// ValidateRule enforces the part of the Admin/runtime contract that can be
+// checked before a write reaches a configuration center.
+func ValidateRule(r coremodel.Resource) error {
+       if r == nil || r.ResourceSpec() == nil {
+               return invalidRule("rule spec is required")
+       }
+       switch typed := r.(type) {
+       case *AffinityRouteResource:
+               if typed.Spec.ConfigVersion != 
constants.ConfiguratorVersionV3x1 {
+                       return invalidRule("affinity configVersion must be 
v3.1")
+               }
+               if typed.Spec.Scope != constants.ScopeApplication && 
typed.Spec.Scope != constants.ScopeService {
+                       return invalidRule("affinity scope must be application 
or service")
+               }
+               if strings.TrimSpace(typed.Spec.Key) == "" || typed.Name != 
typed.Spec.Key+constants.AffinityRuleDotSuffix {
+                       return invalidRule("affinity rule name must be 
key.affinity-router")
+               }
+               if typed.Spec.Affinity == nil || 
strings.TrimSpace(typed.Spec.Affinity.Key) == "" {
+                       return invalidRule("affinityAware.key is required")
+               }
+               if typed.Spec.Affinity.Ratio < 0 || typed.Spec.Affinity.Ratio > 
100 {
+                       return invalidRule("affinityAware.ratio must be in [0, 
100]")
+               }
+               return nil
+       case *ScriptRouteResource:
+               if typed.Spec.ConfigVersion != constants.ConfiguratorVersionV3 
&& typed.Spec.ConfigVersion != constants.ConfiguratorVersionV3x1 {
+                       return invalidRule("script configVersion must be v3.0 
or v3.1")
+               }
+               if typed.Spec.Scope != constants.ScopeApplication {
+                       return invalidRule("script rules only support 
application scope")
+               }
+               if strings.TrimSpace(typed.Spec.Key) == "" || typed.Name != 
typed.Spec.Key+constants.ScriptRuleDotSuffix {
+                       return invalidRule("script rule name must be 
key.script-router")
+               }
+               if typed.Spec.Type != constants.ScriptTypeJavaScript {
+                       return invalidRule("script type must be javascript")
+               }
+               if strings.TrimSpace(typed.Spec.Script) == "" {
+                       return invalidRule("script must be non-empty")
+               }
+               if len([]byte(typed.Spec.Script)) > constants.MaxScriptRuleSize 
{

Review Comment:
   Integration dependency: the script-size limit does not bound execution
   
   A short, valid expression such as `(function(){while(true){}})()` passes the 
non-empty/type/size checks, but the current Dubbo-Go Script engine calls 
`RunProgram` without an interrupt deadline. Publishing such a rule through the 
completed Admin chain can block RPC routing goroutines indefinitely.
   
   This is an existing Dubbo-Go runtime dependency, tracked by 
apache/dubbo-go#3566, with the fix still open in apache/dubbo-go#3575. Please 
track that dependency for the Script feature and include bounded 
execution/failure behavior in runtime or integration acceptance. The engine 
timeout belongs in Dubbo-Go; this resource-contract PR can document the 
dependency without executing scripts in Admin.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to