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


##########
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 {

Review Comment:
   [P2] Handle a nil Spec without panicking
   
   `ResourceSpec()` returns an interface. When the concrete `Spec` pointer is 
nil, that interface still carries its pointer type, so `r.ResourceSpec() == 
nil` is false and validation reaches a nil dereference.
   
   Both of these calls panic on the current head instead of returning the 
intended "rule spec is required" error:
   
   ```go
   ValidateRule(&AffinityRouteResource{})
   ValidateRule(&ScriptRouteResource{})
   ```
   
   `EncodeRule` is affected as well because it calls this validator. Please 
check the concrete resource/Spec pointers before dereferencing them, and add 
regression tests asserting an error without a panic for both kinds. I 
reproduced both failures locally; the existing package tests and race check 
pass.



-- 
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