AlexStocks commented on code in PR #1066:
URL: https://github.com/apache/dubbo-go-pixiu/pull/1066#discussion_r4430940723


##########
admin/logic/route_binding.go:
##########
@@ -199,11 +225,17 @@ func (s *RouteBindingStore) List(ctx context.Context, 
unpublished bool) ([]Route
                if err != nil {
                        return nil, err
                }
-               statuses = routeBindingStatuses(entries, publishedEntries)
+               statuses, err = s.routeBindingStatuses(entries, 
publishedEntries)
+               if err != nil {
+                       return nil, err
+               }
        }
        result := make([]RouteBinding, 0, len(entries))
        for _, entry := range entries {
-               view := routeBindingView(entry)
+               view, err := s.view(entry)

Review Comment:
   🔴 **一条坏记录会让整个路由列表返回 500**
   
   `List` 里把 `routeBindingView(entry)` 换成了 `s.view(entry)`,而 `view()` 会跑 
`Normalize`(先 `migrateLegacyRouteBindingSpec` 迁移,再 schema 校验 + 语义校验)。任一 entry 
出错就 `return nil, err`,整个列表接口失败。
   
   改动前 `routeBindingView` 只做纯字段搬运,永远不报错 —— 所以这是一次**可用性回归**,而不是新功能的风险。
   
   触发面比看起来宽得多:
   
   1. 历史遗留 draft/published 里,`spec.target` 只要出现在 `allowedTargetFields` 
之外的字段,`migration` 直接判死;
   2. 任何一次 schema 演进(新增必填字段、收紧格式)都会让**升级前存下的所有记录**在新版本上校验失败;
   3. `History` / `HistorySummaries` 也会对历史快照跑 `Normalize`,同一类数据把历史页一起带下去。
   
   后果不对称:Admin UI 的路由列表页依赖这个接口,列表挂了 = 用户在 UI 里看不到也修不了那条坏记录,只能去 etcd 
手抠。运维视角这是最难受的故障形态。
   
   **Suggestion**:把「读取」和「校验」解耦,读取永不为单条数据失败:
   
   ```go
   // RouteBinding 增加一个非致命字段
   LoadError string `json:"loadError,omitempty"`
   
   for _, entry := range entries {
        view, err := s.view(entry)
        if err != nil {
                view = RouteBinding{Object: entry.record.Object} // 原样返回,UI 仍可打开
                view.LoadError = err.Error()
                // 计数并打日志,便于运维发现需要修复的记录
        }
        ...
   }
   ```
   
   写路径(`SaveDraft` / `Publish`)保持严格校验不变 —— 那才是该拒绝的地方。读路径的目标是「让运维看见并修好」,不是「一起挂掉」。
   
   如果坚持 fail-fast,至少要让 `Normalize` 的失败只影响该条 route 的 `Get`/`Status`,而 `List` 
降级为跳过后在响应里带 `warnings`。



##########
admin/controller/configInfo/legacy_resource.go:
##########
@@ -0,0 +1,284 @@
+/*
+ * 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 configInfo
+
+import (
+       "encoding/json"
+       "errors"
+       "net/http"
+       "strconv"
+       "strings"
+)
+
+import (
+       "github.com/gin-gonic/gin"
+)
+
+import (
+       adminconfig "github.com/apache/dubbo-go-pixiu/admin/config"
+       "github.com/apache/dubbo-go-pixiu/admin/logic"
+       commonyaml "github.com/apache/dubbo-go-pixiu/pkg/common/yaml"
+       "github.com/apache/dubbo-go-pixiu/pkg/config"
+)
+
+// These handlers preserve the Resource/Method Admin API for clients deployed
+// before AdminRouteBinding. They continue to read/write the legacy runtime
+// etcd keys, so old YAML and published records remain usable.
+func GetResourceList(c *gin.Context) {
+       resources, err := logic.BizGetResourceList(legacyUnpublished(c))
+       if err != nil {
+               legacyError(c, err)
+               return
+       }
+       data, _ := json.Marshal(resources)
+       c.JSON(http.StatusOK, adminconfig.WithRet(string(data)))
+}
+
+func GetResourceDetail(c *gin.Context) {
+       detail, err := logic.BizGetResourceDetail(c.Query(logic.ResourceID), 
legacyUnpublished(c))
+       if err != nil {
+               legacyError(c, err)
+               return
+       }
+       c.JSON(http.StatusOK, adminconfig.WithRet(detail))
+}
+
+func CreateResourceInfo(c *gin.Context) {
+       resource, err := decodeLegacyResource(c)
+       if err != nil {
+               legacyError(c, err)
+               return
+       }
+       // Creation always assigns server-owned identities; positive IDs are 
only
+       // accepted by the logic layer when mirroring the same records to draft.
+       resource.ID = 0
+       for index := range resource.Methods {
+               resource.Methods[index].ID = 0
+       }
+       if legacyUnpublished(c) {
+               err = logic.BizSetResourceInfo(resource, true, true)
+       } else {
+               err = logic.BizSetResourceInfo(resource, true, false)
+               if err == nil {
+                       // Mirror the published records into the draft 
namespace with the
+                       // same Resource/Method IDs. Allocating a second set 
here would make
+                       // subsequent edits and publishes address a different 
route.
+                       err = logic.BizSetResourceInfo(resource, false, true)

Review Comment:
   🟡 **创建路径分三步写、无事务、无补偿**
   
   ```go
   BizSetResourceInfo(resource, true, false)   // 1. 写 published
   BizSetResourceInfo(resource, false, true)   // 2. 镜像到 draft
   for ... BizSetResourceMethod(..., true)     // 3. 逐个写 draft method
   ```
   
   三个独立的写阶段,中间任何一步失败:
   
   - 第 1 步成功、第 2 步失败 → **published 里有这条 Resource,draft 里没有**。后续走 draft 
编辑/发布流程永远看不到它,而客户端收到的是错误响应,会重试,重试又会因为 `Client.Create` 撞 key 而失败。
   - 第 3 步中途失败 → draft 里 Resource 有、method 少几个,直接发布出去就是残缺路由。
   
   PR 描述里写的是 "atomic publish",而同一个 PR 里 `BizUpdateResourceAndMethods` 已经用 
`client.Txn` 做了原子更新 —— 创建路径没有对齐这个标准,看起来是遗漏而不是有意设计。
   
   **Suggestion**:把三步合并成一个 Txn(resource + N 个 method,两个 namespace 一起提交):
   
   ```go
   ops := []clientv3.Op{clientv3.OpPut(publishedResourceKey, publishedValue), 
...}
   ops = append(ops, clientv3.OpPut(draftResourceKey, draftValue))
   for _, m := range methods { ops = append(ops, 
clientv3.OpPut(draftMethodKey(m), methodValue)) }
   client.Txn(ctx).Then(ops...).Commit()
   ```
   
   若确实要分阶段(比如 published 和 draft 必须先后可见),至少要**在失败时补偿**已写入的 
key,并让错误信息说明「已创建但镜像失败,请检查」,不要只返回原始 error。



##########
admin/logic/route_binding.go:
##########
@@ -922,6 +1002,143 @@ func (s *RouteBindingStore) Diff(ctx context.Context, 
name string) (RouteBinding
        }, nil
 }
 
+// History returns immutable published snapshots for one route, oldest first.
+func (s *RouteBindingStore) History(ctx context.Context, name string) 
([]RouteBindingHistoryEntry, error) {
+       ctx = routeBindingContext(ctx)
+       name, err := normalizeRouteBindingName(name)
+       if err != nil {
+               return nil, err
+       }
+       response, err := s.kv.Get(ctx, s.historyPrefix(name), 
clientv3.WithPrefix())
+       if err != nil {
+               return nil, fmt.Errorf("list route binding history %q: %w", 
name, err)
+       }
+       entries := make([]RouteBindingHistoryEntry, 0, len(response.Kvs))
+       for _, kv := range response.Kvs {
+               var record routeBindingHistoryRecord
+               if err := json.Unmarshal(kv.Value, &record); err != nil {
+                       return nil, fmt.Errorf("decode route binding history 
%q: %w", string(kv.Key), err)
+               }
+               entry := RouteBindingHistoryEntry{Revision: record.Revision, 
PublishedAt: record.PublishedAt}
+               if record.Binding != nil {
+                       object, err := s.Normalize(record.Binding.Object)
+                       if err != nil {
+                               return nil, fmt.Errorf("normalize route binding 
history %q: %w", string(kv.Key), err)
+                       }
+                       entry.Object = &object
+                       entry.ResourceID = record.Binding.ResourceID
+                       entry.MethodID = record.Binding.MethodID
+               }
+               entries = append(entries, entry)
+       }
+       sort.Slice(entries, func(i, j int) bool { return entries[i].Revision < 
entries[j].Revision })
+       return entries, nil
+}
+
+// HistorySummaries returns the latest published snapshot for every route.
+// This keeps deletion tombstones discoverable from the Admin UI after the
+// route has disappeared from both draft and published lists.
+func (s *RouteBindingStore) HistorySummaries(ctx context.Context) 
([]RouteBindingHistorySummary, error) {
+       ctx = routeBindingContext(ctx)
+       prefix := s.root + "/" + routeBindingHistorySegment + "/"
+       response, err := s.kv.Get(ctx, prefix, clientv3.WithPrefix())
+       if err != nil {
+               return nil, fmt.Errorf("list route binding history summaries: 
%w", err)
+       }
+       latest := make(map[string]RouteBindingHistorySummary)
+       for _, kv := range response.Kvs {
+               relative := strings.TrimPrefix(string(kv.Key), prefix)
+               parts := strings.Split(relative, "/")
+               if len(parts) != 2 || parts[0] == "" {
+                       return nil, fmt.Errorf("invalid route binding history 
key %q", string(kv.Key))
+               }
+               name, err := url.PathUnescape(parts[0])
+               if err != nil {
+                       return nil, fmt.Errorf("decode route binding history 
key %q: %w", string(kv.Key), err)
+               }
+               name, err = normalizeRouteBindingName(name)
+               if err != nil {
+                       return nil, fmt.Errorf("invalid route binding history 
key %q: %w", string(kv.Key), err)
+               }
+               keyRevision, err := strconv.ParseInt(parts[1], 10, 64)
+               if err != nil || keyRevision <= 0 {
+                       return nil, fmt.Errorf("invalid route binding history 
revision in key %q", string(kv.Key))
+               }
+               var record routeBindingHistoryRecord
+               if err := json.Unmarshal(kv.Value, &record); err != nil {
+                       return nil, fmt.Errorf("decode route binding history 
%q: %w", string(kv.Key), err)
+               }
+               if record.Revision != keyRevision {
+                       return nil, fmt.Errorf("route binding history key %q 
contains revision %d", string(kv.Key), record.Revision)
+               }
+               if current, exists := latest[name]; !exists || record.Revision 
> current.LatestRevision {
+                       latest[name] = RouteBindingHistorySummary{
+                               Name:           name,
+                               LatestRevision: record.Revision,
+                               PublishedAt:    record.PublishedAt,
+                               Deleted:        record.Binding == nil,
+                       }
+               }
+       }
+       summaries := make([]RouteBindingHistorySummary, 0, len(latest))
+       for _, summary := range latest {
+               summaries = append(summaries, summary)
+       }
+       sort.Slice(summaries, func(i, j int) bool { return summaries[i].Name < 
summaries[j].Name })
+       return summaries, nil
+}
+
+// Rollback stages the selected published snapshot as the current draft and
+// sends it through the normal atomic publish path. If publish loses a race,
+// the selected version remains a draft and the active runtime stays intact.
+func (s *RouteBindingStore) Rollback(ctx context.Context, name string, 
historyRevision, expectedDraftRevision int64) (RouteBindingPublishResult, 
error) {
+       ctx = routeBindingContext(ctx)
+       name, err := normalizeRouteBindingName(name)
+       if err != nil {
+               return RouteBindingPublishResult{}, err
+       }
+       if historyRevision <= 0 {
+               return RouteBindingPublishResult{}, errors.New("history 
revision must be positive")
+       }
+       response, err := s.kv.Get(ctx, s.historyKey(name, historyRevision))
+       if err != nil {
+               return RouteBindingPublishResult{}, fmt.Errorf("read route 
binding history %q revision %d: %w", name, historyRevision, err)
+       }
+       if len(response.Kvs) == 0 {
+               return RouteBindingPublishResult{}, fmt.Errorf("route binding 
history revision %d not found for %q", historyRevision, name)
+       }
+       var record routeBindingHistoryRecord
+       if err := json.Unmarshal(response.Kvs[0].Value, &record); err != nil {
+               return RouteBindingPublishResult{}, fmt.Errorf("decode route 
binding history %q revision %d: %w", name, historyRevision, err)
+       }
+       if record.Binding == nil {
+               return s.DeleteAndPublish(ctx, name, expectedDraftRevision)
+       }
+       if record.Binding.Object.Metadata.Name != name {
+               return RouteBindingPublishResult{}, fmt.Errorf("history 
revision %d belongs to a different route", historyRevision)
+       }
+       saved, err := s.SaveDraft(ctx, record.Binding.Object, false, 
expectedDraftRevision)
+       if err != nil {
+               return RouteBindingPublishResult{}, err
+       }
+       return s.Publish(ctx, name, saved.Revision)
+}
+
+func (s *RouteBindingStore) nextPublishedGeneration(ctx context.Context) 
(int64, error) {

Review Comment:
   🟡 **revision 的「值」和「CAS token」来自两次读,并发下会覆盖已提交的历史快照**
   
   调用顺序是这样的:
   
   1. `nextPublishedGeneration(ctx)` —— 读 marker 的 **value**,算出 `current+1`;
   2. `readPublishState` / `markerRevision` —— 稍后再读 marker 的 **ModRevision**,作为 
Txn 的比较条件;
   3. Txn 里把第 1 步算出的值写回。
   
   两次读之间没有任何绑定。于是存在这个交错(同一 route 的两个并发 publish 就够):
   
   ```
   A: 读 marker value=4  → 准备写 5
   B: 读 marker value=4  → 写 history[user-get/5]=B的快照, marker=5   ✅ 提交
   A: 读 marker ModRevision(已是 B 提交后的新 revision)→ 比较条件成立
   A: 写 history[user-get/5]=A的快照                              ✅ 提交,覆盖了 B
   ```
   
   key 是 `history/<name>/<revision>`,所以 A 直接把 B 已经提交的快照**覆盖**了。这和本 PR 反复强调的 
"immutable snapshots" 直接冲突。
   
   `buildPublishComparisons` 里对 marker 的 CAS 是对的,问题只在于「比较用的 
token」和「要写入的值」取自不同次读。
   
   **Suggestion**:把两次读并成一次,用同一个 `ModRevision` 既做 CAS 又算新值。例如让 
`nextPublishedGeneration` 返回 `(newValue, modRevision, 
exists)`,`buildPublishComparisons` 直接用这个 `modRevision`,不要再单独 
`markerRevision(...)` 读一遍。改动很小,但把整类问题关掉了。
   
   顺带补一句:现有 4 个 history/rollback 测试都是串行的 happy path,这条路径建议加一个并发用例(两个 goroutine 
同时 publish 同一 route,断言最终 history 条目数 == 成功 publish 次数)。



##########
admin/logic/route_binding.go:
##########
@@ -922,6 +1002,143 @@ func (s *RouteBindingStore) Diff(ctx context.Context, 
name string) (RouteBinding
        }, nil
 }
 
+// History returns immutable published snapshots for one route, oldest first.
+func (s *RouteBindingStore) History(ctx context.Context, name string) 
([]RouteBindingHistoryEntry, error) {
+       ctx = routeBindingContext(ctx)
+       name, err := normalizeRouteBindingName(name)
+       if err != nil {
+               return nil, err
+       }
+       response, err := s.kv.Get(ctx, s.historyPrefix(name), 
clientv3.WithPrefix())

Review Comment:
   🟡 **历史快照无上限、无分页、无保留策略**
   
   每次 `Publish` / `DeleteAndPublish` 都往 `history/<name>/<rev>` 写一份**完整 object 
快照**,并且:
   
   - `History()` 用 `WithPrefix` 把该 route **全部**历史一次读进内存再全量返回;
   - 没有任何过期/裁剪逻辑;
   - Admin UI 每次打开历史面板都会拉全量。
   
   单条 route 的 object 不算大,但 CI/CD 驱动的发布很容易把单条 route 的历史刷到几千条:etcd 
持续增长、接口响应体线性膨胀、前端一次性渲染几千个条目。这是典型的「功能对,运维错」。
   
   **Suggestion**(任选其一,建议都做):
   
   1. **保留策略**:在同一 Txn 里附带删除 `revision - N` 之前的 key(N 取 20~50 对回滚已经足够),把「保留最近 N 
版」写进文档;
   2. **分页**:`History(ctx, name, limit, beforeRevision)`,etcd 侧用 `WithLimit` + 
`WithSort(SortByKey, SortDescend)` 做游标,避免全量读。
   
   另外 `History` 里的 `sort.Slice` 是按字符串 key 排序后按 `Revision` 排 —— 
目前没问题,但一旦引入分页,排序必须下沉到 etcd(`WithSort`),否则翻页会重复/漏条目。



##########
admin/logic/legacy_resource.go:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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 logic
+
+import (
+       "errors"
+       "fmt"
+       "regexp"
+       "sort"
+       "strconv"
+       "strings"
+)
+
+import (
+       clientv3 "go.etcd.io/etcd/client/v3"
+)
+
+import (
+       adminconfig "github.com/apache/dubbo-go-pixiu/admin/config"
+       commonyaml "github.com/apache/dubbo-go-pixiu/pkg/common/yaml"
+       "github.com/apache/dubbo-go-pixiu/pkg/config"
+)
+
+const legacyResources = "resources"
+
+func legacyResourceKey(id string, unpublished bool) string {
+       if unpublished {
+               return getUnpublishedRootPath(legacyResources) + "/" + id
+       }
+       return getRootPath(legacyResources) + "/" + id
+}
+
+func legacyMethodPrefix(resourceID string, unpublished bool) string {
+       return legacyResourceKey(resourceID, unpublished) + "/" + Method
+}
+
+func legacyMethodKey(resourceID, methodID string, unpublished bool) string {
+       return legacyMethodPrefix(resourceID, unpublished) + "/" + methodID
+}
+
+func legacyResourceKeyPattern(unpublished bool) *regexp.Regexp {
+       root := getRootPath(legacyResources)
+       if unpublished {
+               root = getUnpublishedRootPath(legacyResources)
+       }
+       return regexp.MustCompile("^" + regexp.QuoteMeta(root) + `/[^/]+/?$`)
+}
+
+// BizGetResourceList restores the original Resource API over the runtime key
+// layout. RouteBinding records are not included because they use a separate
+// namespace and are compiled to these keys only when published.
+func BizGetResourceList(unpublished bool) ([]config.Resource, error) {
+       keys, values, err := adminconfig.Client.GetChildrenKVList(func() string 
{
+               if unpublished {
+                       return getUnpublishedRootPath(legacyResources)
+               }
+               return getRootPath(legacyResources)
+       }())
+       if err != nil {
+               return nil, err
+       }
+       if len(keys) != len(values) {
+               return nil, fmt.Errorf("legacy resource key/value count 
mismatch: %d != %d", len(keys), len(values))
+       }
+       resources := make([]config.Resource, 0, len(values))
+       pattern := legacyResourceKeyPattern(unpublished)
+       for index, key := range keys {
+               if !pattern.MatchString(key) {
+                       continue
+               }
+               var resource config.Resource
+               if err := commonyaml.UnmarshalYML([]byte(values[index]), 
&resource); err != nil {
+                       return nil, fmt.Errorf("decode legacy resource %q: %w", 
key, err)
+               }
+               resources = append(resources, resource)
+       }
+       return resources, nil
+}
+
+func BizGetResourceDetail(id string, unpublished bool) (string, error) {
+       return adminconfig.Client.Get(legacyResourceKey(id, unpublished))
+}
+
+// BizResourceExists checks an exact legacy Resource key without conflating a
+// missing record with an etcd read failure.
+func BizResourceExists(id string, unpublished bool) (bool, error) {
+       id, err := normalizePositiveLegacyID(id, ResourceID)
+       if err != nil {
+               return false, err
+       }
+       if adminconfig.Client == nil {
+               return false, errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return false, errors.New("admin etcd client is unavailable")
+       }
+       response, err := client.Get(adminconfig.Client.GetCtx(), 
legacyResourceKey(id, unpublished))
+       if err != nil {
+               return false, fmt.Errorf("read legacy resource %q: %w", id, err)
+       }
+       return len(response.Kvs) > 0, nil
+}
+
+func BizSetResourceInfo(resource *config.Resource, created, unpublished bool) 
error {
+       if resource == nil {
+               return errors.New("legacy resource is nil")
+       }
+       methods := append([]config.Method(nil), resource.Methods...)
+       storedResource := *resource
+       storedResource.Methods = nil
+       if created && storedResource.ID <= 0 {
+               storedResource.ID = nextLegacyResourceID()
+               if storedResource.ID <= 0 {
+                       return errors.New("could not allocate legacy resource 
id")
+               }
+       } else if storedResource.ID <= 0 {
+               return errors.New("legacy resource id must be positive")
+       }
+       resource.ID = storedResource.ID
+       data, err := commonyaml.MarshalYML(storedResource)
+       if err != nil {
+               return fmt.Errorf("encode legacy resource: %w", err)
+       }
+       key := legacyResourceKey(strconv.Itoa(storedResource.ID), unpublished)
+       if created {
+               err = adminconfig.Client.Create(key, string(data))
+       } else {
+               err = adminconfig.Client.Update(key, string(data))
+       }
+       if err != nil {
+               return fmt.Errorf("save legacy resource: %w", err)
+       }
+       if created {
+               for index := range methods {
+                       methods[index].ResourcePath = storedResource.Path
+                       if err := 
BizSetResourceMethod(strconv.Itoa(storedResource.ID), &methods[index], true, 
unpublished); err != nil {
+                               return err
+                       }
+                       resource.Methods[index] = methods[index]
+               }
+       }
+       return nil
+}
+
+func BizDeleteResourceInfo(id string, unpublished bool) error {
+       id, err := normalizePositiveLegacyID(id, ResourceID)
+       if err != nil {
+               return err
+       }
+       if adminconfig.Client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       _, err = client.Delete(adminconfig.Client.GetCtx(), 
legacyResourceKey(id, unpublished), clientv3.WithPrefix())
+       return err
+}
+
+func BizGetMethodList(resourceID string, unpublished bool) ([]config.Method, 
error) {
+       _, values, err := 
adminconfig.Client.GetChildrenKVList(legacyMethodPrefix(resourceID, 
unpublished))
+       if err != nil {
+               return nil, err
+       }
+       methods := make([]config.Method, 0, len(values))
+       for _, value := range values {
+               var method config.Method
+               if err := commonyaml.UnmarshalYML([]byte(value), &method); err 
!= nil {
+                       return nil, fmt.Errorf("decode legacy method: %w", err)
+               }
+               methods = append(methods, method)
+       }
+       return methods, nil
+}
+
+// BizUpdateResourceAndMethods updates a legacy Resource and its Methods in one
+// etcd transaction. This keeps Method.ResourcePath aligned with the Resource
+// when a legacy client changes the route path.
+func BizUpdateResourceAndMethods(resource *config.Resource, methods 
[]config.Method, unpublished bool) error {
+       if resource == nil {
+               return errors.New("legacy resource is nil")
+       }
+       resourceID, err := normalizePositiveLegacyID(strconv.Itoa(resource.ID), 
ResourceID)
+       if err != nil {
+               return err
+       }
+       if adminconfig.Client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+
+       storedResource := *resource
+       storedResource.Methods = nil
+       resourceData, err := commonyaml.MarshalYML(storedResource)
+       if err != nil {
+               return fmt.Errorf("encode legacy resource: %w", err)
+       }
+       operations := []clientv3.Op{clientv3.OpPut(
+               legacyResourceKey(resourceID, unpublished), 
string(resourceData),
+       )}
+       for index := range methods {
+               if methods[index].ID <= 0 {
+                       return fmt.Errorf("legacy method id must be positive, 
got %d", methods[index].ID)
+               }
+               methods[index].ResourcePath = resource.Path
+               methodData, err := commonyaml.MarshalYML(methods[index])
+               if err != nil {
+                       return fmt.Errorf("encode legacy method %d: %w", 
methods[index].ID, err)
+               }
+               operations = append(operations, clientv3.OpPut(
+                       legacyMethodKey(resourceID, 
strconv.Itoa(methods[index].ID), unpublished), string(methodData),
+               ))
+       }
+       if _, err := 
client.Txn(adminconfig.Client.GetCtx()).Then(operations...).Commit(); err != 
nil {
+               return fmt.Errorf("save legacy resource and methods atomically: 
%w", err)
+       }
+       return nil
+}
+
+func BizGetMethodDetail(resourceID, methodID string, unpublished bool) 
(string, error) {
+       return adminconfig.Client.Get(legacyMethodKey(resourceID, methodID, 
unpublished))
+}
+
+func BizSetResourceMethod(resourceID string, method *config.Method, created, 
unpublished bool) error {
+       if method == nil {
+               return errors.New("legacy method is nil")
+       }
+       if created && method.ID <= 0 {
+               method.ID = nextLegacyMethodID()
+               if method.ID <= 0 {
+                       return errors.New("could not allocate legacy method id")
+               }
+       } else if method.ID <= 0 {
+               return errors.New("legacy method id must be positive")
+       }
+       data, err := commonyaml.MarshalYML(method)
+       if err != nil {
+               return fmt.Errorf("encode legacy method: %w", err)
+       }
+       key := legacyMethodKey(resourceID, strconv.Itoa(method.ID), unpublished)
+       if created {
+               err = adminconfig.Client.Create(key, string(data))
+       } else {
+               err = adminconfig.Client.Update(key, string(data))
+       }
+       if err != nil {
+               return fmt.Errorf("save legacy method: %w", err)
+       }
+       return nil
+}
+
+func BizDeleteMethodInfo(resourceID, methodID string, unpublished bool) error {
+       var err error
+       resourceID, err = normalizePositiveLegacyID(resourceID, ResourceID)
+       if err != nil {
+               return err
+       }
+       methodID, err = normalizePositiveLegacyID(methodID, MethodID)
+       if err != nil {
+               return err
+       }
+       if adminconfig.Client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       return adminconfig.Client.Delete(legacyMethodKey(resourceID, methodID, 
unpublished))
+}
+
+// BizMethodExists checks an exact legacy Method key without conflating a
+// missing record with an etcd read failure.
+func BizMethodExists(resourceID, methodID string, unpublished bool) (bool, 
error) {
+       var err error
+       resourceID, err = normalizePositiveLegacyID(resourceID, ResourceID)
+       if err != nil {
+               return false, err
+       }
+       methodID, err = normalizePositiveLegacyID(methodID, MethodID)
+       if err != nil {
+               return false, err
+       }
+       if adminconfig.Client == nil {
+               return false, errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return false, errors.New("admin raw etcd client is unavailable")
+       }
+       response, err := client.Get(adminconfig.Client.GetCtx(), 
legacyMethodKey(resourceID, methodID, unpublished))
+       if err != nil {
+               return false, fmt.Errorf("read legacy method %q/%q: %w", 
resourceID, methodID, err)
+       }
+       return len(response.Kvs) > 0, nil
+}
+
+// BizBatchReleaseResources publishes each staged legacy Resource and its
+// Method records in one etcd transaction. The legacy API can address either
+// Resource or Method publication, so both endpoints share this transaction
+// boundary while remaining independent of AdminRouteBinding publishing.
+func BizBatchReleaseResources() error {
+       if adminconfig.Client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       fromPrefix := getUnpublishedRootPath(legacyResources) + "/"
+       response, err := client.Get(adminconfig.Client.GetCtx(), fromPrefix, 
clientv3.WithPrefix())
+       if err != nil {
+               return fmt.Errorf("read staged legacy resources: %w", err)
+       }
+       grouped := make(map[string][]clientv3.Op)
+       for _, item := range response.Kvs {
+               relative := strings.TrimPrefix(string(item.Key), fromPrefix)
+               parts := strings.SplitN(relative, "/", 2)
+               if relative == "" || strings.HasPrefix(relative, "/") {
+                       return fmt.Errorf("invalid staged legacy resource key 
%q", string(item.Key))
+               }
+               resourceID, err := normalizePositiveLegacyID(parts[0], 
ResourceID)
+               if err != nil {
+                       return fmt.Errorf("invalid staged legacy resource key 
%q: %w", string(item.Key), err)
+               }
+               if len(parts) == 2 {
+                       methodParts := strings.Split(parts[1], "/")
+                       if len(methodParts) != 2 || methodParts[0] != Method {
+                               return fmt.Errorf("invalid staged legacy 
resource key %q", string(item.Key))
+                       }
+                       if _, err := normalizePositiveLegacyID(methodParts[1], 
MethodID); err != nil {
+                               return fmt.Errorf("invalid staged legacy 
resource key %q: %w", string(item.Key), err)
+                       }
+               }
+               grouped[resourceID] = append(grouped[resourceID], 
clientv3.OpPut(
+                       getRootPath(legacyResources)+"/"+relative,
+                       string(item.Value),
+               ))
+       }
+
+       resourceIDs := make([]string, 0, len(grouped))
+       for resourceID := range grouped {
+               resourceIDs = append(resourceIDs, resourceID)
+       }
+       sort.Strings(resourceIDs)
+       for _, resourceID := range resourceIDs {
+               ops := grouped[resourceID]
+               sort.Slice(ops, func(i, j int) bool { return 
string(ops[i].KeyBytes()) < string(ops[j].KeyBytes()) })
+               _, err := 
client.Txn(adminconfig.Client.GetCtx()).Then(ops...).Commit()

Review Comment:
   🟡 **批量发布是「每个 Resource 一个 Txn」,不是一次发布**
   
   函数注释写的是 "publishes each staged legacy Resource and its Method records in one 
etcd transaction",容易读成「整体一次事务」,实际是按 resourceID 循环,**每个资源单独 Txn**:
   
   ```
   for _, resourceID := range resourceIDs {
       _, err := client.Txn(ctx).Then(ops...).Commit()   // 每个资源一次
   }
   ```
   
   后果:第 3 个资源失败时,前 2 
个已经发布、后面的没发布,接口返回错误但**没有告诉调用方发布到哪了**。对「发布」这种全有或全无的语义,这是需要明确取舍的地方:要么整体一次 Txn(注意 
etcd 单次 Txn 的操作数和 1.5MB 请求上限),要么把成功/失败列表返回给调用方。
   
   另外两点:
   
   1. **发布后不清 staged key**:`unpublished/resources/**` 从不删除,每次发布只是覆盖 
published。这个命名空间会无限增长(和 history 一样的运维债),而且「草稿已发布」和「草稿还没发布」在 etcd 里无法区分。
   2. **两个端点共用一个实现**:`/config/api/resource/publish` 和 
`/config/api/resource/method/publish` 都调到 `BizBatchReleaseResources()`,也就是说「发布 
method」等于「发布所有资源」。如果这是有意的兼容行为,请在 `admin/API.md` 里写明;如果不是,调用方会误以为只发布了某一个。
   
   **Suggestion**:至少补一条注释说明「按资源分段提交,非全局原子」,并在返回值里带上已发布的 resourceID 列表。



##########
pkg/config/schema/builtin.go:
##########
@@ -72,128 +78,256 @@ func adminRouteBindingSchema() ObjectSchema {
                                },
                                UI: UIHints{Group: "entry", Order: 10},
                        },
-                       "target": {
+                       "backendRef": {
                                Type:     FieldTypeObject,
                                Required: true,
                                Properties: map[string]*FieldSchema{
-                                       "protocol": {
-                                               Type:    FieldTypeString,
-                                               Default: "dubbo",
-                                               Enum:    []any{"dubbo"},
-                                               UI:      UIHints{Component: 
"select", Order: 10},
-                                       },
-                                       "application": {
+                                       "type": {
                                                Type:        FieldTypeString,
-                                               Required:    true,
-                                               Description: "Dubbo 
applicationName",
-                                               UI:          UIHints{Component: 
"text", Order: 20},
-                                       },
-                                       "interface": {
-                                               Type:     FieldTypeString,
-                                               Required: true,
-                                               UI:       UIHints{Component: 
"text", Order: 30},
-                                       },
-                                       "method": {
-                                               Type:     FieldTypeString,
-                                               Required: true,
-                                               UI:       UIHints{Component: 
"text", Order: 40},
+                                               Default:     "registry",
+                                               Enum:        []any{"registry"},
+                                               Description: "Dubbo services 
are resolved from the registries configured on the listener.",
+                                               UI:          UIHints{Component: 
"text", Order: 10},
                                        },
-                                       "version": {Type: FieldTypeString, 
Default: "", UI: UIHints{Component: "text", Order: 50}},
-                                       "group":   {Type: FieldTypeString, 
Default: "", UI: UIHints{Component: "text", Order: 60}},
-                                       "cluster": {
+                                       "clusterName": {
                                                Type:        FieldTypeString,
-                                               Required:    true,
-                                               Description: "legacy 
integrationRequest.clusterName",
-                                               UI:          UIHints{Component: 
"text", Order: 70},
+                                               Description: "Preserved only 
when migrating legacy target.cluster to integrationRequest.clusterName.",
                                        },
                                },
-                               UI: UIHints{Group: "target", Order: 20},
+                               UI: UIHints{Group: "backend", Order: 20},
                        },
-                       "params": {
-                               Type:        FieldTypeArray,
-                               Default:     []any{},
-                               Description: "Ordered HTTP source to Dubbo 
argument mappings",
-                               Items: &FieldSchema{
-                                       Type: FieldTypeObject,
-                                       Properties: map[string]*FieldSchema{
-                                               "from": {
-                                                       Type:        
FieldTypeString,
-                                                       Required:    true,
-                                                       Pattern:     
`^(uri|queryStrings|headers|requestBody)\..+`,
-                                                       Description: "legacy 
mappingParams.name",
-                                               },
-                                               "to": {
-                                                       Type:        
FieldTypeInteger,
-                                                       Required:    true,
-                                                       Minimum:     
floatPointer(0),
-                                                       Description: 
"zero-based Dubbo argument index",
-                                               },
-                                               "type": {
-                                                       Type:        
FieldTypeString,
-                                                       Required:    true,
-                                                       Enum:        
supportedDubboParamTypeEnum(),
-                                                       Description: "legacy 
mapType and parameterTypes entry",
+                       "serviceSelection": {
+                               Type:     FieldTypeObject,
+                               Required: true,
+                               Properties: map[string]*FieldSchema{
+                                       "application": {Type: FieldTypeString, 
Required: true, UI: UIHints{Component: "text", Order: 10}},
+                                       "interface":   {Type: FieldTypeString, 
Required: true, UI: UIHints{Component: "text", Order: 20}},
+                                       "group":       {Type: FieldTypeString, 
Default: "", UI: UIHints{Component: "text", Order: 30}},
+                                       "version":     {Type: FieldTypeString, 
Default: "", UI: UIHints{Component: "text", Order: 40}},
+                               },
+                               UI: UIHints{Group: "service", Order: 30},
+                       },
+                       "invocation": {
+                               Type:     FieldTypeObject,
+                               Required: true,
+                               Properties: map[string]*FieldSchema{
+                                       "method":  {Type: FieldTypeString, 
Required: true, UI: UIHints{Component: "text", Order: 10}},
+                                       "timeout": {Type: FieldTypeString, 
Default: "1s", Description: "Positive Go duration string", UI: 
UIHints{Component: "text", Order: 20}},
+                                       "parameters": {
+                                               Type:        FieldTypeArray,
+                                               Default:     []any{},
+                                               Description: "Ordered HTTP 
source to Dubbo argument mappings",
+                                               Items: &FieldSchema{
+                                                       Type: FieldTypeObject,
+                                                       Properties: 
map[string]*FieldSchema{
+                                                               "from": {
+                                                                       Type:   
     FieldTypeString,
+                                                                       
Required:    true,
+                                                                       
Pattern:     `^(uri|queryStrings|headers|requestBody)\..+`,
+                                                                       
Description: "legacy mappingParams.name",
+                                                               },
+                                                               "to": {
+                                                                       Type:   
     FieldTypeInteger,
+                                                                       
Required:    true,
+                                                                       
Minimum:     floatPointer(0),
+                                                                       
Description: "zero-based Dubbo argument index",
+                                                               },
+                                                               "type": {
+                                                                       Type:   
     FieldTypeString,
+                                                                       
Required:    true,
+                                                                       Enum:   
     supportedDubboParamTypeEnum(),
+                                                                       
Description: "legacy mapType and parameterTypes entry",
+                                                               },
+                                                       },
                                                },
+                                               UI: UIHints{Component: 
"parameter-binding-table", Group: "invocation", Order: 30},
                                        },
                                },
-                               UI: UIHints{Component: 
"parameter-binding-table", Group: "params", Order: 30},
+                               UI: UIHints{Group: "invocation", Order: 40},
                        },
                        "enabled": {
                                Type:        FieldTypeBoolean,
                                Default:     true,
                                Description: "Whether Pixiu accepts requests 
for the published route",
                                UI:          UIHints{Component: "switch", 
Group: "lifecycle", Order: 10},
                        },
-                       "extensions": {
-                               Type:    FieldTypeObject,
-                               Default: map[string]any{},
-                               UI:      UIHints{Component: "extension-fields", 
Group: "advanced", Order: 50, Advanced: true},
-                       },
                },
        }
 }
 
-func validateAdminRouteBinding(object AdminObject) []ValidationIssue {
-       params, ok := object.Spec["params"].([]any)
-       if !ok {
+// migrateLegacyRouteBindingSpec converts the target/params shape emitted by
+// PR #1046 to the separated backend/service/invocation contract. It only
+// migrates the known legacy fields and rejects mixed or unknown input rather
+// than silently discarding configuration.
+func migrateLegacyRouteBindingSpec(object *AdminObject) []ValidationIssue {
+       if extensions, exists := object.Spec["extensions"]; exists {
+               values, ok := extensions.(map[string]any)
+               if !ok || len(values) != 0 {
+                       return []ValidationIssue{issue("spec.extensions", 
"unsupported", "route extensions are not supported; remove this field")}
+               }
+               delete(object.Spec, "extensions")
+       }
+
+       _, hasTarget := object.Spec["target"]
+       _, hasParams := object.Spec["params"]
+       if !hasTarget && !hasParams {
                return nil
        }
+       for _, field := range []string{"backendRef", "serviceSelection", 
"invocation"} {
+               if _, exists := object.Spec[field]; exists {
+                       return []ValidationIssue{issue("spec."+field, 
"mixed_model", "cannot combine the legacy target/params fields with the 
separated route model")}
+               }
+       }
+       issues := make([]ValidationIssue, 0)
+       target, ok := object.Spec["target"].(map[string]any)
+       if !hasTarget || !ok {
+               return []ValidationIssue{issue("spec.target", "migration", 
"legacy target must be an object")}
+       }
+       allowedTargetFields := map[string]bool{"protocol": true, "application": 
true, "interface": true, "method": true, "version": true, "group": true, 
"cluster": true}
+       for key := range target {
+               if !allowedTargetFields[key] {
+                       issues = append(issues, issue("spec.target."+key, 
"migration", "legacy field has no AdminRouteBinding migration"))
+               }
+       }
+       if protocol, _ := target["protocol"].(string); protocol != "" && 
protocol != "dubbo" {
+               issues = append(issues, issue("spec.target.protocol", 
"migration", "only the legacy dubbo protocol can be migrated"))
+       }
+       if len(issues) != 0 {
+               return issues
+       }
+       backendRef := map[string]any{"type": "registry"}
+       if clusterName, exists := target["cluster"]; exists {
+               backendRef["clusterName"] = clusterName
+       }
+       object.Spec["backendRef"] = backendRef
+       object.Spec["serviceSelection"] = map[string]any{

Review Comment:
   💭 **迁移时把可能为 nil 的字段直接写进 `serviceSelection`**
   
   ```go
   object.Spec["serviceSelection"] = map[string]any{
        "application": target["application"],   // 缺失时是 untyped nil
        "interface":   target["interface"],
        "group":       target["group"],
        "version":     target["version"],
   }
   ```
   
   `application` / `interface` 缺失会被后面的 `validateRouteBindingService` 
拦住(required),这没问题。但 `group` / `version` 缺失时,key 会被显式写成 `nil`,序列化后落盘是 `group: 
null`。
   
   语义上 `null` 和「字段不存在」不是一回事:后续如果有人在 schema 里给 `group` 
加默认值,`applyDefaultsToFields` 通常只在 key **不存在**时补默认(`null` 
存在时会走类型校验分支),行为就取决于实现细节了。这类「看起来等价、其实不等价」的状态最容易在半年后咬人。
   
   **Suggestion**:只写非 nil 的字段:
   
   ```go
   serviceSelection := map[string]any{}
   for _, field := range []string{"application", "interface", "group", 
"version"} {
        if value, ok := target[field]; ok && value != nil {
                serviceSelection[field] = value
        }
   }
   object.Spec["serviceSelection"] = serviceSelection
   ```
   
   顺带:`backendRef` 里 `if clusterName, exists := target["cluster"]; exists` 只判断了 
key 存在、没判断值为 nil,同样的 `clusterName: null` 问题也存在,建议一并处理。



##########
admin/logic/legacy_resource.go:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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 logic
+
+import (
+       "errors"
+       "fmt"
+       "regexp"
+       "sort"
+       "strconv"
+       "strings"
+)
+
+import (
+       clientv3 "go.etcd.io/etcd/client/v3"
+)
+
+import (
+       adminconfig "github.com/apache/dubbo-go-pixiu/admin/config"
+       commonyaml "github.com/apache/dubbo-go-pixiu/pkg/common/yaml"
+       "github.com/apache/dubbo-go-pixiu/pkg/config"
+)
+
+const legacyResources = "resources"
+
+func legacyResourceKey(id string, unpublished bool) string {
+       if unpublished {
+               return getUnpublishedRootPath(legacyResources) + "/" + id
+       }
+       return getRootPath(legacyResources) + "/" + id
+}
+
+func legacyMethodPrefix(resourceID string, unpublished bool) string {
+       return legacyResourceKey(resourceID, unpublished) + "/" + Method
+}
+
+func legacyMethodKey(resourceID, methodID string, unpublished bool) string {
+       return legacyMethodPrefix(resourceID, unpublished) + "/" + methodID
+}
+
+func legacyResourceKeyPattern(unpublished bool) *regexp.Regexp {
+       root := getRootPath(legacyResources)
+       if unpublished {
+               root = getUnpublishedRootPath(legacyResources)
+       }
+       return regexp.MustCompile("^" + regexp.QuoteMeta(root) + `/[^/]+/?$`)
+}
+
+// BizGetResourceList restores the original Resource API over the runtime key
+// layout. RouteBinding records are not included because they use a separate
+// namespace and are compiled to these keys only when published.
+func BizGetResourceList(unpublished bool) ([]config.Resource, error) {
+       keys, values, err := adminconfig.Client.GetChildrenKVList(func() string 
{
+               if unpublished {
+                       return getUnpublishedRootPath(legacyResources)
+               }
+               return getRootPath(legacyResources)
+       }())
+       if err != nil {
+               return nil, err
+       }
+       if len(keys) != len(values) {
+               return nil, fmt.Errorf("legacy resource key/value count 
mismatch: %d != %d", len(keys), len(values))
+       }
+       resources := make([]config.Resource, 0, len(values))
+       pattern := legacyResourceKeyPattern(unpublished)
+       for index, key := range keys {
+               if !pattern.MatchString(key) {
+                       continue
+               }
+               var resource config.Resource
+               if err := commonyaml.UnmarshalYML([]byte(values[index]), 
&resource); err != nil {
+                       return nil, fmt.Errorf("decode legacy resource %q: %w", 
key, err)
+               }
+               resources = append(resources, resource)
+       }
+       return resources, nil
+}
+
+func BizGetResourceDetail(id string, unpublished bool) (string, error) {
+       return adminconfig.Client.Get(legacyResourceKey(id, unpublished))
+}
+
+// BizResourceExists checks an exact legacy Resource key without conflating a
+// missing record with an etcd read failure.
+func BizResourceExists(id string, unpublished bool) (bool, error) {
+       id, err := normalizePositiveLegacyID(id, ResourceID)
+       if err != nil {
+               return false, err
+       }
+       if adminconfig.Client == nil {
+               return false, errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return false, errors.New("admin etcd client is unavailable")
+       }
+       response, err := client.Get(adminconfig.Client.GetCtx(), 
legacyResourceKey(id, unpublished))
+       if err != nil {
+               return false, fmt.Errorf("read legacy resource %q: %w", id, err)
+       }
+       return len(response.Kvs) > 0, nil
+}
+
+func BizSetResourceInfo(resource *config.Resource, created, unpublished bool) 
error {
+       if resource == nil {
+               return errors.New("legacy resource is nil")
+       }
+       methods := append([]config.Method(nil), resource.Methods...)
+       storedResource := *resource
+       storedResource.Methods = nil
+       if created && storedResource.ID <= 0 {
+               storedResource.ID = nextLegacyResourceID()
+               if storedResource.ID <= 0 {
+                       return errors.New("could not allocate legacy resource 
id")
+               }
+       } else if storedResource.ID <= 0 {
+               return errors.New("legacy resource id must be positive")
+       }
+       resource.ID = storedResource.ID
+       data, err := commonyaml.MarshalYML(storedResource)
+       if err != nil {
+               return fmt.Errorf("encode legacy resource: %w", err)
+       }
+       key := legacyResourceKey(strconv.Itoa(storedResource.ID), unpublished)
+       if created {
+               err = adminconfig.Client.Create(key, string(data))
+       } else {
+               err = adminconfig.Client.Update(key, string(data))
+       }
+       if err != nil {
+               return fmt.Errorf("save legacy resource: %w", err)
+       }
+       if created {
+               for index := range methods {
+                       methods[index].ResourcePath = storedResource.Path
+                       if err := 
BizSetResourceMethod(strconv.Itoa(storedResource.ID), &methods[index], true, 
unpublished); err != nil {
+                               return err
+                       }
+                       resource.Methods[index] = methods[index]
+               }
+       }
+       return nil
+}
+
+func BizDeleteResourceInfo(id string, unpublished bool) error {
+       id, err := normalizePositiveLegacyID(id, ResourceID)
+       if err != nil {
+               return err
+       }
+       if adminconfig.Client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       _, err = client.Delete(adminconfig.Client.GetCtx(), 
legacyResourceKey(id, unpublished), clientv3.WithPrefix())
+       return err
+}
+
+func BizGetMethodList(resourceID string, unpublished bool) ([]config.Method, 
error) {

Review Comment:
   💭 **ID 校验不一致:删除校验、读取不校验**
   
   同一个文件里:
   
   - `BizDeleteResourceInfo` / `BizResourceExists` / `BizDeleteMethodInfo` / 
`BizMethodExists` 都走 `normalizePositiveLegacyID`;
   - `BizGetMethodList`(本行)/ `BizGetMethodDetail` / `BizSetResourceMethod` 
直接用原始字符串拼 key。
   
   `resourceID` 来自 HTTP query,于是:
   
   - `?resourceId=` 空值 → key 变成 `resources//method/{id}`,读不到但也不报错,返回空列表;
   - `?resourceId=01` 和 `?resourceId=1` 是**两个不同的 etcd 
key**:能写进去但读不出来(或反之),排查时极难定位;
   - 由于没有校验,负号和超大值也会直接进 key。
   
   **Suggestion**:三个函数入口统一 `normalizePositiveLegacyID(resourceID, ResourceID)` 
/ `(methodID, MethodID)`,和删除路径保持一致。校验集中在 logic 层,控制器就不必重复校验(现在 
`DeleteResourceInfo` 在 controller 和 logic 各校验一遍,也是重复)。



##########
admin/logic/legacy_resource.go:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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 logic
+
+import (
+       "errors"
+       "fmt"
+       "regexp"
+       "sort"
+       "strconv"
+       "strings"
+)
+
+import (
+       clientv3 "go.etcd.io/etcd/client/v3"
+)
+
+import (
+       adminconfig "github.com/apache/dubbo-go-pixiu/admin/config"
+       commonyaml "github.com/apache/dubbo-go-pixiu/pkg/common/yaml"
+       "github.com/apache/dubbo-go-pixiu/pkg/config"
+)
+
+const legacyResources = "resources"
+
+func legacyResourceKey(id string, unpublished bool) string {
+       if unpublished {
+               return getUnpublishedRootPath(legacyResources) + "/" + id
+       }
+       return getRootPath(legacyResources) + "/" + id
+}
+
+func legacyMethodPrefix(resourceID string, unpublished bool) string {
+       return legacyResourceKey(resourceID, unpublished) + "/" + Method
+}
+
+func legacyMethodKey(resourceID, methodID string, unpublished bool) string {
+       return legacyMethodPrefix(resourceID, unpublished) + "/" + methodID
+}
+
+func legacyResourceKeyPattern(unpublished bool) *regexp.Regexp {
+       root := getRootPath(legacyResources)
+       if unpublished {
+               root = getUnpublishedRootPath(legacyResources)
+       }
+       return regexp.MustCompile("^" + regexp.QuoteMeta(root) + `/[^/]+/?$`)
+}
+
+// BizGetResourceList restores the original Resource API over the runtime key
+// layout. RouteBinding records are not included because they use a separate
+// namespace and are compiled to these keys only when published.
+func BizGetResourceList(unpublished bool) ([]config.Resource, error) {
+       keys, values, err := adminconfig.Client.GetChildrenKVList(func() string 
{
+               if unpublished {
+                       return getUnpublishedRootPath(legacyResources)
+               }
+               return getRootPath(legacyResources)
+       }())
+       if err != nil {
+               return nil, err
+       }
+       if len(keys) != len(values) {
+               return nil, fmt.Errorf("legacy resource key/value count 
mismatch: %d != %d", len(keys), len(values))
+       }
+       resources := make([]config.Resource, 0, len(values))
+       pattern := legacyResourceKeyPattern(unpublished)
+       for index, key := range keys {
+               if !pattern.MatchString(key) {
+                       continue
+               }
+               var resource config.Resource
+               if err := commonyaml.UnmarshalYML([]byte(values[index]), 
&resource); err != nil {
+                       return nil, fmt.Errorf("decode legacy resource %q: %w", 
key, err)
+               }
+               resources = append(resources, resource)
+       }
+       return resources, nil
+}
+
+func BizGetResourceDetail(id string, unpublished bool) (string, error) {
+       return adminconfig.Client.Get(legacyResourceKey(id, unpublished))
+}
+
+// BizResourceExists checks an exact legacy Resource key without conflating a
+// missing record with an etcd read failure.
+func BizResourceExists(id string, unpublished bool) (bool, error) {
+       id, err := normalizePositiveLegacyID(id, ResourceID)
+       if err != nil {
+               return false, err
+       }
+       if adminconfig.Client == nil {
+               return false, errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return false, errors.New("admin etcd client is unavailable")
+       }
+       response, err := client.Get(adminconfig.Client.GetCtx(), 
legacyResourceKey(id, unpublished))
+       if err != nil {
+               return false, fmt.Errorf("read legacy resource %q: %w", id, err)
+       }
+       return len(response.Kvs) > 0, nil
+}
+
+func BizSetResourceInfo(resource *config.Resource, created, unpublished bool) 
error {
+       if resource == nil {
+               return errors.New("legacy resource is nil")
+       }
+       methods := append([]config.Method(nil), resource.Methods...)
+       storedResource := *resource
+       storedResource.Methods = nil
+       if created && storedResource.ID <= 0 {
+               storedResource.ID = nextLegacyResourceID()
+               if storedResource.ID <= 0 {
+                       return errors.New("could not allocate legacy resource 
id")
+               }
+       } else if storedResource.ID <= 0 {
+               return errors.New("legacy resource id must be positive")
+       }
+       resource.ID = storedResource.ID
+       data, err := commonyaml.MarshalYML(storedResource)
+       if err != nil {
+               return fmt.Errorf("encode legacy resource: %w", err)
+       }
+       key := legacyResourceKey(strconv.Itoa(storedResource.ID), unpublished)
+       if created {
+               err = adminconfig.Client.Create(key, string(data))
+       } else {
+               err = adminconfig.Client.Update(key, string(data))
+       }
+       if err != nil {
+               return fmt.Errorf("save legacy resource: %w", err)
+       }
+       if created {
+               for index := range methods {
+                       methods[index].ResourcePath = storedResource.Path
+                       if err := 
BizSetResourceMethod(strconv.Itoa(storedResource.ID), &methods[index], true, 
unpublished); err != nil {
+                               return err
+                       }
+                       resource.Methods[index] = methods[index]
+               }
+       }
+       return nil
+}
+
+func BizDeleteResourceInfo(id string, unpublished bool) error {
+       id, err := normalizePositiveLegacyID(id, ResourceID)
+       if err != nil {
+               return err
+       }
+       if adminconfig.Client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       client := adminconfig.Client.GetRawClient()
+       if client == nil {
+               return errors.New("admin etcd client is unavailable")
+       }
+       _, err = client.Delete(adminconfig.Client.GetCtx(), 
legacyResourceKey(id, unpublished), clientv3.WithPrefix())

Review Comment:
   🔴 **数据丢失:`WithPrefix()` 把 `resources/1` 当成 `resources/10` 的前缀**
   
   `legacyResourceKey("1", unpublished)` 返回的是 `<base>/resources/1`,而 
`resources/10`、`resources/11` … `resources/19` 全部以这个字符串为前缀。etcd 的 
`WithPrefix()` 是纯字节前缀匹配,不是路径段匹配。
   
   所以:
   
   ```
   DELETE /config/api/resource?resourceId=1
   ```
   
   在系统里存在 10 个以上 Resource 之后,会**连带删除 10~19 号 Resource 以及它们的全部 Method**,而接口返回 
`"Success"`。因为 `DeleteResourceInfo` 默认走 published 命名空间(`legacyUnpublished` 默认 
false),删的是正在生效的配置。
   
   **这不是理论风险**:Resource/Method ID 由 `nextLegacyResourceID()` 从 1 自增分配,第 10 
个资源出现是必然事件。
   
   **Suggestion**:这个仓库里已经有正确写法可以抄 —— `admin/logic/route_binding.go` 的 
`runtimeResourceDeleteOperations`:
   
   ```go
   func (s *RouteBindingStore) runtimeResourceDeleteOperations(resourceID int) 
[]clientv3.Op {
        key := s.runtimeResourceKey(resourceID)
        return []clientv3.Op{
                clientv3.OpDelete(key),                      // 精确删自己
                clientv3.OpDelete(key+"/", clientv3.WithPrefix()), // 只删子节点
        }
   }
   ```
   
   这里对应改成:
   
   ```go
   key := legacyResourceKey(id, unpublished)
   if _, err := client.Txn(adminconfig.Client.GetCtx()).Then(
        clientv3.OpDelete(key),
        clientv3.OpDelete(key+"/", clientv3.WithPrefix()),
   ).Commit(); err != nil {
        return fmt.Errorf("delete legacy resource %q: %w", id, err)
   }
   return nil
   ```
   
   **请务必补一个回归用例**:建 `resources/1` 和 `resources/10`(各自带 method),删 `1`,断言 `10` 及其 
method 仍在。这个 bug 单测里几分钟就能钉死,线上发现就是配置全丢。



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