You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by xu...@apache.org on 2026/10/20 06:04:03 UTC
(dubbo-go-pixiu) branch develop updated: [OSPP] feat(admin): add per-route enabled state (#1046)
This is an automated email from the ASF dual-hosted git repository.
Alanxtl pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/dubbo-go-pixiu.git
The following commit(s) were added to refs/heads/develop by this push:
new 45b3eb9ca [OSPP] feat(admin): add per-route enabled state (#1046)
45b3eb9ca is described below
commit 45b3eb9caac9b3f513e6a2dea3f4b8dfc56cc0be
Author: Nene7ko_ <14...@users.noreply.github.com>
AuthorDate: Tue Oct 20 14:03:57 2026 +0800
[OSPP] feat(admin): add per-route enabled state (#1046)
* feat(config): add schema-driven YAML model
* refactor(config): model admin route bindings
* feat(admin): add per-route API router publishing
* style: format Go imports
* feat(admin-web): sync route YAML with form
* fix(admin): satisfy staticcheck
* feat(admin): add route enabled state
* refactor: reduce route editor complexity
* refactor: clear route admin quality alerts
* fix: align API router lifecycle endpoints
* fix: restore generated docs license header
* fix(admin): close route binding review findings
* style: fix route binding test imports
* fix(admin): detect legacy runtime route conflicts
* fix(admin): align route editor with schema
* refactor: reduce route admin complexity
* fix(admin): restore PluginGroup publish endpoint
* chore: format imports
* fix(admin): preserve per-route publish isolation
---
admin/API.md | 231 +---
admin/API_CN.md | 241 +---
admin/controller/configInfo/configInfo.go | 480 -------
.../{configInfo_test.go => plugin_group.go} | 48 +-
admin/controller/configInfo/route_binding.go | 481 +++++++
admin/controller/configInfo/route_binding_test.go | 206 +++
admin/controller/opa/opa.go | 17 +
admin/doc/docs.go | 481 +++----
admin/doc/swagger.json | 452 +++----
admin/doc/swagger.yaml | 355 ++---
admin/initialize/router.go | 32 +-
.../router_plugin_group_test.go} | 29 +-
admin/logic/logic.go | 314 +----
admin/logic/route_binding.go | 1371 ++++++++++++++++++++
admin/logic/route_binding_test.go | 790 +++++++++++
admin/web/package-lock.json | 16 +
admin/web/package.json | 1 +
admin/web/src/api.ts | 25 +-
admin/web/src/app/App.tsx | 4 +-
admin/web/src/features/config/ConfigPages.tsx | 414 +++---
.../web/src/features/config/RouteBindingEditor.tsx | 628 +++++++++
.../config/RouteBindingEditorModel.test.ts | 179 +++
.../src/features/config/RouteBindingEditorModel.ts | 281 ++++
.../features/config/RouteBindingEditorSections.tsx | 1164 +++++++++++++++++
admin/web/src/hooks/use-resources.ts | 24 -
admin/web/src/i18n/index.ts | 7 +
admin/web/src/services/http.ts | 110 +-
admin/web/src/services/method-api.ts | 55 -
admin/web/src/services/resource-api.ts | 48 -
admin/web/src/services/route-binding-api.ts | 107 ++
admin/web/src/styles.css | 999 +++++++++++++-
admin/web/src/types/api.ts | 127 +-
admin/web/tests/api-contract.test.ts | 59 +-
configs/admin_config.yaml | 4 +-
pkg/config/api_config.go | 107 +-
pkg/config/api_config_etcd_test.go | 85 ++
pkg/config/schema/README.md | 45 +
pkg/config/schema/builtin.go | 224 ++++
pkg/config/schema/compiler.go | 219 ++++
.../config/schema/model.go | 44 +-
pkg/config/schema/registry.go | 195 +++
pkg/config/schema/registry_test.go | 109 ++
pkg/config/schema/route_binding_test.go | 189 +++
pkg/config/schema/schema.go | 105 ++
.../schema/testdata/admin_route_binding.yaml | 20 +
pkg/config/schema/validate.go | 391 ++++++
.../config/schema/yaml.go | 40 +-
pkg/filter/http/apiconfig/api/discovery_service.go | 9 +-
.../http/apiconfig/api/discovery_service_test.go | 18 +
49 files changed, 9081 insertions(+), 2499 deletions(-)
diff --git a/admin/API.md b/admin/API.md
index 94f322f29..5968231ce 100644
--- a/admin/API.md
+++ b/admin/API.md
@@ -2,9 +2,9 @@
**English** | [中文](API_CN.md)
-This API documentation describes the backend operations of the Pixiu management platform, including the APIs for retrieving, creating, modifying, and deleting resources (Resource), methods (Method), and plugin groups (PluginGroup). Pixiu provides a complete set of APIs to help users manage API gateway resource mappings, plugin configurations, and request handling. The examples in this document cover common request and response formats and show how to test the APIs using Postman.
+This API documentation describes the backend operations of the Pixiu management platform, including APIs for managing API route bindings (AdminRouteBinding), plugin groups (PluginGroup), and OPA policies. Pixiu provides APIs to help users manage API gateway route mappings, plugin configurations, and request handling. The examples in this document cover common request and response formats and show how to test the APIs using Postman.
-Whether you are creating new resources, modifying existing configurations, or managing plugin groups, this document provides clear steps and necessary API details, making it easier for developers to get started and integrate quickly.
+Whether you are creating new API routes, modifying existing configurations, or managing plugin groups, this document provides clear steps and necessary API details, making it easier for developers to get started and integrate quickly.
More detailed API descriptions can be found in the [Swagger documentation](./doc/swagger.json).
@@ -58,240 +58,129 @@ name: pixiu
description: pixiu111 sample
```
-## II. Resource
+## II. API Routes
-### 2.1 Get Resource List
+API Router configuration is managed through AdminRouteBinding objects. The legacy Resource/Method Admin CRUD API is replaced. Existing runtime Resource/Method records are not imported into the new draft model; recreate routes that need to be managed through this API. Publishing a new route continues to generate the legacy runtime configuration used by Pixiu.
-**Request**:
-
-```http
-GET /config/api/resource/list HTTP/1.1
-Host: 127.0.0.1:8080
-cache-control: no-cache
-```
-
-### 2.2 Get Resource Details
+### 2.1 Get API Route Schema
**Request**:
```http
-GET /config/api/resource/detail?resourceId=1 HTTP/1.1
+GET /config/api/route/schema HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
```
-### 2.3 Create Resource
+The response data contains the registered Admin object schemas, including the AdminRouteBinding schema used by the editor.
+
+### 2.2 Get API Route List
**Request**:
```http
-POST /config/api/resource/ HTTP/1.1
+GET /config/api/route/list?scope=draft HTTP/1.1
Host: 127.0.0.1:8080
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
cache-control: no-cache
```
-**Form Data**:
+Use scope=draft (the default) to list drafts or scope=published to list published routes. The legacy unpublished query parameter is also accepted: 1 selects drafts and 0 selects published routes. The draft list includes backend-calculated publication status.
-```text
-Content-Disposition: form-data; name="content"
-path: '/api/v1/test-dubbo/friend2'
-type: restful
-description: user
-timeout: 100ms
-plugins:
- pre:
- pluginNames:
- - rate limit
- - access
- post:
- groupNames:
- - group2
-methods:
- - httpVerb: GET
- resourcePath: '/api/v1/test-dubbo/friend2'
- onAir: true
- timeout: 1000ms
- inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
- integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
-
-### 2.4 Modify Resource
+### 2.3 Get API Route Details
**Request**:
```http
-PUT /config/api/resource? HTTP/1.1
+GET /config/api/route/detail?name=<route-name>&scope=draft HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
```
-**Form Data**:
+The name parameter is the immutable route identity. Set scope=published to read the published version.
-```text
-Content-Disposition: form-data; name="content"
-id: 1
-path: '/api/v1/test-dubbo/friend'
-type: restful
-description: update
-timeout: 1000ms
-plugins:
- pre:
- pluginNames:
- - rate limit
- - access
- post:
- groupNames:
- - group2
-methods:
- - httpVerb: GET
- onAir: true
- timeout: 1000ms
- inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
- integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
-
-### 2.5 Delete Resource
+### 2.4 Create API Route Draft
**Request**:
```http
-DELETE /config/api/resource/?resourceId=2 HTTP/1.1
+POST /config/api/route HTTP/1.1
Host: 127.0.0.1:8080
+Content-Type: application/json
cache-control: no-cache
```
-## III. Method Related
+Send an AdminRouteBinding object as JSON. The endpoint also accepts the object wrapped as {"object": <AdminRouteBinding>, "expectedRevision": <revision>}, or YAML in the content form field.
-### 3.1 Get Method List for a Resource
+### 2.5 Modify API Route Draft
**Request**:
```http
-GET /config/api/resource/method/list?resourceId=1 HTTP/1.1
+PUT /config/api/route?name=<route-name> HTTP/1.1
Host: 127.0.0.1:8080
+Content-Type: application/json
cache-control: no-cache
```
-### 3.2 Get Method Details
+Send the updated AdminRouteBinding object. The name query parameter must match metadata.name and cannot be changed. expectedRevision may be supplied in the wrapped JSON body, as a query parameter, or through the If-Match header to reject stale updates.
+
+### 2.6 Validate or Preview an API Route
**Request**:
```http
-GET /config/api/resource/method/detail?resourceId=1&methodId=2 HTTP/1.1
+POST /config/api/route/validate HTTP/1.1
+POST /config/api/route/preview HTTP/1.1
Host: 127.0.0.1:8080
+Content-Type: application/json
cache-control: no-cache
```
-### 3.3 Create Method
+Both endpoints accept an AdminRouteBinding object and do not write to etcd. Validation returns the normalized object with schema defaults. Preview returns the normalized object and the generated legacy Pixiu YAML.
+
+### 2.7 Get API Route Status or Diff
**Request**:
```http
-POST /config/api/resource/method/?resourceId=1 HTTP/1.1
+GET /config/api/route/status?name=<route-name> HTTP/1.1
+GET /config/api/route/diff?name=<route-name> HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
```
-**Form Data**:
+Status reports the draft and published state for one route. Diff returns the field-level differences between its draft and published objects.
-```text
-Content-Disposition: form-data; name="content"
-httpVerb: PUT
-resourcePath: '/api/v1/test-dubbo/friend'
-onAir: true
-timeout: 1000ms
-inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
-integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
-
-### 3.4 Modify Method
+### 2.8 Publish One API Route
**Request**:
```http
-PUT /config/api/resource/method/?resourceId=1 HTTP/1.1
+PUT /config/api/route/publish?name=<route-name>&expectedRevision=<revision> HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
```
-**Form Data**:
+Publishing validates the route and atomically updates its published AdminRouteBinding and generated runtime configuration in one etcd transaction. expectedRevision is optional and can be used to reject a stale draft. There is no full API-route publish endpoint.
-```text
-Content-Disposition: form-data; name="content"
-id: 2
-httpVerb: PUT
-resourcePath: '/api/v1/test-dubbo/friend'
-onAir: true
-timeout: 300ms
-inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
-integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
+Before publishing, Admin checks for conflicts with legacy runtime Resource/Method records. A conflicting HTTP method and path must be removed from the old runtime configuration before the new route can be published.
-### 3.5 Delete Method
+### 2.9 Delete One API Route
**Request**:
```http
-DELETE /config/api/resource/method/?resourceId=1&methodId=2 HTTP/1.1
+DELETE /config/api/route?name=<route-name>&expectedRevision=<revision> HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
```
-## IV. PluginGroup and Plugin Related
+Deletion immediately removes the route draft and its published runtime configuration in one etcd transaction. The client should ask for confirmation before sending this request.
+expectedRevision is optional; when supplied, it prevents deleting a draft that changed after it was read.
+
+## III. PluginGroup and Plugin Related
-### 4.1 Get PluginGroup List
+### 3.1 Get PluginGroup List
**Request**:
@@ -301,7 +190,7 @@ Host: 127.0.0.1:8080
cache-control: no-cache
```
-### 4.2 Get PluginGroup Details
+### 3.2 Get PluginGroup Details
**Request**:
@@ -311,7 +200,7 @@ Host: 127.0.0.1:8080
cache-control: no-cache
```
-### 4.3 Create PluginGroup
+### 3.3 Create PluginGroup
**Request**:
@@ -338,7 +227,7 @@ plugins:
externalLookupName: "ExternalPluginAccess"
```
-### 4.4 Modify PluginGroup
+### 3.4 Modify PluginGroup
**Request**:
@@ -365,7 +254,7 @@ plugins:
externalLookupName: "ExternalPluginAccess"
```
-### 4.5 Delete PluginGroup
+### 3.5 Delete PluginGroup
**Request**:
@@ -375,11 +264,23 @@ Host: 127.0.0.1:8080
cache-control: no-cache
```
-## V. OPA Policy
+### 3.6 Publish PluginGroup
+
+**Request**:
+
+```http
+PUT /config/api/plugin_group/publish HTTP/1.1
+Host: 127.0.0.1:8080
+cache-control: no-cache
+```
+
+This legacy endpoint publishes the staged PluginGroup configuration to the published namespace. It is independent of API route publication.
+
+## IV. OPA Policy
OPA policy APIs proxy requests to the OPA server. If `server_url` or `policy_id` is not provided, defaults are used (`http://opa:8181` and `pixiu-authz`).
-### 5.1 Get OPA Policy
+### 4.1 Get OPA Policy
**Request**:
@@ -406,7 +307,7 @@ cache-control: no-cache
If the policy does not exist, `data` will be an empty string.
-### 5.2 Create or Update OPA Policy
+### 4.2 Create or Update OPA Policy
**Request**:
@@ -434,7 +335,7 @@ Optional form fields:
* `server_url`
* `bearer_token`
-### 5.3 Delete OPA Policy
+### 4.3 Delete OPA Policy
**Request**:
@@ -450,9 +351,9 @@ cache-control: no-cache
* `server_url`: OPA server URL (optional)
* `bearer_token`: OPA bearer token (optional)
-## VI. xDS Diagnostics
+## V. xDS Diagnostics
-### 6.1 Get xDS Publication Status
+### 5.1 Get xDS Publication Status
This authenticated endpoint returns xDS listener availability, the last-good
snapshot version, resource counts, publication timestamps, the latest listener
diff --git a/admin/API_CN.md b/admin/API_CN.md
index c6f41a743..d98b35435 100644
--- a/admin/API_CN.md
+++ b/admin/API_CN.md
@@ -2,11 +2,9 @@
[English](API.md) | **中文**
-本接口文档详细描述了 Pixiu 管理平台的后端 API 操作,包括获取、创建、修改、删除资源(Resource)、方法(Method)及插件组(PluginGroup)的接口。Pixiu
-平台提供了一整套 API 来帮助用户管理 API 网关的资源映射、插件配置以及请求处理。文档中的示例涵盖了常见的请求与响应格式,并介绍了如何使用
-Postman 进行接口测试。
+本接口文档详细描述 Pixiu 管理平台的后端 API 操作,包括 API 路由绑定(AdminRouteBinding)、插件组(PluginGroup)和 OPA 策略等接口。Pixiu 平台提供相关 API 来管理 API 网关路由映射、插件配置和请求处理。文档中的示例涵盖常见的请求与响应格式,并介绍如何使用 Postman 测试接口。
-无论是创建新资源、修改现有配置,还是管理插件组,本文档都提供了清晰的步骤和必要的 API 细节,方便开发者快速上手并进行集成。
+无论是创建新的 API 路由、修改现有配置,还是管理插件组,本文档都提供清晰的步骤和必要的 API 细节,方便开发者快速上手并进行集成。
更多的 API 具体介绍请参考 [Swagger 文档](./doc/swagger.json)
@@ -60,240 +58,129 @@ name: pixiu
description: pixiu111 sample
```
-## 二、Resource
+## 二、API 路由
-### 2.1 获取 Resource 列表
+API Router 配置使用 AdminRouteBinding 对象管理。旧 Resource/Method Admin CRUD 接口已由新模型替代;已有运行时 Resource/Method 配置不会自动导入新草稿模型,需要通过新接口管理的路由应重新创建为 AdminRouteBinding。新路由发布后仍会生成 Pixiu 使用的旧格式运行时配置。
-**请求**:
-
-```http
-GET /config/api/resource/list HTTP/1.1
-Host: 127.0.0.1:8080
-cache-control: no-cache
-```
-
-### 2.2 获取 Resource 详情
+### 2.1 获取 API 路由 Schema
**请求**:
```http
-GET /config/api/resource/detail?resourceId=1 HTTP/1.1
+GET /config/api/route/schema HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
```
-### 2.3 创建 Resource
+返回数据包含已注册的 Admin 对象 Schema,其中包括编辑器使用的 AdminRouteBinding Schema。
+
+### 2.2 获取 API 路由列表
**请求**:
```http
-POST /config/api/resource/ HTTP/1.1
+GET /config/api/route/list?scope=draft HTTP/1.1
Host: 127.0.0.1:8080
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
cache-control: no-cache
```
-**表单数据**:
-
-```text
-Content-Disposition: form-data; name="content"
-path: '/api/v1/test-dubbo/friend2'
-type: restful
-description: user
-timeout: 100ms
-plugins:
- pre:
- pluginNames:
- - rate limit
- - access
- post:
- groupNames:
- - group2
-methods:
- - httpVerb: GET
- resourcePath: '/api/v1/test-dubbo/friend2'
- onAir: true
- timeout: 1000ms
- inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
- integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
+scope=draft(默认值)查询草稿,scope=published 查询已发布路由。接口同时兼容旧的 unpublished 参数:1 表示草稿,0 表示已发布路由。草稿列表包含由后端计算的发布状态。
-### 2.4 修改 Resource
+### 2.3 获取 API 路由详情
**请求**:
```http
-PUT /config/api/resource? HTTP/1.1
+GET /config/api/route/detail?name=<路由名>&scope=draft HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
```
-**表单数据**:
-
-```text
-Content-Disposition: form-data; name="content"
-id: 1
-path: '/api/v1/test-dubbo/friend'
-type: restful
-description: update
-timeout: 1000ms
-plugins:
- pre:
- pluginNames:
- - rate limit
- - access
- post:
- groupNames:
- - group2
-methods:
- - httpVerb: GET
- onAir: true
- timeout: 1000ms
- inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
- integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
+name 是不可变的路由标识。查询已发布版本时将 scope 设为 published。
-### 2.5 删除 Resource
+### 2.4 创建 API 路由草稿
**请求**:
```http
-DELETE /config/api/resource/?resourceId=2 HTTP/1.1
+POST /config/api/route HTTP/1.1
Host: 127.0.0.1:8080
+Content-Type: application/json
cache-control: no-cache
```
-## 三、Method 相关
+请求体为 AdminRouteBinding JSON 对象。也可使用 {"object": <AdminRouteBinding>, "expectedRevision": <revision>} 包装对象,或通过表单字段 content 提交 YAML。
-### 3.1 查询某个 Resource 下的 Method 列表
+### 2.5 修改 API 路由草稿
**请求**:
```http
-GET /config/api/resource/method/list?resourceId=1 HTTP/1.1
+PUT /config/api/route?name=<路由名> HTTP/1.1
Host: 127.0.0.1:8080
+Content-Type: application/json
cache-control: no-cache
```
-### 3.2 查询 Method 详情
+请求体为更新后的 AdminRouteBinding 对象。name 查询参数必须与 metadata.name 一致且不可修改。expectedRevision 可放在包装后的 JSON 请求体、查询参数或 If-Match 请求头中,用于拒绝过期更新。
+
+### 2.6 校验或预览 API 路由
**请求**:
```http
-GET /config/api/resource/method/detail?resourceId=1&methodId=2 HTTP/1.1
+POST /config/api/route/validate HTTP/1.1
+POST /config/api/route/preview HTTP/1.1
Host: 127.0.0.1:8080
+Content-Type: application/json
cache-control: no-cache
```
-### 3.3 创建 Method
+两个接口都接收 AdminRouteBinding 对象,不会写入 etcd。校验接口返回包含 Schema 默认值的规范化对象;预览接口返回规范化对象以及生成的 Pixiu 旧格式 YAML。
+
+### 2.7 获取 API 路由状态或 Diff
**请求**:
```http
-POST /config/api/resource/method/?resourceId=1 HTTP/1.1
+GET /config/api/route/status?name=<路由名> HTTP/1.1
+GET /config/api/route/diff?name=<路由名> HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
```
-**表单数据**:
-
-```text
-Content-Disposition: form-data; name="content"
-httpVerb: PUT
-resourcePath: '/api/v1/test-dubbo/friend'
-onAir: true
-timeout: 1000ms
-inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
-integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
+状态接口返回单条路由的草稿和已发布状态;Diff 接口返回草稿与已发布对象之间的字段差异。
-### 3.4 修改 Method
+### 2.8 发布单条 API 路由
**请求**:
```http
-PUT /config/api/resource/method/?resourceId=1 HTTP/1.1
+PUT /config/api/route/publish?name=<路由名>&expectedRevision=<revision> HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
-Content-Type: multipart/form-data; boundary=-WebKitFormBoundary7MA4YWxkTrZu0gW
```
-**表单数据**:
+发布前会校验路由,并通过一个 etcd 事务原子更新该路由的已发布 AdminRouteBinding 和生成的运行时配置。expectedRevision 为可选项,可用于拒绝过期草稿。系统不提供 API 路由全量发布接口。
-```text
-Content-Disposition: form-data; name="content"
-id: 2
-httpVerb: PUT
-resourcePath: '/api/v1/test-dubbo/friend'
-onAir: true
-timeout: 300ms
-inboundRequest:
- requestType: http
- queryStrings:
- - name: name
- required: true
-integrationRequest:
- requestType: http
- host: 127.0.0.1:8889
- path: /UserProvider/GetUserByName
- mappingParams:
- - name: queryStrings.name
- mapTo: queryStrings.name
- group: "test"
- version: 1.0.0
-```
+发布前还会检查旧运行时 Resource/Method 配置冲突。若 HTTP 方法和路径冲突,应先从旧运行时配置中移除对应路由。
-### 3.5 删除 Method
+### 2.9 删除单条 API 路由
**请求**:
```http
-DELETE /config/api/resource/method/?resourceId=1&methodId=2 HTTP/1.1
+DELETE /config/api/route?name=<路由名>&expectedRevision=<revision> HTTP/1.1
Host: 127.0.0.1:8080
cache-control: no-cache
```
-## 四、PluginGroup 和 Plugin 相关
+删除会通过一个 etcd 事务立即移除路由草稿和对应的已发布运行时配置。客户端发送请求前应先向用户确认删除。
+expectedRevision 为可选项;如果提供,可避免删除读取后已被其他请求修改的草稿。
+
+## 三、PluginGroup 和 Plugin 相关
-### 4.1 查看 PluginGroup 列表
+### 3.1 查看 PluginGroup 列表
**请求**:
@@ -303,7 +190,7 @@ Host: 127.0.0.1:8080
cache-control: no-cache
```
-### 4.2 查看 PluginGroup 详情
+### 3.2 查看 PluginGroup 详情
**请求**:
@@ -313,7 +200,7 @@ Host: 127.0.0.1:8080
cache-control: no-cache
```
-### 4.3 创建 PluginGroup
+### 3.3 创建 PluginGroup
**请求**:
@@ -340,7 +227,7 @@ plugins:
externalLookupName: "ExternalPluginAccess"
```
-### 4.4 修改 PluginGroup
+### 3.4 修改 PluginGroup
**请求**:
@@ -367,7 +254,7 @@ plugins:
externalLookupName: "ExternalPluginAccess"
```
-### 4.5 删除 PluginGroup
+### 3.5 删除 PluginGroup
**请求**:
@@ -377,11 +264,23 @@ Host: 127.0.0.1:8080
cache-control: no-cache
```
-## 五、OPA 策略
+### 3.6 发布 PluginGroup
+
+**请求**:
+
+```http
+PUT /config/api/plugin_group/publish HTTP/1.1
+Host: 127.0.0.1:8080
+cache-control: no-cache
+```
+
+该旧接口将暂存空间中的 PluginGroup 配置发布到已发布空间,与 API 路由发布相互独立。
+
+## 四、OPA 策略
OPA 策略接口会代理请求到 OPA 服务端。未提供 `server_url` 或 `policy_id` 时,会使用默认值(`http://opa:8181` 和 `pixiu-authz`)。
-### 5.1 获取 OPA 策略
+### 4.1 获取 OPA 策略
**请求**:
@@ -408,7 +307,7 @@ cache-control: no-cache
若策略不存在,`data` 返回空字符串。
-### 5.2 新增或更新 OPA 策略
+### 4.2 新增或更新 OPA 策略
**请求**:
@@ -436,7 +335,7 @@ default allow := false
* `server_url`
* `bearer_token`
-### 5.3 删除 OPA 策略
+### 4.3 删除 OPA 策略
**请求**:
@@ -452,12 +351,11 @@ cache-control: no-cache
* `server_url`: OPA 服务地址(可选)
* `bearer_token`: OPA Bearer Token(可选)
-## 六、xDS 诊断
+## 五、xDS 诊断
-### 6.1 获取 xDS 发布状态
+### 5.1 获取 xDS 发布状态
-该接口需要 Admin JWT,返回 xDS 监听状态、最近一次成功发布的快照版本、资源数量、
-发布时间、最近一次监听或候选配置错误,以及各条 xDS 资源链路的明确支持状态。
+**请求**:
```http
GET /config/api/xds/status HTTP/1.1
@@ -465,8 +363,9 @@ Host: 127.0.0.1:8080
token: <admin-jwt>
```
-`ready` 只有在 xDS 端口已监听且至少一个快照成功发布时为 true;`degraded`
-表示监听启动或新候选配置失败。
+该认证接口返回 xDS 监听状态、最近一次成功发布的快照版本、资源数量、发布时间、最近一次监听或候选配置错误,以及各条 xDS 资源链路的支持状态。
+
+ready 只有在 xDS 端口已监听且至少一个快照成功发布时为 true;degraded 表示监听启动或新候选配置失败。
**返回**:
diff --git a/admin/controller/configInfo/configInfo.go b/admin/controller/configInfo/configInfo.go
index 3dfad9bbd..65c2f80af 100644
--- a/admin/controller/configInfo/configInfo.go
+++ b/admin/controller/configInfo/configInfo.go
@@ -18,23 +18,17 @@
package configInfo
import (
- "encoding/json"
"net/http"
- "strconv"
- "strings"
)
import (
"github.com/gin-gonic/gin"
-
- "github.com/pkg/errors"
)
import (
adminconfig "github.com/apache/dubbo-go-pixiu/admin/config"
"github.com/apache/dubbo-go-pixiu/admin/logic"
"github.com/apache/dubbo-go-pixiu/pkg/common/yaml"
- "github.com/apache/dubbo-go-pixiu/pkg/config"
"github.com/apache/dubbo-go-pixiu/pkg/logger"
)
@@ -84,477 +78,3 @@ func SetBaseInfo(c *gin.Context) {
}
c.JSON(http.StatusOK, adminconfig.WithRet("success"))
}
-
-// @Tags Config
-// @Summary get all resource list
-// @Description Retrieve the list of resources. Use the unpublished parameter to control whether to include unpublished or published resources.
-// @Produce application/json
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {string} string "JSON array"
-// @Router /config/api/resource/list [get]
-// GetResourceList get all resource list
-func GetResourceList(c *gin.Context) {
- unpublished := getUnpublishedVal(c)
-
- res, err := logic.BizGetResourceList(unpublished)
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- data, _ := json.Marshal(res)
- c.JSON(http.StatusOK, adminconfig.WithRet(string(data)))
-}
-
-// @Tags Config
-// @Summary get resource detail with yml
-// @Description get resource details according to resource ID and return the YAML
-// @Produce application/json
-// @Param resourceId query int true "ResourceID"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {string} string "YAML content"
-// @Router /config/api/resource/detail [get]
-// GetResourceDetail get resource detail with yml
-func GetResourceDetail(c *gin.Context) {
- unpublished := getUnpublishedVal(c)
- id := c.Query(logic.ResourceID)
- res, err := logic.BizGetResourceDetail(id, unpublished)
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- c.JSON(http.StatusOK, adminconfig.WithRet(res))
-}
-
-// @Tags Config
-// @Summary create resource
-// @Description create a resource by passing the Resource's YAML via the form's content field (simultaneously writing to the staging area and production area).
-// @Accept application/x-www-form-urlencoded
-// @Produce application/json
-// @Param content formData string true "Resource YAML"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {object} string
-// @Failure 200 {object} string
-// @Router /config/api/resource [post]
-// CreateResourceInfo create resource
-func CreateResourceInfo(c *gin.Context) {
- body := c.PostForm("content")
- unpublished := getUnpublishedVal(c)
-
- res := &config.Resource{}
- err := yaml.UnmarshalYML([]byte(body), res)
- if err != nil {
- logger.Warnf("read body err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
-
- var setErr1, setErr2 error // err1 represent write publish space, err2 represent write unpublished space
- if unpublished {
- setErr2 = logic.BizSetResourceInfo(res, true, true)
- } else {
- setErr1 = logic.BizSetResourceInfo(res, true, false)
- setErr2 = logic.BizSetResourceInfo(res, true, true)
- }
-
- //setErr := logic.BizSetResourceInfo(res, true, unpublished)
- if setErr1 != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(setErr1))
- return
- }
- if setErr2 != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(setErr2))
- return
- }
- c.JSON(http.StatusOK, adminconfig.WithRet("Success"))
-}
-
-// @Tags Config
-// @Summary modify resource
-// @Description modify resource content, where content is the YAML of the Resource. Use resourceId to specify the resource to be modified.
-// @Accept application/x-www-form-urlencoded
-// @Produce application/json
-// @Param resourceId query int false "resource ID"
-// @Param content formData string true "Resource YAML"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {object} string
-// @Router /config/api/resource [put]
-// ModifyResourceInfo modify resource
-func ModifyResourceInfo(c *gin.Context) {
- id := c.Query(logic.ResourceID)
- body := c.PostForm("content")
- unpublished := getUnpublishedVal(c)
-
- res := &config.Resource{}
- err := yaml.UnmarshalYML([]byte(body), res)
- if err != nil {
- logger.Warnf("read body err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
-
- if id != "" {
- res.ID, err = strconv.Atoi(id)
- if err != nil {
- logger.Warnf("resourceID not number err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- }
-
- old, err := getResourceDetail(id, unpublished)
- if err == nil && old != nil {
- // when resource path change, should modify all method below it
- if old.Path != res.Path {
- afterResourcePathChange(id, res.Path, unpublished)
- }
- }
-
- setErr := logic.BizSetResourceInfo(res, false, unpublished)
- if setErr != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(setErr))
- return
- }
-
- c.JSON(http.StatusOK, adminconfig.WithRet("Success"))
-}
-
-func afterResourcePathChange(resourceId, path string, unpublished bool) {
- mList, err := logic.BizGetMethodList(resourceId, unpublished)
- if err != nil {
- return
- }
- for i := range mList {
- m := &mList[i]
- m.ResourcePath = path
- setErr := logic.BizSetResourceMethod(resourceId, m, false, unpublished)
- if setErr != nil {
- logger.Warnf("afterResourcePathChange err, %v\n", err)
- continue
- }
- }
-}
-
-// @Tags Config
-// @Summary delete resource
-// @Description delete resources by ID. When unpublished is 1, this indicates deleting configurations for unpublished spaces (requires checking published spaces).
-// @Produce application/json
-// @Param resourceId query int true "resource ID"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {object} string
-// @Router /config/api/resource [delete]
-// DeleteResourceInfo delete resource
-func DeleteResourceInfo(c *gin.Context) {
- id := c.Query(logic.ResourceID)
- unpublished := getUnpublishedVal(c)
- if unpublished {
- // Check whether the configuration has been released when deleting the configuration
- old, err := getResourceDetail(id, false)
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- if old != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(errors.New("The configuration has been published and cannot be deleted")))
- return
- }
- }
- err := logic.BizDeleteResourceInfo(id, unpublished)
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
-
- c.JSON(http.StatusOK, adminconfig.WithRet("Success"))
-}
-
-// @Tags Config
-// @Summary get all method list below one resource
-// @Description get the list of methods under the specified resource
-// @Produce application/json
-// @Param resourceId query int true "resource ID"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {string} string "JSON array"
-// @Router /config/api/resource/method/list [get]
-// GetMethodList get all method list below one resource
-func GetMethodList(c *gin.Context) {
- resourceId := c.Query(logic.ResourceID) // unique id
- unpublished := getUnpublishedVal(c)
-
- res, err := logic.BizGetMethodList(resourceId, unpublished)
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- data, _ := json.Marshal(res)
- c.JSON(http.StatusOK, adminconfig.WithRet(string(data)))
-}
-
-// @Tags Config
-// @Summary get method detail with yml
-// @Description get method details based on resourceId and methodId, returning YAML.
-// @Produce application/json
-// @Param resourceId query int true "resource ID"
-// @Param methodId query int true "method ID"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {string} string "YAML content"
-// @Router /config/api/resource/method/detail [get]
-// GetMethodDetail get method detail with yml
-func GetMethodDetail(c *gin.Context) {
- resourceId := c.Query(logic.ResourceID)
- methodId := c.Query(logic.MethodID) // unique id
- unpublished := getUnpublishedVal(c)
- res, err := logic.BizGetMethodDetail(resourceId, methodId, unpublished)
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- c.JSON(http.StatusOK, adminconfig.WithRet(res))
-}
-
-// @Tags Config
-// @Summary delete method
-// @Description Deleting a method under a resource, where `unpublished` equals 1 indicates removing the configuration for unpublished spaces (requires checking published spaces).
-// @Produce application/json
-// @Param resourceId query int true "ResourceID"
-// @Param methodId query int true "MethodID"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {object} string
-// @Router /config/api/resource/method [delete]
-// DeleteResourceInfo delete method
-func DeleteMethodInfo(c *gin.Context) {
- resourceId := c.Query(logic.ResourceID)
- methodId := c.Query(logic.MethodID)
- unpublished := getUnpublishedVal(c)
- if unpublished {
- old, err := logic.BizGetMethodDetail(resourceId, methodId, false)
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- if old != "" {
- c.JSON(http.StatusOK, adminconfig.WithError(errors.New("The configuration has been published and cannot be deleted")))
- return
- }
- }
- err := logic.BizDeleteMethodInfo(resourceId, methodId, unpublished)
-
- if err != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- c.JSON(http.StatusOK, adminconfig.WithRet("Success"))
-}
-
-// @Tags Config
-// @Summary create method
-// @Description create a method under the specified resource, where content is the YAML for Method.
-// @Accept application/x-www-form-urlencoded
-// @Produce application/json
-// @Param resourceId query int true "ResourceID"
-// @Param content formData string true "Method YAML"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {object} string
-// @Router /config/api/resource/method [post]
-// CreateMethodInfo create method
-func CreateMethodInfo(c *gin.Context) {
- body := c.PostForm("content")
- resourceId := c.Query(logic.ResourceID)
- unpublished := getUnpublishedVal(c)
-
- res := &config.Method{}
- err := yaml.UnmarshalYML([]byte(body), res)
-
- if err != nil {
- logger.Warnf("read body err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
-
- resource, err := getResourceDetail(resourceId, unpublished)
- if err != nil {
- logger.Warnf("CreateMethodInfo can't query resource err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- res.ResourcePath = resource.Path
-
- setErr := logic.BizSetResourceMethod(resourceId, res, true, unpublished)
- if setErr != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(setErr))
- return
- }
- c.JSON(http.StatusOK, adminconfig.WithRet("Success"))
-}
-
-func getResourceDetail(id string, unpublished bool) (*config.Resource, error) {
- res, err := logic.BizGetResourceDetail(id, unpublished)
- if err != nil {
- return nil, err
- }
-
- resource := &config.Resource{}
- err = yaml.UnmarshalYML([]byte(res), resource)
- if err != nil {
- return nil, err
- }
-
- return resource, nil
-}
-
-// @Tags Config
-// @Summary modify method
-// @Description Modify the specified method, where content is the YAML for Method.
-// @Accept application/x-www-form-urlencoded
-// @Produce application/json
-// @Param resourceId query int true "ResourceID"
-// @Param methodId query int false "MethodID"
-// @Param content formData string true "Method YAML"
-// @Param unpublished formData string false "1: unpublished; 0 or empty: published"
-// @Success 200 {object} string
-// @Router /config/api/resource/method [put]
-// ModifyMethodInfo modify method
-func ModifyMethodInfo(c *gin.Context) {
- body := c.PostForm("content")
- resourceId := c.Query(logic.ResourceID)
- methodId := c.Query(logic.MethodID)
- unpublished := getUnpublishedVal(c)
-
- res := &config.Method{}
- err := yaml.UnmarshalYML([]byte(body), res)
- if err != nil {
- logger.Warnf("read body err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
-
- if methodId != "" {
- res.ID, err = strconv.Atoi(methodId)
- if err != nil {
- logger.Warnf("methodID not number err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- }
-
- resource, err := getResourceDetail(resourceId, unpublished)
- if err != nil {
- logger.Warnf("CreateMethodInfo can't query resource err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- res.ResourcePath = resource.Path
-
- setErr := logic.BizSetResourceMethod(resourceId, res, false, unpublished)
- if setErr != nil {
- c.JSON(http.StatusOK, adminconfig.WithError(setErr))
- return
- }
- c.JSON(http.StatusOK, adminconfig.WithRet("Success"))
-}
-
-// @Tags Config
-// @Summary determine the configuration type of the current operation
-// @Description internal function, no external documentation required
-// getUnpublishedVal Determine the configuration type of the current operation
-func getUnpublishedVal(c *gin.Context) bool {
- // The front-end request carries the unpublished field to determine which configuration is currently operating
- // 1 represent true (unpublished, delay publish), 0 represent false (published, direct publish)
- unpublishedVal := c.PostForm("unpublished")
- if strings.EqualFold(unpublishedVal, "1") {
- return true
- } else {
- return false
- }
-}
-
-// @Tags Config
-// @Summary publish all configuration information
-// @Description publish resources from unpublished spaces to published spaces
-// @Produce application/json
-// @Success 200 {object} string
-// @Router /config/api/resource/publish [put]
-// BatchReleaseResource Publish all configuration information
-func BatchReleaseResource(c *gin.Context) {
- fromKList, fromVList, fromErr := logic.BRGetResourceList(true) // from represent unpublished space
- toKList, toVList, _ := logic.BRGetResourceList(false) // to represent published space
- // Do not handle toList errors
- if fromErr != nil {
- logger.Warnf("Batch Release Resource err, %v\n", fromErr)
- c.JSON(http.StatusOK, adminconfig.WithError(fromErr))
- return
- }
- // todo Optimize comparison method to reduce time complexity
- for i, fromK := range fromKList {
- fromV := fromVList[i]
- fromKTmp := strings.Split(fromK, "/")
- flag := false
- for j, toK := range toKList {
- toV := toVList[j]
- toKTmp := strings.Split(toK, "/")
- flag = strings.EqualFold(fromKTmp[len(fromKTmp)-1], toKTmp[len(toKTmp)-1])
- if flag {
- if !strings.EqualFold(fromV, toV) {
- err := logic.BRUpdate(toK, fromV)
- if err != nil {
- logger.Warnf("Batch Release Resource err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- }
- break
- }
- }
- if !flag {
- err := logic.BRCreate(fromKTmp[len(fromKTmp)-1], fromV, logic.Resources)
- if err != nil {
- logger.Warnf("Batch Release Resource err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- return
- }
- }
- }
-}
-
-// @Tags Config
-// @Summary batch Release Method Config
-// @Description TODO: unimplemented
-// @Produce application/json
-// @Success 200 {object} string
-// @Router /config/api/resource/method/publish [put]
-// BatchReleaseMethod Batch Release Method Config
-func BatchReleaseMethod(c *gin.Context) {
- // todo
-}
-
-// @Tags Config
-// @Summary batch Release PluginGroup Config
-// @Description publish the PluginGroup from the unpublished space to the published space.
-// @Produce application/json
-// @Success 200 {object} string
-// @Router /config/api/plugin_group/publish [put]
-// BatchReleasePluginGroup Batch Release PluginGroup Config
-func BatchReleasePluginGroup(c *gin.Context) {
- fromKList, fromVList, fromErr := logic.BRGetPluginGroupList(true) // from represent unpublished space
- toKList, toVList, _ := logic.BRGetPluginGroupList(false) // to represent published space
- if fromErr != nil {
- logger.Warnf("Batch Release PluginGroup err, %v\n", fromErr)
- c.JSON(http.StatusOK, adminconfig.WithError(fromErr))
- return
- }
- fromKTmp := strings.Split(fromKList[0], "/")
- if toKList == nil {
- err := logic.BRCreate(fromKTmp[len(fromKTmp)-1], fromVList[0], logic.PluginGroup)
- if err != nil {
- logger.Warnf("Batch Release PluginGroup err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- }
- return
- }
- if !strings.EqualFold(fromVList[0], toVList[0]) {
- err := logic.BRUpdate(toKList[0], fromVList[0])
- if err != nil {
- logger.Warnf("Batch Release PluginGroup err, %v\n", err)
- c.JSON(http.StatusOK, adminconfig.WithError(err))
- }
- }
-}
diff --git a/admin/controller/configInfo/configInfo_test.go b/admin/controller/configInfo/plugin_group.go
similarity index 50%
copy from admin/controller/configInfo/configInfo_test.go
copy to admin/controller/configInfo/plugin_group.go
index 1f82312e8..d26c8228c 100644
--- a/admin/controller/configInfo/configInfo_test.go
+++ b/admin/controller/configInfo/plugin_group.go
@@ -18,31 +18,31 @@
package configInfo
import (
- "fmt"
- "strings"
- "testing"
+ "net/http"
)
-func Test_method1(t *testing.T) {
- var list1, list2 []string
- list1 = append(list1, "a")
- list2 = nil
- for _, v1 := range list1 {
- for _, v := range list2 {
- fmt.Println("in side" + v)
- //t.Log("inside" + v)
- }
- fmt.Println(v1)
- //t.Log("outside" + v1)
- }
-}
+import (
+ "github.com/gin-gonic/gin"
+)
-func Test_regx_split(t *testing.T) {
- txt := "/config/api/resources/1/xxx"
- //re := regexp.MustCompile("\\(?<=config\\).+\\(?=resources\\)")
- pre := "/config/api/"
- //re := regexp.MustCompile("^/resources/1")
- split := strings.TrimPrefix(txt, pre)
- //split := re.Split(txt,-1)
- fmt.Println(split)
+import (
+ adminconfig "github.com/apache/dubbo-go-pixiu/admin/config"
+ "github.com/apache/dubbo-go-pixiu/admin/logic"
+ "github.com/apache/dubbo-go-pixiu/pkg/logger"
+)
+
+// @Tags Config
+// @Summary batch Release PluginGroup Config
+// @Description publish the PluginGroup from the unpublished space to the published space.
+// @Produce application/json
+// @Success 200 {object} string
+// @Router /config/api/plugin_group/publish [put]
+// BatchReleasePluginGroup publishes the staged PluginGroup configuration.
+func BatchReleasePluginGroup(c *gin.Context) {
+ if err := logic.BizPublishPluginGroupConfig(); err != nil {
+ logger.Warnf("Batch Release PluginGroup err, %v", err)
+ c.JSON(http.StatusOK, adminconfig.WithError(err))
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet("success"))
}
diff --git a/admin/controller/configInfo/route_binding.go b/admin/controller/configInfo/route_binding.go
new file mode 100644
index 000000000..0e28a7b9b
--- /dev/null
+++ b/admin/controller/configInfo/route_binding.go
@@ -0,0 +1,481 @@
+/*
+ * 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"
+ "fmt"
+ "io"
+ "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"
+ "github.com/apache/dubbo-go-pixiu/pkg/config/schema"
+)
+
+const maxRouteBindingRequestBytes = 4 << 20
+
+type routeBindingRequest struct {
+ Object *schema.AdminObject `json:"object"`
+ ExpectedRevision int64 `json:"expectedRevision"`
+}
+
+type routeBindingValidationResponse struct {
+ Valid bool `json:"valid"`
+ Object schema.AdminObject `json:"object"`
+}
+
+type routeBindingPreviewResponse struct {
+ Object schema.AdminObject `json:"object"`
+ YAML string `json:"yaml"`
+}
+
+type routeBindingErrorResponse struct {
+ Message string `json:"message"`
+ Issues []schema.ValidationIssue `json:"issues,omitempty"`
+}
+
+// GetRouteBindingSchema returns the AdminRouteBinding form and validation
+// schema. It has no etcd dependency so the UI can render before a config
+// namespace contains any routes.
+//
+// @Tags Config
+// @Summary get API route binding schema
+// @Produce application/json
+// @Success 200 {object} string
+// @Router /config/api/route/schema [get]
+func GetRouteBindingSchema(c *gin.Context) {
+ registry, err := schema.DefaultRegistry()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(registry.List()))
+}
+
+// GetRouteBindingList returns high-level route bindings from the draft or
+// published namespace. The default scope is draft; pass scope=published or
+// unpublished=0 to read the published snapshot.
+//
+// @Tags Config
+// @Summary get API route binding list
+// @Produce application/json
+// @Param scope query string false "draft or published"
+// @Param unpublished query string false "1 for draft, 0 for published"
+// @Success 200 {object} string
+// @Router /config/api/route/list [get]
+func GetRouteBindingList(c *gin.Context) {
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ bindings, err := store.List(c.Request.Context(), routeBindingUnpublished(c))
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(bindings))
+}
+
+// GetRouteBindingDetail returns one high-level route binding by metadata.name.
+//
+// @Tags Config
+// @Summary get API route binding detail
+// @Produce application/json
+// @Param name query string true "Route binding name"
+// @Param scope query string false "draft or published"
+// @Param unpublished query string false "1 for draft, 0 for published"
+// @Success 200 {object} string
+// @Router /config/api/route/detail [get]
+func GetRouteBindingDetail(c *gin.Context) {
+ name := c.Query("name")
+ if name == "" {
+ name = c.Param("name")
+ }
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ binding, err := store.Get(c.Request.Context(), name, routeBindingUnpublished(c))
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(binding))
+}
+
+// CreateRouteBinding validates and saves one route binding in the draft
+// namespace. The JSON body may be either an AdminObject or
+// {"object": AdminObject, "expectedRevision": number}; a form content field
+// containing the same object as YAML is also accepted for Admin compatibility.
+//
+// @Tags Config
+// @Summary create API route binding draft
+// @Accept application/json
+// @Produce application/json
+// @Success 200 {object} string
+// @Router /config/api/route [post]
+func CreateRouteBinding(c *gin.Context) {
+ object, expectedRevision, err := decodeRouteBindingRequest(c)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ binding, err := store.SaveDraft(c.Request.Context(), object, true, expectedRevision)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(binding))
+}
+
+// ModifyRouteBinding validates and replaces one route binding draft. If the
+// draft does not exist but a published binding with the same name exists, its
+// stable runtime identity is reused.
+//
+// @Tags Config
+// @Summary modify API route binding draft
+// @Accept application/json
+// @Produce application/json
+// @Param name query string true "Original route binding name"
+// @Success 200 {object} string
+// @Router /config/api/route [put]
+func ModifyRouteBinding(c *gin.Context) {
+ originalName := strings.TrimSpace(c.Query("name"))
+ if originalName == "" {
+ writeRouteBindingError(c, errors.New("route binding name query parameter is required for update"))
+ return
+ }
+ object, expectedRevision, err := decodeRouteBindingRequest(c)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ binding, err := store.UpdateDraft(c.Request.Context(), originalName, object, expectedRevision)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(binding))
+}
+
+// DeleteRouteBinding removes one route draft and its published runtime state
+// in one atomic transaction after the caller confirms the deletion.
+//
+// @Tags Config
+// @Summary delete and publish one API route binding
+// @Produce application/json
+// @Param name query string true "Route binding name"
+// @Param expectedRevision query int false "Draft key mod revision"
+// @Success 200 {object} string
+// @Router /config/api/route [delete]
+func DeleteRouteBinding(c *gin.Context) {
+ name := c.Query("name")
+ expectedRevision, err := routeBindingExpectedRevision(c)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ result, err := store.DeleteAndPublish(c.Request.Context(), name, expectedRevision)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(result))
+}
+
+// ValidateRouteBinding validates an object and returns schema defaults without
+// writing anything to etcd.
+//
+// @Tags Config
+// @Summary validate API route binding
+// @Accept application/json
+// @Produce application/json
+// @Success 200 {object} string
+// @Router /config/api/route/validate [post]
+func ValidateRouteBinding(c *gin.Context) {
+ object, _, err := decodeRouteBindingRequest(c)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ registry, err := schema.NewBuiltinRegistry()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ normalized, err := registry.Normalize(object)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(routeBindingValidationResponse{Valid: true, Object: normalized}))
+}
+
+// PreviewRouteBinding validates and compiles an object to the legacy
+// api_config.yaml shape without writing anything to etcd.
+//
+// @Tags Config
+// @Summary preview API route binding
+// @Accept application/json
+// @Produce application/json
+// @Success 200 {object} string
+// @Router /config/api/route/preview [post]
+func PreviewRouteBinding(c *gin.Context) {
+ object, _, err := decodeRouteBindingRequest(c)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ registry, err := schema.NewBuiltinRegistry()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ normalized, err := registry.Normalize(object)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ compiled, err := schema.CompileAdminRouteBinding(registry, normalized)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ preview, err := compiled.PreviewYAML()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(routeBindingPreviewResponse{Object: normalized, YAML: string(preview)}))
+}
+
+// PublishRouteBinding publishes one route draft in one etcd transaction. Pass
+// name and expectedRevision to reject a stale UI snapshot.
+//
+// @Tags Config
+// @Summary atomically publish one API route binding
+// @Produce application/json
+// @Param name query string true "Route binding name"
+// @Param expectedRevision query int false "Draft route key mod revision"
+// @Success 200 {object} string
+// @Router /config/api/route/publish [put]
+func PublishRouteBinding(c *gin.Context) {
+ name := c.Query("name")
+ if name == "" {
+ name = c.Param("name")
+ }
+ if strings.TrimSpace(name) == "" {
+ writeRouteBindingError(c, errors.New("route binding name is required for publish"))
+ return
+ }
+ expectedRevision, err := routeBindingExpectedRevision(c)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ result, err := store.Publish(c.Request.Context(), name, expectedRevision)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(result))
+}
+
+// GetRouteBindingStatus returns the independent draft and published
+// revisions for one route binding.
+//
+// @Tags Config
+// @Summary get API route binding status
+// @Produce application/json
+// @Param name query string true "Route binding name"
+// @Success 200 {object} string
+// @Router /config/api/route/status [get]
+func GetRouteBindingStatus(c *gin.Context) {
+ name := c.Query("name")
+ if name == "" {
+ name = c.Param("name")
+ }
+ if strings.TrimSpace(name) == "" {
+ writeRouteBindingError(c, errors.New("route binding name is required for status"))
+ return
+ }
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ status, err := store.Status(c.Request.Context(), name)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(status))
+}
+
+// GetRouteBindingDiff returns the field-level diff between one route's draft
+// and published objects.
+//
+// @Tags Config
+// @Summary get API route binding diff
+// @Produce application/json
+// @Param name query string true "Route binding name"
+// @Success 200 {object} string
+// @Router /config/api/route/diff [get]
+func GetRouteBindingDiff(c *gin.Context) {
+ name := c.Query("name")
+ if name == "" {
+ name = c.Param("name")
+ }
+ if strings.TrimSpace(name) == "" {
+ writeRouteBindingError(c, errors.New("route binding name is required for diff"))
+ return
+ }
+ store, err := logic.NewAdminRouteBindingStore()
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ diff, err := store.Diff(c.Request.Context(), name)
+ if err != nil {
+ writeRouteBindingError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithRet(diff))
+}
+
+func decodeRouteBindingRequest(c *gin.Context) (schema.AdminObject, int64, error) {
+ if content := c.PostForm("content"); strings.TrimSpace(content) != "" {
+ object, err := schema.DecodeAdminObjectYAML([]byte(content))
+ if err != nil {
+ return schema.AdminObject{}, 0, err
+ }
+ expectedRevision, err := routeBindingExpectedRevision(c)
+ return object, expectedRevision, err
+ }
+
+ body, err := io.ReadAll(io.LimitReader(c.Request.Body, maxRouteBindingRequestBytes+1))
+ if err != nil {
+ return schema.AdminObject{}, 0, fmt.Errorf("read route binding request: %w", err)
+ }
+ if len(body) > maxRouteBindingRequestBytes {
+ return schema.AdminObject{}, 0, fmt.Errorf("route binding request exceeds %d bytes", maxRouteBindingRequestBytes)
+ }
+ body = []byte(strings.TrimSpace(string(body)))
+ if len(body) == 0 {
+ return schema.AdminObject{}, 0, errors.New("route binding request body is empty")
+ }
+
+ var request routeBindingRequest
+ if err := json.Unmarshal(body, &request); err == nil && request.Object != nil {
+ expectedRevision := request.ExpectedRevision
+ if expectedRevision == 0 {
+ expectedRevision, err = routeBindingExpectedRevision(c)
+ }
+ return *request.Object, expectedRevision, err
+ }
+
+ var object schema.AdminObject
+ if err := json.Unmarshal(body, &object); err == nil && (object.Kind != "" || object.Metadata.Name != "" || object.Spec != nil) {
+ expectedRevision, revisionErr := routeBindingExpectedRevision(c)
+ return object, expectedRevision, revisionErr
+ }
+
+ object, err = schema.DecodeAdminObjectYAML(body)
+ if err != nil {
+ return schema.AdminObject{}, 0, fmt.Errorf("decode route binding request: %w", err)
+ }
+ expectedRevision, revisionErr := routeBindingExpectedRevision(c)
+ return object, expectedRevision, revisionErr
+}
+
+func routeBindingExpectedRevision(c *gin.Context) (int64, error) {
+ value := strings.TrimSpace(c.Query("expectedRevision"))
+ if value == "" {
+ value = strings.Trim(strings.TrimSpace(c.GetHeader("If-Match")), `"`)
+ }
+ if value == "" {
+ return 0, nil
+ }
+ revision, err := strconv.ParseInt(value, 10, 64)
+ if err != nil || revision < 0 {
+ return 0, fmt.Errorf("expected revision %q is invalid", value)
+ }
+ return revision, nil
+}
+
+func routeBindingUnpublished(c *gin.Context) bool {
+ if strings.EqualFold(strings.TrimSpace(c.Query("scope")), "published") {
+ return false
+ }
+ if strings.EqualFold(strings.TrimSpace(c.Query("scope")), "draft") {
+ return true
+ }
+ return c.Query("unpublished") != "0"
+}
+
+func writeRouteBindingError(c *gin.Context, err error) {
+ if err == nil {
+ err = errors.New("unknown route binding error")
+ }
+ if errors.Is(err, logic.ErrRouteBindingConflict) || errors.Is(err, logic.ErrRouteBindingPublishConflict) {
+ c.JSON(http.StatusOK, adminconfig.RetData{Code: adminconfig.RETRY, Data: err.Error()})
+ return
+ }
+ var validationErrors schema.ValidationErrors
+ if errors.As(err, &validationErrors) {
+ issues := append([]schema.ValidationIssue(nil), validationErrors...)
+ c.JSON(http.StatusOK, adminconfig.RetData{
+ Code: adminconfig.ERR,
+ Data: routeBindingErrorResponse{Message: err.Error(), Issues: issues},
+ })
+ return
+ }
+ c.JSON(http.StatusOK, adminconfig.WithError(err))
+}
diff --git a/admin/controller/configInfo/route_binding_test.go b/admin/controller/configInfo/route_binding_test.go
new file mode 100644
index 000000000..6da862514
--- /dev/null
+++ b/admin/controller/configInfo/route_binding_test.go
@@ -0,0 +1,206 @@
+/*
+ * 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 (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+import (
+ "github.com/gin-gonic/gin"
+)
+
+import (
+ adminconfig "github.com/apache/dubbo-go-pixiu/admin/config"
+ "github.com/apache/dubbo-go-pixiu/admin/logic"
+ "github.com/apache/dubbo-go-pixiu/pkg/config/schema"
+)
+
+func TestGetRouteBindingSchema(t *testing.T) {
+ response := invokeRouteBindingHandler(t, http.MethodGet, nil, GetRouteBindingSchema)
+ var result struct {
+ Code string `json:"code"`
+ Data []schema.ObjectSchema `json:"data"`
+ }
+ decodeRouteBindingResponse(t, response, &result)
+ if result.Code != adminconfig.OK {
+ t.Fatalf("response code: want %s, got %s", adminconfig.OK, result.Code)
+ }
+ if len(result.Data) != 1 || result.Data[0].Kind != schema.KindAdminRouteBinding {
+ t.Fatalf("schema response: %+v", result.Data)
+ }
+ paramType := result.Data[0].Fields["params"].Items.Properties["type"]
+ if paramType == nil || len(paramType.Enum) == 0 {
+ t.Fatalf("parameter type enum missing from schema response: %+v", result.Data[0].Fields["params"])
+ }
+}
+
+func TestValidateRouteBindingReturnsDefaults(t *testing.T) {
+ body := []byte(`{
+ "kind": "AdminRouteBinding",
+ "metadata": {"name": "user-get"},
+ "spec": {
+ "entry": {},
+ "target": {
+ "application": "UserProvider",
+ "interface": "com.example.UserService",
+ "method": "GetUser",
+ "cluster": "user-dubbo"
+ }
+ }
+}`)
+ response := invokeRouteBindingHandler(t, http.MethodPost, body, ValidateRouteBinding)
+ var result struct {
+ Code string `json:"code"`
+ Data routeBindingValidationResponse `json:"data"`
+ }
+ decodeRouteBindingResponse(t, response, &result)
+ if result.Code != adminconfig.OK || !result.Data.Valid {
+ t.Fatalf("validation response: %+v", result)
+ }
+ if result.Data.Object.Spec["entry"].(map[string]any)["protocol"] != "http" {
+ t.Fatalf("entry defaults: %+v", result.Data.Object.Spec["entry"])
+ }
+ entry := result.Data.Object.Spec["entry"].(map[string]any)
+ if entry["path"] != "/api/v1/example" || entry["method"] != "GET" {
+ t.Fatalf("entry defaults: %+v", entry)
+ }
+ if result.Data.Object.Spec["target"].(map[string]any)["protocol"] != "dubbo" {
+ t.Fatalf("target defaults: %+v", result.Data.Object.Spec["target"])
+ }
+ if result.Data.Object.Spec["enabled"] != true {
+ t.Fatalf("enabled default: %+v", result.Data.Object.Spec["enabled"])
+ }
+ if _, exists := result.Data.Object.Spec["publish"]; exists {
+ t.Fatalf("deprecated publish metadata was returned: %+v", result.Data.Object.Spec["publish"])
+ }
+}
+
+func TestValidateRouteBindingReturnsFieldIssues(t *testing.T) {
+ body := []byte(`{
+ "kind": "AdminRouteBinding",
+ "metadata": {"name": "bad-route"},
+ "spec": {
+ "entry": {"path": "api/users", "method": "TRACE"},
+ "target": {"application": "UserProvider"}
+ }
+}`)
+ response := invokeRouteBindingHandler(t, http.MethodPost, body, ValidateRouteBinding)
+ var result struct {
+ Code string `json:"code"`
+ Data routeBindingErrorResponse `json:"data"`
+ }
+ decodeRouteBindingResponse(t, response, &result)
+ if result.Code != adminconfig.ERR {
+ t.Fatalf("response code: want %s, got %s", adminconfig.ERR, result.Code)
+ }
+ if len(result.Data.Issues) == 0 {
+ t.Fatalf("expected validation issues, got %+v", result.Data)
+ }
+ foundPathIssue := false
+ for _, issue := range result.Data.Issues {
+ if issue.Path == "spec.entry.path" {
+ foundPathIssue = true
+ break
+ }
+ }
+ if !foundPathIssue {
+ t.Fatalf("path validation issue missing: %+v", result.Data.Issues)
+ }
+}
+
+func TestPreviewRouteBindingReturnsLegacyYAML(t *testing.T) {
+ body := []byte(`{
+ "kind": "AdminRouteBinding",
+ "metadata": {"name": "user-get"},
+ "spec": {
+ "entry": {"path": "/api/users", "method": "GET"},
+ "target": {
+ "application": "UserProvider",
+ "interface": "com.example.UserService",
+ "method": "GetUser",
+ "cluster": "user-dubbo"
+ }
+ }
+}`)
+ response := invokeRouteBindingHandler(t, http.MethodPost, body, PreviewRouteBinding)
+ var result struct {
+ Code string `json:"code"`
+ Data routeBindingPreviewResponse `json:"data"`
+ }
+ decodeRouteBindingResponse(t, response, &result)
+ if result.Code != adminconfig.OK {
+ t.Fatalf("response code: want %s, got %s", adminconfig.OK, result.Code)
+ }
+ if result.Data.YAML == "" || !bytes.Contains([]byte(result.Data.YAML), []byte("resources:")) {
+ t.Fatalf("legacy preview yaml: %q", result.Data.YAML)
+ }
+ if bytes.Contains([]byte(result.Data.YAML), []byte("AdminRouteBinding")) || bytes.Contains([]byte(result.Data.YAML), []byte("publish:")) {
+ t.Fatalf("control-plane fields leaked into legacy preview: %q", result.Data.YAML)
+ }
+}
+
+func TestWriteRouteBindingErrorReturnsRetryCode(t *testing.T) {
+ tests := []error{
+ logic.ErrRouteBindingConflict,
+ fmt.Errorf("wrapped publish conflict: %w", logic.ErrRouteBindingPublishConflict),
+ }
+ for _, err := range tests {
+ response := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(response)
+ writeRouteBindingError(context, err)
+
+ var result adminconfig.RetData
+ decodeRouteBindingResponse(t, response, &result)
+ if result.Code != adminconfig.RETRY {
+ t.Fatalf("error %q: response code: want %s, got %s", err, adminconfig.RETRY, result.Code)
+ }
+ if result.Data != err.Error() {
+ t.Fatalf("error %q: response data: want %q, got %#v", err, err.Error(), result.Data)
+ }
+ }
+}
+
+func invokeRouteBindingHandler(t *testing.T, method string, body []byte, handler gin.HandlerFunc) *httptest.ResponseRecorder {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ request := httptest.NewRequest(method, "/", bytes.NewReader(body))
+ if body != nil {
+ request.Header.Set("Content-Type", "application/json")
+ }
+ response := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(response)
+ context.Request = request
+ handler(context)
+ return response
+}
+
+func decodeRouteBindingResponse(t *testing.T, response *httptest.ResponseRecorder, target any) {
+ t.Helper()
+ if response.Code != http.StatusOK {
+ t.Fatalf("http status: want %d, got %d", http.StatusOK, response.Code)
+ }
+ if err := json.Unmarshal(response.Body.Bytes(), target); err != nil {
+ t.Fatalf("decode response %q: %v", response.Body.String(), err)
+ }
+}
diff --git a/admin/controller/opa/opa.go b/admin/controller/opa/opa.go
index 1b1673fe0..2300f37cf 100644
--- a/admin/controller/opa/opa.go
+++ b/admin/controller/opa/opa.go
@@ -35,6 +35,13 @@ import (
// @Tags Config
// @Summary upload OPA policy (server mode)
+// @Accept application/x-www-form-urlencoded
+// @Produce application/json
+// @Param server_url formData string false "OPA server url"
+// @Param policy_id formData string false "Policy ID"
+// @Param bearer_token formData string false "Bearer token"
+// @Param content formData string true "Rego content"
+// @Success 200 {object} string
// @Router /config/api/opa/policy [put]
func PutOPAPolicy(c *gin.Context) {
// For PUT, we typically expect Form Data
@@ -57,6 +64,11 @@ func PutOPAPolicy(c *gin.Context) {
// @Tags Config
// @Summary get OPA policy (server mode)
+// @Produce application/json
+// @Param server_url query string false "OPA server url"
+// @Param policy_id query string false "Policy ID"
+// @Param bearer_token query string false "Bearer token"
+// @Success 200 {object} string
// @Router /config/api/opa/policy [get]
func GetOPAPolicy(c *gin.Context) {
var query adminconfig.OPAQuery
@@ -78,6 +90,11 @@ func GetOPAPolicy(c *gin.Context) {
// @Tags Config
// @Summary delete OPA policy (server mode)
+// @Produce application/json
+// @Param server_url query string false "OPA server url"
+// @Param policy_id query string false "Policy ID"
+// @Param bearer_token query string false "Bearer token"
+// @Success 200 {object} string
// @Router /config/api/opa/policy [delete]
func DeleteOPAPolicy(c *gin.Context) {
var query adminconfig.OPAQuery
diff --git a/admin/doc/docs.go b/admin/doc/docs.go
index 611ec678f..f85d7ee4c 100644
--- a/admin/doc/docs.go
+++ b/admin/doc/docs.go
@@ -1,19 +1,19 @@
-//
-// 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.
-//
+/*
+ * 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 doc Code generated by swaggo/swag. DO NOT EDIT
package doc
@@ -114,26 +114,6 @@ const docTemplate = `{
}
}
},
- "/config/api/xds/status": {
- "get": {
- "description": "Returns xDS listener availability, last-good snapshot metadata, latest errors, readiness, and resource support matrix.",
- "produces": [
- "application/json"
- ],
- "tags": [
- "XDS"
- ],
- "summary": "get Admin xDS publication status",
- "responses": {
- "200": {
- "description": "OK",
- "schema": {
- "type": "object"
- }
- }
- }
- }
- },
"/config/api/cluster": {
"put": {
"description": "Create a cluster by passing the YAML/JSON configuration for the cluster through the form's content field.",
@@ -410,58 +390,33 @@ const docTemplate = `{
}
}
},
- "/config/api/plugin_group/publish": {
- "put": {
- "description": "publish the PluginGroup from the unpublished space to the published space.",
- "produces": [
- "application/json"
- ],
- "tags": [
- "Config"
- ],
- "summary": "batch Release PluginGroup Config",
- "responses": {
- "200": {
- "description": "OK",
- "schema": {
- "type": "string"
- }
- }
- }
- }
- },
- "/config/api/resource": {
- "put": {
- "description": "modify resource content, where content is the YAML of the Resource. Use resourceId to specify the resource to be modified.",
- "consumes": [
- "application/x-www-form-urlencoded"
- ],
+ "/config/api/opa/policy": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "modify resource",
+ "summary": "get OPA policy (server mode)",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
+ "type": "string",
+ "description": "OPA server url",
+ "name": "server_url",
"in": "query"
},
{
"type": "string",
- "description": "Resource YAML",
- "name": "content",
- "in": "formData",
- "required": true
+ "description": "Policy ID",
+ "name": "policy_id",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "description": "Bearer token",
+ "name": "bearer_token",
+ "in": "query"
}
],
"responses": {
@@ -473,8 +428,7 @@ const docTemplate = `{
}
}
},
- "post": {
- "description": "create a resource by passing the Resource's YAML via the form's content field (simultaneously writing to the staging area and production area).",
+ "put": {
"consumes": [
"application/x-www-form-urlencoded"
],
@@ -484,20 +438,32 @@ const docTemplate = `{
"tags": [
"Config"
],
- "summary": "create resource",
+ "summary": "upload OPA policy (server mode)",
"parameters": [
{
"type": "string",
- "description": "Resource YAML",
- "name": "content",
- "in": "formData",
- "required": true
+ "description": "OPA server url",
+ "name": "server_url",
+ "in": "formData"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
+ "description": "Policy ID",
+ "name": "policy_id",
"in": "formData"
+ },
+ {
+ "type": "string",
+ "description": "Bearer token",
+ "name": "bearer_token",
+ "in": "formData"
+ },
+ {
+ "type": "string",
+ "description": "Rego content",
+ "name": "content",
+ "in": "formData",
+ "required": true
}
],
"responses": {
@@ -510,27 +476,31 @@ const docTemplate = `{
}
},
"delete": {
- "description": "delete resources by ID. When unpublished is 1, this indicates deleting configurations for unpublished spaces (requires checking published spaces).",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "delete resource",
+ "summary": "delete OPA policy (server mode)",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
- "in": "query",
- "required": true
+ "type": "string",
+ "description": "OPA server url",
+ "name": "server_url",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "description": "Policy ID",
+ "name": "policy_id",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "description": "Bearer token",
+ "name": "bearer_token",
+ "in": "query"
}
],
"responses": {
@@ -543,34 +513,19 @@ const docTemplate = `{
}
}
},
- "/config/api/resource/detail": {
- "get": {
- "description": "get resource details according to resource ID and return the YAML",
+ "/config/api/plugin_group/publish": {
+ "put": {
+ "description": "publish the PluginGroup from the unpublished space to the published space.",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get resource detail with yml",
- "parameters": [
- {
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
- {
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
- }
- ],
+ "summary": "batch Release PluginGroup Config",
"responses": {
"200": {
- "description": "YAML content",
+ "description": "OK",
"schema": {
"type": "string"
}
@@ -578,39 +533,39 @@ const docTemplate = `{
}
}
},
- "/config/api/resource/list": {
- "get": {
- "description": "Retrieve the list of resources. Use the unpublished parameter to control whether to include unpublished or published resources.",
+ "/config/api/route": {
+ "put": {
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get all resource list",
+ "summary": "modify API route binding draft",
"parameters": [
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "description": "Original route binding name",
+ "name": "name",
+ "in": "query",
+ "required": true
}
],
"responses": {
"200": {
- "description": "JSON array",
+ "description": "OK",
"schema": {
"type": "string"
}
}
}
- }
- },
- "/config/api/resource/method": {
- "put": {
- "description": "Modify the specified method, where content is the YAML for Method.",
+ },
+ "post": {
"consumes": [
- "application/x-www-form-urlencoded"
+ "application/json"
],
"produces": [
"application/json"
@@ -618,35 +573,7 @@ const docTemplate = `{
"tags": [
"Config"
],
- "summary": "modify method",
- "parameters": [
- {
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
- {
- "type": "integer",
- "description": "MethodID",
- "name": "methodId",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Method YAML",
- "name": "content",
- "in": "formData",
- "required": true
- },
- {
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
- }
- ],
+ "summary": "create API route binding draft",
"responses": {
"200": {
"description": "OK",
@@ -656,38 +583,27 @@ const docTemplate = `{
}
}
},
- "post": {
- "description": "create a method under the specified resource, where content is the YAML for Method.",
- "consumes": [
- "application/x-www-form-urlencoded"
- ],
+ "delete": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "create method",
+ "summary": "delete and publish one API route binding",
"parameters": [
- {
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
{
"type": "string",
- "description": "Method YAML",
- "name": "content",
- "in": "formData",
+ "description": "Route binding name",
+ "name": "name",
+ "in": "query",
"required": true
},
{
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "type": "integer",
+ "description": "Draft key mod revision",
+ "name": "expectedRevision",
+ "in": "query"
}
],
"responses": {
@@ -698,36 +614,36 @@ const docTemplate = `{
}
}
}
- },
- "delete": {
- "description": "Deleting a method under a resource, where ` + "`" + `unpublished` + "`" + ` equals 1 indicates removing the configuration for unpublished spaces (requires checking published spaces).",
+ }
+ },
+ "/config/api/route/detail": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "delete method",
+ "summary": "get API route binding detail",
"parameters": [
{
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
+ "type": "string",
+ "description": "Route binding name",
+ "name": "name",
"in": "query",
"required": true
},
{
- "type": "integer",
- "description": "MethodID",
- "name": "methodId",
- "in": "query",
- "required": true
+ "type": "string",
+ "description": "draft or published",
+ "name": "scope",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
+ "description": "1 for draft, 0 for published",
"name": "unpublished",
- "in": "formData"
+ "in": "query"
}
],
"responses": {
@@ -740,41 +656,27 @@ const docTemplate = `{
}
}
},
- "/config/api/resource/method/detail": {
+ "/config/api/route/diff": {
"get": {
- "description": "get method details based on resourceId and methodId, returning YAML.",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get method detail with yml",
+ "summary": "get API route binding diff",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
- {
- "type": "integer",
- "description": "method ID",
- "name": "methodId",
+ "type": "string",
+ "description": "Route binding name",
+ "name": "name",
"in": "query",
"required": true
- },
- {
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
}
],
"responses": {
"200": {
- "description": "YAML content",
+ "description": "OK",
"schema": {
"type": "string"
}
@@ -782,34 +684,32 @@ const docTemplate = `{
}
}
},
- "/config/api/resource/method/list": {
+ "/config/api/route/list": {
"get": {
- "description": "get the list of methods under the specified resource",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get all method list below one resource",
+ "summary": "get API route binding list",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
- "in": "query",
- "required": true
+ "type": "string",
+ "description": "draft or published",
+ "name": "scope",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
+ "description": "1 for draft, 0 for published",
"name": "unpublished",
- "in": "formData"
+ "in": "query"
}
],
"responses": {
"200": {
- "description": "JSON array",
+ "description": "OK",
"schema": {
"type": "string"
}
@@ -817,16 +717,18 @@ const docTemplate = `{
}
}
},
- "/config/api/resource/method/publish": {
- "put": {
- "description": "TODO: unimplemented",
+ "/config/api/route/preview": {
+ "post": {
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "batch Release Method Config",
+ "summary": "preview API route binding",
"responses": {
"200": {
"description": "OK",
@@ -837,32 +739,27 @@ const docTemplate = `{
}
}
},
- "/config/api/opa/policy": {
- "get": {
+ "/config/api/route/publish": {
+ "put": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get OPA policy (server mode)",
+ "summary": "atomically publish one API route binding",
"parameters": [
{
"type": "string",
- "description": "OPA server url",
- "name": "server_url",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Policy ID",
- "name": "policy_id",
- "in": "query"
+ "description": "Route binding name",
+ "name": "name",
+ "in": "query",
+ "required": true
},
{
- "type": "string",
- "description": "Bearer token",
- "name": "bearer_token",
+ "type": "integer",
+ "description": "Draft route key mod revision",
+ "name": "expectedRevision",
"in": "query"
}
],
@@ -874,45 +771,17 @@ const docTemplate = `{
}
}
}
- },
- "put": {
- "consumes": [
- "application/x-www-form-urlencoded"
- ],
+ }
+ },
+ "/config/api/route/schema": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "upload OPA policy (server mode)",
- "parameters": [
- {
- "type": "string",
- "description": "OPA server url",
- "name": "server_url",
- "in": "formData"
- },
- {
- "type": "string",
- "description": "Policy ID",
- "name": "policy_id",
- "in": "formData"
- },
- {
- "type": "string",
- "description": "Bearer token",
- "name": "bearer_token",
- "in": "formData"
- },
- {
- "type": "string",
- "description": "Rego content",
- "name": "content",
- "in": "formData",
- "required": true
- }
- ],
+ "summary": "get API route binding schema",
"responses": {
"200": {
"description": "OK",
@@ -921,33 +790,24 @@ const docTemplate = `{
}
}
}
- },
- "delete": {
+ }
+ },
+ "/config/api/route/status": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "delete OPA policy (server mode)",
+ "summary": "get API route binding status",
"parameters": [
{
"type": "string",
- "description": "OPA server url",
- "name": "server_url",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Policy ID",
- "name": "policy_id",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Bearer token",
- "name": "bearer_token",
- "in": "query"
+ "description": "Route binding name",
+ "name": "name",
+ "in": "query",
+ "required": true
}
],
"responses": {
@@ -960,16 +820,18 @@ const docTemplate = `{
}
}
},
- "/config/api/resource/publish": {
- "put": {
- "description": "publish resources from unpublished spaces to published spaces",
+ "/config/api/route/validate": {
+ "post": {
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "publish all configuration information",
+ "summary": "validate API route binding",
"responses": {
"200": {
"description": "OK",
@@ -980,6 +842,26 @@ const docTemplate = `{
}
}
},
+ "/config/api/xds/status": {
+ "get": {
+ "description": "Returns xDS listener availability, last-good snapshot metadata, latest errors, readiness, and resource support matrix.",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "XDS"
+ ],
+ "summary": "get Admin xDS publication status",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/github_com_apache_dubbo-go-pixiu_admin_config.RetData"
+ }
+ }
+ }
+ }
+ },
"/register": {
"post": {
"produces": [
@@ -1134,6 +1016,17 @@ const docTemplate = `{
}
}
}
+ },
+ "definitions": {
+ "github_com_apache_dubbo-go-pixiu_admin_config.RetData": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "string"
+ },
+ "data": {}
+ }
+ }
}
}`
diff --git a/admin/doc/swagger.json b/admin/doc/swagger.json
index 531a3a929..ff8b5047e 100644
--- a/admin/doc/swagger.json
+++ b/admin/doc/swagger.json
@@ -86,26 +86,6 @@
}
}
},
- "/config/api/xds/status": {
- "get": {
- "description": "Returns xDS listener availability, last-good snapshot metadata, latest errors, readiness, and resource support matrix.",
- "produces": [
- "application/json"
- ],
- "tags": [
- "XDS"
- ],
- "summary": "get Admin xDS publication status",
- "responses": {
- "200": {
- "description": "OK",
- "schema": {
- "type": "object"
- }
- }
- }
- }
- },
"/config/api/cluster": {
"put": {
"description": "Create a cluster by passing the YAML/JSON configuration for the cluster through the form's content field.",
@@ -382,58 +362,33 @@
}
}
},
- "/config/api/plugin_group/publish": {
- "put": {
- "description": "publish the PluginGroup from the unpublished space to the published space.",
- "produces": [
- "application/json"
- ],
- "tags": [
- "Config"
- ],
- "summary": "batch Release PluginGroup Config",
- "responses": {
- "200": {
- "description": "OK",
- "schema": {
- "type": "string"
- }
- }
- }
- }
- },
- "/config/api/resource": {
- "put": {
- "description": "modify resource content, where content is the YAML of the Resource. Use resourceId to specify the resource to be modified.",
- "consumes": [
- "application/x-www-form-urlencoded"
- ],
+ "/config/api/opa/policy": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "modify resource",
+ "summary": "get OPA policy (server mode)",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
+ "type": "string",
+ "description": "OPA server url",
+ "name": "server_url",
"in": "query"
},
{
"type": "string",
- "description": "Resource YAML",
- "name": "content",
- "in": "formData",
- "required": true
+ "description": "Policy ID",
+ "name": "policy_id",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "description": "Bearer token",
+ "name": "bearer_token",
+ "in": "query"
}
],
"responses": {
@@ -445,8 +400,7 @@
}
}
},
- "post": {
- "description": "create a resource by passing the Resource's YAML via the form's content field (simultaneously writing to the staging area and production area).",
+ "put": {
"consumes": [
"application/x-www-form-urlencoded"
],
@@ -456,20 +410,32 @@
"tags": [
"Config"
],
- "summary": "create resource",
+ "summary": "upload OPA policy (server mode)",
"parameters": [
{
"type": "string",
- "description": "Resource YAML",
- "name": "content",
- "in": "formData",
- "required": true
+ "description": "OPA server url",
+ "name": "server_url",
+ "in": "formData"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
+ "description": "Policy ID",
+ "name": "policy_id",
"in": "formData"
+ },
+ {
+ "type": "string",
+ "description": "Bearer token",
+ "name": "bearer_token",
+ "in": "formData"
+ },
+ {
+ "type": "string",
+ "description": "Rego content",
+ "name": "content",
+ "in": "formData",
+ "required": true
}
],
"responses": {
@@ -482,27 +448,31 @@
}
},
"delete": {
- "description": "delete resources by ID. When unpublished is 1, this indicates deleting configurations for unpublished spaces (requires checking published spaces).",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "delete resource",
+ "summary": "delete OPA policy (server mode)",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
- "in": "query",
- "required": true
+ "type": "string",
+ "description": "OPA server url",
+ "name": "server_url",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "description": "Policy ID",
+ "name": "policy_id",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "description": "Bearer token",
+ "name": "bearer_token",
+ "in": "query"
}
],
"responses": {
@@ -515,34 +485,19 @@
}
}
},
- "/config/api/resource/detail": {
- "get": {
- "description": "get resource details according to resource ID and return the YAML",
+ "/config/api/plugin_group/publish": {
+ "put": {
+ "description": "publish the PluginGroup from the unpublished space to the published space.",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get resource detail with yml",
- "parameters": [
- {
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
- {
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
- }
- ],
+ "summary": "batch Release PluginGroup Config",
"responses": {
"200": {
- "description": "YAML content",
+ "description": "OK",
"schema": {
"type": "string"
}
@@ -550,39 +505,39 @@
}
}
},
- "/config/api/resource/list": {
- "get": {
- "description": "Retrieve the list of resources. Use the unpublished parameter to control whether to include unpublished or published resources.",
+ "/config/api/route": {
+ "put": {
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get all resource list",
+ "summary": "modify API route binding draft",
"parameters": [
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "description": "Original route binding name",
+ "name": "name",
+ "in": "query",
+ "required": true
}
],
"responses": {
"200": {
- "description": "JSON array",
+ "description": "OK",
"schema": {
"type": "string"
}
}
}
- }
- },
- "/config/api/resource/method": {
- "put": {
- "description": "Modify the specified method, where content is the YAML for Method.",
+ },
+ "post": {
"consumes": [
- "application/x-www-form-urlencoded"
+ "application/json"
],
"produces": [
"application/json"
@@ -590,35 +545,7 @@
"tags": [
"Config"
],
- "summary": "modify method",
- "parameters": [
- {
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
- {
- "type": "integer",
- "description": "MethodID",
- "name": "methodId",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Method YAML",
- "name": "content",
- "in": "formData",
- "required": true
- },
- {
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
- }
- ],
+ "summary": "create API route binding draft",
"responses": {
"200": {
"description": "OK",
@@ -628,38 +555,27 @@
}
}
},
- "post": {
- "description": "create a method under the specified resource, where content is the YAML for Method.",
- "consumes": [
- "application/x-www-form-urlencoded"
- ],
+ "delete": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "create method",
+ "summary": "delete and publish one API route binding",
"parameters": [
- {
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
{
"type": "string",
- "description": "Method YAML",
- "name": "content",
- "in": "formData",
+ "description": "Route binding name",
+ "name": "name",
+ "in": "query",
"required": true
},
{
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
+ "type": "integer",
+ "description": "Draft key mod revision",
+ "name": "expectedRevision",
+ "in": "query"
}
],
"responses": {
@@ -670,36 +586,36 @@
}
}
}
- },
- "delete": {
- "description": "Deleting a method under a resource, where `unpublished` equals 1 indicates removing the configuration for unpublished spaces (requires checking published spaces).",
+ }
+ },
+ "/config/api/route/detail": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "delete method",
+ "summary": "get API route binding detail",
"parameters": [
{
- "type": "integer",
- "description": "ResourceID",
- "name": "resourceId",
+ "type": "string",
+ "description": "Route binding name",
+ "name": "name",
"in": "query",
"required": true
},
{
- "type": "integer",
- "description": "MethodID",
- "name": "methodId",
- "in": "query",
- "required": true
+ "type": "string",
+ "description": "draft or published",
+ "name": "scope",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
+ "description": "1 for draft, 0 for published",
"name": "unpublished",
- "in": "formData"
+ "in": "query"
}
],
"responses": {
@@ -712,41 +628,27 @@
}
}
},
- "/config/api/resource/method/detail": {
+ "/config/api/route/diff": {
"get": {
- "description": "get method details based on resourceId and methodId, returning YAML.",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get method detail with yml",
+ "summary": "get API route binding diff",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
- "in": "query",
- "required": true
- },
- {
- "type": "integer",
- "description": "method ID",
- "name": "methodId",
+ "type": "string",
+ "description": "Route binding name",
+ "name": "name",
"in": "query",
"required": true
- },
- {
- "type": "string",
- "description": "1: unpublished; 0 or empty: published",
- "name": "unpublished",
- "in": "formData"
}
],
"responses": {
"200": {
- "description": "YAML content",
+ "description": "OK",
"schema": {
"type": "string"
}
@@ -754,34 +656,32 @@
}
}
},
- "/config/api/resource/method/list": {
+ "/config/api/route/list": {
"get": {
- "description": "get the list of methods under the specified resource",
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get all method list below one resource",
+ "summary": "get API route binding list",
"parameters": [
{
- "type": "integer",
- "description": "resource ID",
- "name": "resourceId",
- "in": "query",
- "required": true
+ "type": "string",
+ "description": "draft or published",
+ "name": "scope",
+ "in": "query"
},
{
"type": "string",
- "description": "1: unpublished; 0 or empty: published",
+ "description": "1 for draft, 0 for published",
"name": "unpublished",
- "in": "formData"
+ "in": "query"
}
],
"responses": {
"200": {
- "description": "JSON array",
+ "description": "OK",
"schema": {
"type": "string"
}
@@ -789,16 +689,18 @@
}
}
},
- "/config/api/resource/method/publish": {
- "put": {
- "description": "TODO: unimplemented",
+ "/config/api/route/preview": {
+ "post": {
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "batch Release Method Config",
+ "summary": "preview API route binding",
"responses": {
"200": {
"description": "OK",
@@ -809,32 +711,27 @@
}
}
},
- "/config/api/opa/policy": {
- "get": {
+ "/config/api/route/publish": {
+ "put": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "get OPA policy (server mode)",
+ "summary": "atomically publish one API route binding",
"parameters": [
{
"type": "string",
- "description": "OPA server url",
- "name": "server_url",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Policy ID",
- "name": "policy_id",
- "in": "query"
+ "description": "Route binding name",
+ "name": "name",
+ "in": "query",
+ "required": true
},
{
- "type": "string",
- "description": "Bearer token",
- "name": "bearer_token",
+ "type": "integer",
+ "description": "Draft route key mod revision",
+ "name": "expectedRevision",
"in": "query"
}
],
@@ -846,45 +743,17 @@
}
}
}
- },
- "put": {
- "consumes": [
- "application/x-www-form-urlencoded"
- ],
+ }
+ },
+ "/config/api/route/schema": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "upload OPA policy (server mode)",
- "parameters": [
- {
- "type": "string",
- "description": "OPA server url",
- "name": "server_url",
- "in": "formData"
- },
- {
- "type": "string",
- "description": "Policy ID",
- "name": "policy_id",
- "in": "formData"
- },
- {
- "type": "string",
- "description": "Bearer token",
- "name": "bearer_token",
- "in": "formData"
- },
- {
- "type": "string",
- "description": "Rego content",
- "name": "content",
- "in": "formData",
- "required": true
- }
- ],
+ "summary": "get API route binding schema",
"responses": {
"200": {
"description": "OK",
@@ -893,33 +762,24 @@
}
}
}
- },
- "delete": {
+ }
+ },
+ "/config/api/route/status": {
+ "get": {
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "delete OPA policy (server mode)",
+ "summary": "get API route binding status",
"parameters": [
{
"type": "string",
- "description": "OPA server url",
- "name": "server_url",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Policy ID",
- "name": "policy_id",
- "in": "query"
- },
- {
- "type": "string",
- "description": "Bearer token",
- "name": "bearer_token",
- "in": "query"
+ "description": "Route binding name",
+ "name": "name",
+ "in": "query",
+ "required": true
}
],
"responses": {
@@ -931,16 +791,19 @@
}
}
}
- }, "/config/api/resource/publish": {
- "put": {
- "description": "publish resources from unpublished spaces to published spaces",
+ },
+ "/config/api/route/validate": {
+ "post": {
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"Config"
],
- "summary": "publish all configuration information",
+ "summary": "validate API route binding",
"responses": {
"200": {
"description": "OK",
@@ -951,6 +814,26 @@
}
}
},
+ "/config/api/xds/status": {
+ "get": {
+ "description": "Returns xDS listener availability, last-good snapshot metadata, latest errors, readiness, and resource support matrix.",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "XDS"
+ ],
+ "summary": "get Admin xDS publication status",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/github_com_apache_dubbo-go-pixiu_admin_config.RetData"
+ }
+ }
+ }
+ }
+ },
"/register": {
"post": {
"produces": [
@@ -1105,5 +988,16 @@
}
}
}
+ },
+ "definitions": {
+ "github_com_apache_dubbo-go-pixiu_admin_config.RetData": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "string"
+ },
+ "data": {}
+ }
+ }
}
-}
+}
\ No newline at end of file
diff --git a/admin/doc/swagger.yaml b/admin/doc/swagger.yaml
index d748e7708..418f6d553 100644
--- a/admin/doc/swagger.yaml
+++ b/admin/doc/swagger.yaml
@@ -1,3 +1,10 @@
+definitions:
+ github_com_apache_dubbo-go-pixiu_admin_config.RetData:
+ properties:
+ code:
+ type: string
+ data: {}
+ type: object
info:
contact: {}
paths:
@@ -57,20 +64,6 @@ paths:
summary: modify pixiu base info such as name,desc
tags:
- Config
- /config/api/xds/status:
- get:
- description: Returns xDS listener availability, last-good snapshot metadata,
- latest errors, readiness, and resource support matrix.
- produces:
- - application/json
- responses:
- "200":
- description: OK
- schema:
- type: object
- summary: get Admin xDS publication status
- tags:
- - XDS
/config/api/cluster:
delete:
description: delete cluster according to cluster ID
@@ -257,10 +250,21 @@ paths:
summary: get all Listener list
tags:
- Config
- /config/api/plugin_group/publish:
- put:
- description: publish the PluginGroup from the unpublished space to the published
- space.
+ /config/api/opa/policy:
+ delete:
+ parameters:
+ - description: OPA server url
+ in: query
+ name: server_url
+ type: string
+ - description: Policy ID
+ in: query
+ name: policy_id
+ type: string
+ - description: Bearer token
+ in: query
+ name: bearer_token
+ type: string
produces:
- application/json
responses:
@@ -268,22 +272,22 @@ paths:
description: OK
schema:
type: string
- summary: batch Release PluginGroup Config
+ summary: delete OPA policy (server mode)
tags:
- Config
- /config/api/resource:
- delete:
- description: delete resources by ID. When unpublished is 1, this indicates deleting
- configurations for unpublished spaces (requires checking published spaces).
+ get:
parameters:
- - description: resource ID
+ - description: OPA server url
in: query
- name: resourceId
- required: true
- type: integer
- - description: '1: unpublished; 0 or empty: published'
- in: formData
- name: unpublished
+ name: server_url
+ type: string
+ - description: Policy ID
+ in: query
+ name: policy_id
+ type: string
+ - description: Bearer token
+ in: query
+ name: bearer_token
type: string
produces:
- application/json
@@ -292,23 +296,29 @@ paths:
description: OK
schema:
type: string
- summary: delete resource
+ summary: get OPA policy (server mode)
tags:
- Config
- post:
+ put:
consumes:
- application/x-www-form-urlencoded
- description: create a resource by passing the Resource's YAML via the form's
- content field (simultaneously writing to the staging area and production area).
parameters:
- - description: Resource YAML
+ - description: OPA server url
in: formData
- name: content
- required: true
+ name: server_url
type: string
- - description: '1: unpublished; 0 or empty: published'
+ - description: Policy ID
in: formData
- name: unpublished
+ name: policy_id
+ type: string
+ - description: Bearer token
+ in: formData
+ name: bearer_token
+ type: string
+ - description: Rego content
+ in: formData
+ name: content
+ required: true
type: string
produces:
- application/json
@@ -317,28 +327,13 @@ paths:
description: OK
schema:
type: string
- summary: create resource
+ summary: upload OPA policy (server mode)
tags:
- Config
+ /config/api/plugin_group/publish:
put:
- consumes:
- - application/x-www-form-urlencoded
- description: modify resource content, where content is the YAML of the Resource.
- Use resourceId to specify the resource to be modified.
- parameters:
- - description: resource ID
- in: query
- name: resourceId
- type: integer
- - description: Resource YAML
- in: formData
- name: content
- required: true
- type: string
- - description: '1: unpublished; 0 or empty: published'
- in: formData
- name: unpublished
- type: string
+ description: publish the PluginGroup from the unpublished space to the published
+ space.
produces:
- application/json
responses:
@@ -346,70 +341,52 @@ paths:
description: OK
schema:
type: string
- summary: modify resource
+ summary: batch Release PluginGroup Config
tags:
- Config
- /config/api/resource/detail:
- get:
- description: get resource details according to resource ID and return the YAML
+ /config/api/route:
+ delete:
parameters:
- - description: ResourceID
+ - description: Route binding name
in: query
- name: resourceId
+ name: name
required: true
- type: integer
- - description: '1: unpublished; 0 or empty: published'
- in: formData
- name: unpublished
type: string
+ - description: Draft key mod revision
+ in: query
+ name: expectedRevision
+ type: integer
produces:
- application/json
responses:
"200":
- description: YAML content
+ description: OK
schema:
type: string
- summary: get resource detail with yml
+ summary: delete and publish one API route binding
tags:
- Config
- /config/api/resource/list:
- get:
- description: Retrieve the list of resources. Use the unpublished parameter to
- control whether to include unpublished or published resources.
- parameters:
- - description: '1: unpublished; 0 or empty: published'
- in: formData
- name: unpublished
- type: string
+ post:
+ consumes:
+ - application/json
produces:
- application/json
responses:
"200":
- description: JSON array
+ description: OK
schema:
type: string
- summary: get all resource list
+ summary: create API route binding draft
tags:
- Config
- /config/api/resource/method:
- delete:
- description: Deleting a method under a resource, where `unpublished` equals
- 1 indicates removing the configuration for unpublished spaces (requires checking
- published spaces).
+ put:
+ consumes:
+ - application/json
parameters:
- - description: ResourceID
+ - description: Original route binding name
in: query
- name: resourceId
- required: true
- type: integer
- - description: MethodID
- in: query
- name: methodId
+ name: name
required: true
- type: integer
- - description: '1: unpublished; 0 or empty: published'
- in: formData
- name: unpublished
type: string
produces:
- application/json
@@ -418,27 +395,23 @@ paths:
description: OK
schema:
type: string
- summary: delete method
+ summary: modify API route binding draft
tags:
- Config
- post:
- consumes:
- - application/x-www-form-urlencoded
- description: create a method under the specified resource, where content is
- the YAML for Method.
+ /config/api/route/detail:
+ get:
parameters:
- - description: ResourceID
+ - description: Route binding name
in: query
- name: resourceId
- required: true
- type: integer
- - description: Method YAML
- in: formData
- name: content
+ name: name
required: true
type: string
- - description: '1: unpublished; 0 or empty: published'
- in: formData
+ - description: draft or published
+ in: query
+ name: scope
+ type: string
+ - description: 1 for draft, 0 for published
+ in: query
name: unpublished
type: string
produces:
@@ -448,32 +421,17 @@ paths:
description: OK
schema:
type: string
- summary: create method
+ summary: get API route binding detail
tags:
- Config
- put:
- consumes:
- - application/x-www-form-urlencoded
- description: Modify the specified method, where content is the YAML for Method.
+ /config/api/route/diff:
+ get:
parameters:
- - description: ResourceID
+ - description: Route binding name
in: query
- name: resourceId
- required: true
- type: integer
- - description: MethodID
- in: query
- name: methodId
- type: integer
- - description: Method YAML
- in: formData
- name: content
+ name: name
required: true
type: string
- - description: '1: unpublished; 0 or empty: published'
- in: formData
- name: unpublished
- type: string
produces:
- application/json
responses:
@@ -481,64 +439,56 @@ paths:
description: OK
schema:
type: string
- summary: modify method
+ summary: get API route binding diff
tags:
- Config
- /config/api/resource/method/detail:
+ /config/api/route/list:
get:
- description: get method details based on resourceId and methodId, returning
- YAML.
parameters:
- - description: resource ID
+ - description: draft or published
in: query
- name: resourceId
- required: true
- type: integer
- - description: method ID
+ name: scope
+ type: string
+ - description: 1 for draft, 0 for published
in: query
- name: methodId
- required: true
- type: integer
- - description: '1: unpublished; 0 or empty: published'
- in: formData
name: unpublished
type: string
produces:
- application/json
responses:
"200":
- description: YAML content
+ description: OK
schema:
type: string
- summary: get method detail with yml
+ summary: get API route binding list
tags:
- Config
- /config/api/resource/method/list:
- get:
- description: get the list of methods under the specified resource
- parameters:
- - description: resource ID
- in: query
- name: resourceId
- required: true
- type: integer
- - description: '1: unpublished; 0 or empty: published'
- in: formData
- name: unpublished
- type: string
+ /config/api/route/preview:
+ post:
+ consumes:
+ - application/json
produces:
- application/json
responses:
"200":
- description: JSON array
+ description: OK
schema:
type: string
- summary: get all method list below one resource
+ summary: preview API route binding
tags:
- Config
- /config/api/resource/method/publish:
+ /config/api/route/publish:
put:
- description: 'TODO: unimplemented'
+ parameters:
+ - description: Route binding name
+ in: query
+ name: name
+ required: true
+ type: string
+ - description: Draft route key mod revision
+ in: query
+ name: expectedRevision
+ type: integer
produces:
- application/json
responses:
@@ -546,10 +496,10 @@ paths:
description: OK
schema:
type: string
- summary: batch Release Method Config
+ summary: atomically publish one API route binding
tags:
- Config
- /config/api/opa/policy:
+ /config/api/route/schema:
get:
produces:
- application/json
@@ -558,41 +508,15 @@ paths:
description: OK
schema:
type: string
- summary: get OPA policy (server mode)
+ summary: get API route binding schema
tags:
- Config
+ /config/api/route/status:
+ get:
parameters:
- - description: OPA server url
+ - description: Route binding name
in: query
- name: server_url
- type: string
- - description: Policy ID
- in: query
- name: policy_id
- type: string
- - description: Bearer token
- in: query
- name: bearer_token
- type: string
- put:
- consumes:
- - application/x-www-form-urlencoded
- parameters:
- - description: OPA server url
- in: formData
- name: server_url
- type: string
- - description: Policy ID
- in: formData
- name: policy_id
- type: string
- - description: Bearer token
- in: formData
- name: bearer_token
- type: string
- - description: Rego content
- in: formData
- name: content
+ name: name
required: true
type: string
produces:
@@ -602,10 +526,13 @@ paths:
description: OK
schema:
type: string
- summary: upload OPA policy (server mode)
+ summary: get API route binding status
tags:
- Config
- delete:
+ /config/api/route/validate:
+ post:
+ consumes:
+ - application/json
produces:
- application/json
responses:
@@ -613,35 +540,23 @@ paths:
description: OK
schema:
type: string
- summary: delete OPA policy (server mode)
+ summary: validate API route binding
tags:
- Config
- parameters:
- - description: OPA server url
- in: query
- name: server_url
- type: string
- - description: Policy ID
- in: query
- name: policy_id
- type: string
- - description: Bearer token
- in: query
- name: bearer_token
- type: string
- /config/api/resource/publish:
- put:
- description: publish resources from unpublished spaces to published spaces
+ /config/api/xds/status:
+ get:
+ description: Returns xDS listener availability, last-good snapshot metadata,
+ latest errors, readiness, and resource support matrix.
produces:
- application/json
responses:
"200":
description: OK
schema:
- type: string
- summary: publish all configuration information
+ $ref: '#/definitions/github_com_apache_dubbo-go-pixiu_admin_config.RetData'
+ summary: get Admin xDS publication status
tags:
- - Config
+ - XDS
/register:
post:
parameters:
diff --git a/admin/initialize/router.go b/admin/initialize/router.go
index 391981a72..8a6ea0188 100644
--- a/admin/initialize/router.go
+++ b/admin/initialize/router.go
@@ -61,12 +61,6 @@ func Routers() *gin.Engine {
taR.POST("/config/api/base/", configInfo.SetBaseInfo)
taR.PUT("/config/api/base/", configInfo.SetBaseInfo)
- taR.GET("/config/api/resource/list", configInfo.GetResourceList)
- taR.GET("/config/api/resource/detail", configInfo.GetResourceDetail)
- taR.POST("/config/api/resource", configInfo.CreateResourceInfo)
- taR.PUT("/config/api/resource", configInfo.ModifyResourceInfo)
- taR.DELETE("/config/api/resource", configInfo.DeleteResourceInfo)
-
taR.GET("/config/api/cluster/list", configInfo.GetClusterList)
taR.GET("/config/api/cluster/detail", configInfo.DetailCluster)
taR.POST("/config/api/cluster", configInfo.UpdateCluster)
@@ -79,20 +73,28 @@ func Routers() *gin.Engine {
taR.PUT("/config/api/listener", configInfo.CreateListener)
taR.DELETE("/config/api/listener", configInfo.DeleteListener)
- taR.GET("/config/api/resource/method/list", configInfo.GetMethodList)
- taR.GET("/config/api/resource/method/detail", configInfo.GetMethodDetail)
- taR.POST("/config/api/resource/method", configInfo.CreateMethodInfo)
- taR.PUT("/config/api/resource/method", configInfo.ModifyMethodInfo)
- taR.DELETE("/config/api/resource/method", configInfo.DeleteMethodInfo)
+ // AdminRouteBinding API. Each route has
+ // an independent draft/publish boundary; publishing one route still
+ // updates its generated legacy keys in one etcd transaction.
+ taR.GET("/config/api/route/schema", configInfo.GetRouteBindingSchema)
+ taR.GET("/config/api/route/list", configInfo.GetRouteBindingList)
+ taR.GET("/config/api/route/detail", configInfo.GetRouteBindingDetail)
+ taR.POST("/config/api/route", configInfo.CreateRouteBinding)
+ taR.PUT("/config/api/route", configInfo.ModifyRouteBinding)
+ taR.DELETE("/config/api/route", configInfo.DeleteRouteBinding)
+ taR.POST("/config/api/route/validate", configInfo.ValidateRouteBinding)
+ taR.POST("/config/api/route/preview", configInfo.PreviewRouteBinding)
+ taR.PUT("/config/api/route/publish", configInfo.PublishRouteBinding)
+ taR.GET("/config/api/route/status", configInfo.GetRouteBindingStatus)
+ taR.GET("/config/api/route/diff", configInfo.GetRouteBindingDiff)
+
+ // PluginGroup publication is independent of API route publication.
+ taR.PUT("/config/api/plugin_group/publish", configInfo.BatchReleasePluginGroup)
taR.GET("/config/api/opa/policy", opa.GetOPAPolicy)
taR.PUT("/config/api/opa/policy", opa.PutOPAPolicy)
taR.DELETE("/config/api/opa/policy", opa.DeleteOPAPolicy)
- // Which request method to choose, Temporarily choose put method
- taR.PUT("/config/api/resource/publish", configInfo.BatchReleaseResource)
- taR.PUT("/config/api/resource/method/publish", configInfo.BatchReleaseMethod)
- taR.PUT("/config/api/plugin_group/publish", configInfo.BatchReleasePluginGroup)
}
return router
diff --git a/admin/controller/configInfo/configInfo_test.go b/admin/initialize/router_plugin_group_test.go
similarity index 58%
copy from admin/controller/configInfo/configInfo_test.go
copy to admin/initialize/router_plugin_group_test.go
index 1f82312e8..d9fcb28f8 100644
--- a/admin/controller/configInfo/configInfo_test.go
+++ b/admin/initialize/router_plugin_group_test.go
@@ -15,34 +15,17 @@
* limitations under the License.
*/
-package configInfo
+package initialize
import (
- "fmt"
- "strings"
"testing"
)
-func Test_method1(t *testing.T) {
- var list1, list2 []string
- list1 = append(list1, "a")
- list2 = nil
- for _, v1 := range list1 {
- for _, v := range list2 {
- fmt.Println("in side" + v)
- //t.Log("inside" + v)
+func TestPluginGroupPublishRouteRegistered(t *testing.T) {
+ for _, route := range Routers().Routes() {
+ if route.Method == "PUT" && route.Path == "/config/api/plugin_group/publish" {
+ return
}
- fmt.Println(v1)
- //t.Log("outside" + v1)
}
-}
-
-func Test_regx_split(t *testing.T) {
- txt := "/config/api/resources/1/xxx"
- //re := regexp.MustCompile("\\(?<=config\\).+\\(?=resources\\)")
- pre := "/config/api/"
- //re := regexp.MustCompile("^/resources/1")
- split := strings.TrimPrefix(txt, pre)
- //split := re.Split(txt,-1)
- fmt.Println(split)
+ t.Fatal("PUT /config/api/plugin_group/publish is not registered")
}
diff --git a/admin/logic/logic.go b/admin/logic/logic.go
index 602cd03a5..1b944691a 100644
--- a/admin/logic/logic.go
+++ b/admin/logic/logic.go
@@ -48,19 +48,17 @@ import (
const (
Base = "base"
- Resources = "resources"
Method = "method"
ResourceID = "resourceId"
ClusterID = "clusterId"
Listener = "listener"
- MethodID = "methodId"
- PluginGroup = "pluginGroup"
Plugin = "plugin"
Filter = "filter"
Ratelimit = "ratelimit"
OPA = "opa"
Clusters = "clusters"
Listeners = "listeners"
+ PluginGroup = "pluginGroup"
Unpublished = "unpublished"
ErrID = -1
@@ -118,229 +116,6 @@ func BizSetBaseInfo(info *adminconfig.BaseInfo, created bool) error {
return nil
}
-// BizGetResourceList get resource list
-func BizGetResourceList(unpublished bool) ([]config.Resource, error) {
- var kList, vList []string
- var err error
- if unpublished {
- kList, vList, err = adminconfig.Client.GetChildrenKVList(getUnpublishedRootPath(Resources))
- } else {
- kList, vList, err = adminconfig.Client.GetChildrenKVList(getRootPath(Resources))
- }
-
- if err != nil {
- logger.Errorf("BizGetResourceList err, %v\n", err)
- return nil, perrors.WithMessage(err, "BizGetResourceList error")
- }
- var ret []config.Resource
-
- for i, k := range kList {
- // only handle resource, filter method
- re := getCheckResourceRegexp()
- if m := re.Match([]byte(k)); !m {
- continue
- }
- v := vList[i]
- res := &config.Resource{}
- err := yaml.UnmarshalYML([]byte(v), res)
- if err != nil {
- logger.Errorf("UnmarshalYML err, %v\n", err)
- }
- ret = append(ret, *res)
- }
-
- return ret, nil
-}
-
-// BizGetResourceDetail get resource detail
-func BizGetResourceDetail(id string, unpublished bool) (string, error) {
- key := getResourceKey(id, unpublished)
- detail, err := adminconfig.Client.Get(key)
- if err != nil {
- logger.Errorf("BizGetResourceDetail err, %v\n", err)
- return "", perrors.WithMessage(err, "BizGetResourceDetail error")
- }
- return detail, nil
-}
-
-// BizSetResourceInfo create resource
-func BizSetResourceInfo(res *config.Resource, created, unpublished bool) error {
-
- if created {
- // backups method
- methods := res.Methods
- res.Methods = nil
-
- res.ID = getResourceId()
- if res.ID == ErrID {
- logger.Warnf("can't get id from etcd")
- return perrors.New("BizSetResourceInfo error can't get id from etcd")
- }
- data, _ := yaml.MarshalYML(res)
-
- setErr := adminconfig.Client.Create(getResourceKey(strconv.Itoa(res.ID), unpublished), string(data))
- if setErr != nil {
- logger.Warnf("Create etcd error, %v\n", setErr)
- return perrors.WithMessage(setErr, "BizSetResourceInfo error")
- }
-
- for i := range methods {
- methods[i].ResourcePath = res.Path
- }
- // create methods
- _ = BizBatchCreateResourceMethod(strconv.Itoa(res.ID), methods, unpublished)
- } else {
- key := getResourceKey(strconv.Itoa(res.ID), unpublished)
- data, _ := yaml.MarshalYML(res)
-
- // should set method in this situation
- res.Methods = nil
- setErr := adminconfig.Client.Update(key, string(data))
- if setErr != nil {
- logger.Warnf("update etcd error, %v\n", setErr)
- return perrors.WithMessage(setErr, "BizSetResourceInfo error")
- }
- }
- return nil
-}
-
-// BizDeleteResourceInfo delete resource
-func BizDeleteResourceInfo(id string, unpublished bool) error {
- key := getResourceKey(id, unpublished)
- // delete all key with prefix to delete method key
- _, err := adminconfig.Client.GetRawClient().Delete(adminconfig.Client.GetCtx(), key, clientv3.WithPrefix())
- if err != nil {
- logger.Warnf("BizDeleteResourceInfo, %v\n", err)
- return perrors.WithMessage(err, "BizDeleteResourceInfo error")
- }
- return nil
-}
-
-// BizGetMethodList get method list
-func BizGetMethodList(resourceId string, unpublished bool) ([]config.Method, error) {
- key := getResourceMethodPrefixKey(resourceId, unpublished)
-
- _, vList, err := adminconfig.Client.GetChildrenKVList(key)
- if err != nil {
- logger.Errorf("BizGetMethodList err, %v\n", err)
- return nil, perrors.WithMessage(err, "BizGetMethodList error")
- }
-
- var ret []config.Method
- for _, v := range vList {
- res := &config.Method{}
- err := yaml.UnmarshalYML([]byte(v), res)
- if err != nil {
- logger.Errorf("UnmarshalYML err, %v\n", err)
- }
- ret = append(ret, *res)
- }
-
- return ret, nil
-}
-
-// BizGetMethodDetail get method detail
-func BizGetMethodDetail(resourceId string, methodId string, unpublished bool) (string, error) {
- key := getMethodKey(resourceId, methodId, unpublished)
- detail, err := adminconfig.Client.Get(key)
- if err != nil {
- logger.Errorf("BizGetMethodDetail err, %v\n", err)
- return "", perrors.WithMessage(err, "BizGetMethodDetail error")
- }
- return detail, nil
-}
-
-// BizBatchCreateResourceMethod batch create method below one resource
-func BizBatchCreateResourceMethod(resourceId string, methods []config.Method, unpublished bool) error {
-
- if len(methods) == 0 {
- return nil
- }
-
- var kList, vList []string
-
- for _, method := range methods {
- method.ID = getMethodId()
- if method.ID == ErrID {
- logger.Warnf("can't get id from etcd")
- continue
- }
- kList = append(kList, getMethodKey(resourceId, strconv.Itoa(method.ID), unpublished))
- data, _ := yaml.MarshalYML(method)
- vList = append(vList, string(data))
- }
-
- err := adminconfig.Client.BatchCreate(kList, vList)
- if err != nil {
- logger.Warnf("update etcd error, %v\n", err)
- return perrors.WithMessage(err, "BizBatchCreateResourceMethod error")
- }
- return nil
-}
-
-// BizSetResourceMethod create or update method below specific path
-func BizSetResourceMethod(resourceId string, method *config.Method, created, unpublished bool) error {
-
- if created {
- method.ID = getMethodId()
- key := getMethodKey(resourceId, strconv.Itoa(method.ID), unpublished)
-
- if method.ID == ErrID {
- logger.Warnf("can't get id from etcd")
- return perrors.New("BizSetResourceMethod error can't get id from etcd")
- }
- data, _ := yaml.MarshalYML(method)
-
- err := adminconfig.Client.Create(key, string(data))
- if err != nil {
- logger.Warnf("BizSetResourceMethod etcd error, %v\n", err)
- return perrors.WithMessage(err, "BizSetResourceMethod error")
- }
- } else {
- data, _ := yaml.MarshalYML(method)
- key := getMethodKey(resourceId, strconv.Itoa(method.ID), unpublished)
- err := adminconfig.Client.Update(key, string(data))
- if err != nil {
- logger.Warnf("BizSetResourceMethod etcd error, %v\n", err)
- return perrors.WithMessage(err, "BizSetResourceMethod error")
- }
- }
-
- return nil
-}
-
-// BizDeleteMethodInfo delete method
-func BizDeleteMethodInfo(resourceId string, methodId string, unpublished bool) error {
- key := getMethodKey(resourceId, methodId, unpublished)
- err := adminconfig.Client.Delete(key)
- if err != nil {
- logger.Warnf("BizDeleteMethodInfo, %v\n", err)
- return perrors.WithMessage(err, "BizDeleteMethodInfo error")
- }
- return nil
-}
-
-// BRGetResourceList GetResourceList
-func BRGetResourceList(unpublished bool) ([]string, []string, error) {
- if unpublished {
- return adminconfig.Client.GetChildrenKVList(getUnpublishedRootPath(Resources))
- } else {
- return adminconfig.Client.GetChildrenKVList(getRootPath(Resources))
- }
-}
-
-// BRGetMethodList GetMethodList
-func BRGetMethodList(resourceId string, unpublished bool) ([]string, []string, error) {
- key := getResourceMethodPrefixKey(resourceId, unpublished)
- return adminconfig.Client.GetChildrenKVList(key)
-}
-
-// BRGetPluginGroupList GetPluginGroupList
-func BRGetPluginGroupList(unpublished bool) ([]string, []string, error) {
- key := getPluginGroupPrefixKey(unpublished)
- return adminconfig.Client.GetChildrenKVList(key)
-}
-
// BizGetClusters get clusters
func BizGetClusters() ([]config.Cluster, error) {
var (
@@ -532,22 +307,43 @@ func BizGetListener(name string) (string, error) {
return detail, nil
}
-// BRUpdate
-func BRUpdate(key, value string) error {
- return adminconfig.Client.Update(key, value)
-}
+// BizPublishPluginGroupConfig copies the first staged PluginGroup config into
+// the published namespace, creating it if it does not already exist.
+func BizPublishPluginGroupConfig() error {
+ if adminconfig.Client == nil {
+ return perrors.New("admin etcd client is not initialized")
+ }
+ if adminconfig.Bootstrap == nil {
+ return perrors.New("admin bootstrap is not initialized")
+ }
-func BRCreate(key, value, configType string) error {
- if strings.EqualFold(configType, Resources) {
- return adminconfig.Client.Create(getResourceKey(key, false), value)
- } else if strings.EqualFold(configType, Method) {
+ draftKeys, draftValues, err := adminconfig.Client.GetChildrenKVList(getPluginGroupPrefixKey(true))
+ if err != nil {
+ return perrors.WithMessage(err, "get unpublished PluginGroup config")
+ }
+ if len(draftKeys) == 0 || len(draftKeys) != len(draftValues) {
+ return perrors.New("unpublished PluginGroup config is empty or invalid")
+ }
- } else if strings.EqualFold(configType, PluginGroup) {
- return adminconfig.Client.Create(getPluginGroupKey(key, false), value)
- } else {
- return adminconfig.Client.Create(getPluginRatelimitKey(false), value)
+ publishedKeys, publishedValues, err := adminconfig.Client.GetChildrenKVList(getPluginGroupPrefixKey(false))
+ if err != nil && !errors.Is(err, gxetcd.ErrKVPairNotFound) {
+ return perrors.WithMessage(err, "get published PluginGroup config")
+ }
+ if len(publishedKeys) == 0 {
+ name := strings.TrimPrefix(draftKeys[0], getPluginGroupPrefixKey(true)+"/")
+ if name == draftKeys[0] || name == "" || strings.Contains(name, "/") {
+ return perrors.Errorf("invalid unpublished PluginGroup key %q", draftKeys[0])
+ }
+ key := getPluginGroupPrefixKey(false) + "/" + name
+ return adminconfig.Client.Create(key, draftValues[0])
}
- return errors.New("")
+ if len(publishedKeys) != len(publishedValues) {
+ return perrors.New("published PluginGroup config is invalid")
+ }
+ if strings.EqualFold(draftValues[0], publishedValues[0]) {
+ return nil
+ }
+ return adminconfig.Client.Update(publishedKeys[0], draftValues[0])
}
// BizGetOPAPolicy fetches the policy raw text. Returns empty string if not found.
@@ -671,13 +467,6 @@ func doOPARequestWithStatus(method, url, bearerToken, contentType string, body [
}
}
-func getResourceKey(path string, unpublished bool) string {
- if unpublished {
- return getUnpublishedRootPath(Resources) + "/" + path
- }
- return getRootPath(Resources) + "/" + path
-}
-
func getClusterKey(path string) string {
return getRootPath(Clusters) + "/" + path
}
@@ -686,14 +475,6 @@ func getListenerKey(path string) string {
return getRootPath(Listeners) + "/" + path
}
-func getPluginRatelimitKey(unpublished bool) string {
- return getFilterPrefixKey(unpublished) + "/" + Ratelimit
-}
-
-func getPluginGroupKey(name string, unpublished bool) string {
- return getPluginGroupPrefixKey(unpublished) + "/" + name
-}
-
func getPluginGroupPrefixKey(unpublished bool) string {
if unpublished {
return getUnpublishedRootPath(PluginGroup)
@@ -701,6 +482,10 @@ func getPluginGroupPrefixKey(unpublished bool) string {
return getRootPath(PluginGroup)
}
+func getPluginRatelimitKey(unpublished bool) string {
+ return getFilterPrefixKey(unpublished) + "/" + Ratelimit
+}
+
func getFilterPrefixKey(unpublished bool) string {
if unpublished {
return getUnpublishedRootPath(Filter)
@@ -708,27 +493,10 @@ func getFilterPrefixKey(unpublished bool) string {
return getRootPath(Filter)
}
-func getResourceMethodPrefixKey(path string, unpublished bool) string {
- return getResourceKey(path, unpublished) + "/" + Method
-}
-
-func getMethodKey(path string, method string, unpublished bool) string {
- return getResourceMethodPrefixKey(path, unpublished) + "/" + method
-}
-
-// create method, No need to judge whether to publish or not
-func getResourceId() int {
- return loopGetId(getRootPath(ResourceID))
-}
-
func getClusterId() int {
return loopGetId(getRootPath(ClusterID))
}
-func getMethodId() int {
- return loopGetId(getRootPath(MethodID))
-}
-
func loopGetId(k string) int {
for {
@@ -786,10 +554,6 @@ func getUnpublishedRootPath(key string) string {
return adminconfig.Bootstrap.GetPath() + "/" + Unpublished + "/" + key
}
-func getCheckResourceRegexp() *regexp.Regexp {
- return regexp.MustCompile(".+/resources/[^/]+/?$")
-}
-
func getCheckClusterRegexp() *regexp.Regexp {
return regexp.MustCompile(".+/clusters/[^/]+/?$")
}
diff --git a/admin/logic/route_binding.go b/admin/logic/route_binding.go
new file mode 100644
index 000000000..d19903d7a
--- /dev/null
+++ b/admin/logic/route_binding.go
@@ -0,0 +1,1371 @@
+/*
+ * 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 (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/url"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+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"
+ legacyconfig "github.com/apache/dubbo-go-pixiu/pkg/config"
+ "github.com/apache/dubbo-go-pixiu/pkg/config/schema"
+)
+
+const (
+ routeBindingPathSegment = "route-bindings"
+ routeBindingRevisionSegment = "route-bindings-revision"
+ routeBindingRuntimeResourceDir = "resources"
+ maxRouteBindingIDRetries = 16
+)
+
+var (
+ ErrRouteBindingNotFound = errors.New("admin route binding not found")
+ ErrRouteBindingAlreadyExists = errors.New("admin route binding already exists")
+ ErrRouteBindingNameImmutable = errors.New("admin route binding metadata.name is immutable")
+ ErrRouteBindingConflict = errors.New("admin route binding was modified concurrently")
+ ErrRouteBindingPublishConflict = errors.New("admin route binding publish conflict")
+ ErrRouteBindingRuntimeConflict = errors.New("admin route binding conflicts with an existing runtime route")
+)
+
+// routeBindingKV is the small part of clientv3.KV needed by the route store.
+// Keeping this boundary narrow makes the planning and transaction logic easy
+// to exercise without coupling it to the gost wrapper.
+type routeBindingKV interface {
+ Get(context.Context, string, ...clientv3.OpOption) (*clientv3.GetResponse, error)
+ Txn(context.Context) clientv3.Txn
+}
+
+// RouteBinding is the Admin-facing response shape. ResourceID and MethodID
+// are stable runtime identities used by Pixiu's legacy etcd watcher; they are
+// not part of the user-editable AdminRouteBinding object.
+type RouteBinding struct {
+ Object schema.AdminObject `json:"object"`
+ ResourceID int `json:"resourceId"`
+ MethodID int `json:"methodId"`
+ Revision int64 `json:"revision"`
+ PublishStatus *RouteBindingPublishStatus `json:"publishStatus,omitempty"`
+}
+
+// RouteBindingPublishResult describes one atomic publish transaction.
+type RouteBindingPublishResult struct {
+ Name string `json:"name"`
+ Revision int64 `json:"revision"`
+ DraftRevision int64 `json:"draftRevision"`
+ PublishedRevision int64 `json:"publishedRevision"`
+ PublishedCount int `json:"publishedCount"`
+ DeletedCount int `json:"deletedCount"`
+}
+
+// RouteBindingPublishStatus exposes one route's draft and published state.
+// Revisions are the etcd key mod revisions for that route, not a global
+// configuration revision.
+type RouteBindingPublishStatus struct {
+ Name string `json:"name"`
+ DraftRevision int64 `json:"draftRevision"`
+ PublishedRevision int64 `json:"publishedRevision"`
+ DraftExists bool `json:"draftExists"`
+ PublishedExists bool `json:"publishedExists"`
+ Dirty bool `json:"dirty"`
+}
+
+type RouteBindingDiffChange struct {
+ Path string `json:"path"`
+ Before any `json:"before"`
+ After any `json:"after"`
+}
+
+// RouteBindingDiff compares one route's draft object with its published
+// object. A nil side represents a route that only exists in the other scope.
+type RouteBindingDiff struct {
+ Name string `json:"name"`
+ Draft *RouteBinding `json:"draft,omitempty"`
+ Published *RouteBinding `json:"published,omitempty"`
+ Changes []RouteBindingDiffChange `json:"changes"`
+}
+
+type routeBindingRecord struct {
+ Object schema.AdminObject `json:"object"`
+ ResourceID int `json:"resourceId"`
+ MethodID int `json:"methodId"`
+}
+
+type routeBindingEntry struct {
+ record routeBindingRecord
+ key string
+ revision int64
+}
+
+// RouteBindingStore owns the AdminRouteBinding persistence and publish
+// boundary. Published runtime data is deliberately written in the existing
+// Resource/Method layout so the current Pixiu watcher can consume it.
+type RouteBindingStore struct {
+ kv routeBindingKV
+ root string
+ registry *schema.Registry
+}
+
+// NewRouteBindingStore creates a store over an etcd v3 client.
+func NewRouteBindingStore(kv routeBindingKV, root string, registry *schema.Registry) (*RouteBindingStore, error) {
+ if kv == nil {
+ return nil, errors.New("route binding etcd client is nil")
+ }
+ root = strings.TrimRight(strings.TrimSpace(root), "/")
+ if root == "" {
+ return nil, errors.New("route binding etcd root path is empty")
+ }
+ if registry == nil {
+ var err error
+ registry, err = schema.NewBuiltinRegistry()
+ if err != nil {
+ return nil, fmt.Errorf("create route binding schema registry: %w", err)
+ }
+ }
+ return &RouteBindingStore{kv: kv, root: root, registry: registry}, nil
+}
+
+// NewAdminRouteBindingStore creates the production store from the Admin
+// process' configured etcd client and root path.
+func NewAdminRouteBindingStore() (*RouteBindingStore, error) {
+ if adminconfig.Bootstrap == nil {
+ return nil, errors.New("admin bootstrap is nil")
+ }
+ if adminconfig.Client == nil {
+ return nil, errors.New("admin etcd client is nil")
+ }
+ rawClient := adminconfig.Client.GetRawClient()
+ if rawClient == nil {
+ return nil, errors.New("admin raw etcd client is nil")
+ }
+ registry, err := schema.DefaultRegistry()
+ if err != nil {
+ return nil, fmt.Errorf("get Admin route binding schema registry: %w", err)
+ }
+ return NewRouteBindingStore(rawClient, adminconfig.Bootstrap.GetPath(), registry)
+}
+
+func routeBindingContext(ctx context.Context) context.Context {
+ if ctx == nil {
+ return context.Background()
+ }
+ return ctx
+}
+
+// Registry returns the schema registry used by this store.
+func (s *RouteBindingStore) Registry() *schema.Registry {
+ return s.registry
+}
+
+// List returns high-level route bindings from either the draft or published
+// namespace. Empty namespaces are returned as an empty slice.
+func (s *RouteBindingStore) List(ctx context.Context, unpublished bool) ([]RouteBinding, error) {
+ ctx = routeBindingContext(ctx)
+ entries, err := s.listEntries(ctx, s.bindingPrefix(unpublished))
+ if err != nil {
+ return nil, err
+ }
+ var statuses map[string]RouteBindingPublishStatus
+ if unpublished {
+ publishedEntries, err := s.listEntries(ctx, s.bindingPrefix(false))
+ if err != nil {
+ return nil, err
+ }
+ statuses = routeBindingStatuses(entries, publishedEntries)
+ }
+ result := make([]RouteBinding, 0, len(entries))
+ for _, entry := range entries {
+ view := routeBindingView(entry)
+ if status, exists := statuses[entry.record.Object.Metadata.Name]; exists {
+ view.PublishStatus = &status
+ }
+ result = append(result, view)
+ }
+ return result, nil
+}
+
+func routeBindingStatuses(draftEntries, publishedEntries []routeBindingEntry) map[string]RouteBindingPublishStatus {
+ publishedByName := make(map[string]routeBindingEntry, len(publishedEntries))
+ for _, entry := range publishedEntries {
+ publishedByName[entry.record.Object.Metadata.Name] = entry
+ }
+
+ statuses := make(map[string]RouteBindingPublishStatus, len(draftEntries))
+ for _, draft := range draftEntries {
+ name := draft.record.Object.Metadata.Name
+ published, publishedExists := publishedByName[name]
+ status := RouteBindingPublishStatus{
+ Name: name,
+ DraftRevision: draft.revision,
+ DraftExists: true,
+ PublishedExists: publishedExists,
+ PublishedRevision: published.revision,
+ Dirty: !publishedExists || !reflect.DeepEqual(draft.record.Object, published.record.Object),
+ }
+ statuses[name] = status
+ }
+ return statuses
+}
+
+// Get returns one high-level route binding from either the draft or published
+// namespace.
+func (s *RouteBindingStore) Get(ctx context.Context, name string, unpublished bool) (RouteBinding, error) {
+ ctx = routeBindingContext(ctx)
+ name, err := normalizeRouteBindingName(name)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+ entry, exists, _, err := s.getEntry(ctx, s.bindingPrefix(unpublished), name)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+ if !exists {
+ return RouteBinding{}, fmt.Errorf("%w: %s", ErrRouteBindingNotFound, name)
+ }
+ return routeBindingView(entry), nil
+}
+
+// Normalize validates an object and applies all registered schema defaults.
+// It is useful to the controller's validate and preview endpoints and does
+// not require an etcd write.
+func (s *RouteBindingStore) Normalize(object schema.AdminObject) (schema.AdminObject, error) {
+ normalized, err := s.registry.Normalize(object)
+ if err != nil {
+ return normalized, err
+ }
+ name, err := normalizeRouteBindingName(normalized.Metadata.Name)
+ if err != nil {
+ return normalized, err
+ }
+ normalized.Metadata.Name = name
+ return normalized, nil
+}
+
+// Preview validates and compiles an Admin object without writing it.
+func (s *RouteBindingStore) Preview(object schema.AdminObject) (schema.AdminObject, []byte, error) {
+ normalized, err := s.Normalize(object)
+ if err != nil {
+ return normalized, nil, err
+ }
+ compiled, err := schema.CompileAdminRouteBinding(s.registry, normalized)
+ if err != nil {
+ return normalized, nil, err
+ }
+ preview, err := compiled.PreviewYAML()
+ if err != nil {
+ return normalized, nil, err
+ }
+ return normalized, preview, nil
+}
+
+// SaveDraft validates and atomically stores one AdminRouteBinding in the
+// draft namespace. POST callers use create=true; PUT callers use create=false.
+// expectedRevision is the draft key's mod revision and may be zero to allow
+// an unconditional write.
+func (s *RouteBindingStore) SaveDraft(ctx context.Context, object schema.AdminObject, create bool, expectedRevision int64) (RouteBinding, error) {
+ ctx = routeBindingContext(ctx)
+ if err := validateSaveDraftRequest(create, expectedRevision); err != nil {
+ return RouteBinding{}, err
+ }
+ normalized, err := s.Normalize(object)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+ name := normalized.Metadata.Name
+ draftPrefix := s.bindingPrefix(true)
+ draftEntry, draftExists, draftRevision, err := s.getEntry(ctx, draftPrefix, name)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+ if err := validateDraftSaveState(name, create, expectedRevision, draftExists, draftRevision); err != nil {
+ return RouteBinding{}, err
+ }
+
+ resourceID, methodID, err := s.resolveRuntimeIdentity(ctx, name, draftEntry, draftExists)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+
+ record := routeBindingRecord{
+ Object: normalized,
+ ResourceID: resourceID,
+ MethodID: methodID,
+ }
+ value, err := json.Marshal(record)
+ if err != nil {
+ return RouteBinding{}, fmt.Errorf("encode route binding %q: %w", name, err)
+ }
+ if err := s.commitDraft(ctx, name, draftPrefix, value, create, expectedRevision); err != nil {
+ return RouteBinding{}, err
+ }
+
+ saved, exists, revision, err := s.getEntry(ctx, draftPrefix, name)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+ if !exists {
+ return RouteBinding{}, fmt.Errorf("route binding %q disappeared after save", name)
+ }
+ saved.revision = revision
+ return routeBindingView(saved), nil
+}
+
+// UpdateDraft updates one existing route binding draft without allowing its
+// metadata.name to change. The original name is the stable identity supplied
+// by the caller, while the object name is user-editable in the YAML editor.
+func (s *RouteBindingStore) UpdateDraft(ctx context.Context, originalName string, object schema.AdminObject, expectedRevision int64) (RouteBinding, error) {
+ originalName, err := normalizeRouteBindingName(originalName)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+ normalized, err := s.Normalize(object)
+ if err != nil {
+ return RouteBinding{}, err
+ }
+ if normalized.Metadata.Name != originalName {
+ return RouteBinding{}, fmt.Errorf("%w: %q cannot be changed to %q", ErrRouteBindingNameImmutable, originalName, normalized.Metadata.Name)
+ }
+ return s.SaveDraft(ctx, normalized, false, expectedRevision)
+}
+
+func validateSaveDraftRequest(create bool, expectedRevision int64) error {
+ if expectedRevision < 0 {
+ return errors.New("expected revision must not be negative")
+ }
+ if create && expectedRevision > 0 {
+ return errors.New("create route binding does not accept an expected revision")
+ }
+ return nil
+}
+
+func validateDraftSaveState(name string, create bool, expectedRevision int64, exists bool, revision int64) error {
+ if create && exists {
+ return fmt.Errorf("%w: %s", ErrRouteBindingAlreadyExists, name)
+ }
+ if expectedRevision > 0 && (!exists || revision != expectedRevision) {
+ return fmt.Errorf("%w: %s", ErrRouteBindingConflict, name)
+ }
+ return nil
+}
+
+func (s *RouteBindingStore) resolveRuntimeIdentity(ctx context.Context, name string, draft routeBindingEntry, draftExists bool) (int, int, error) {
+ resourceID, methodID := draft.record.ResourceID, draft.record.MethodID
+ if !draftExists {
+ published, exists, _, err := s.getEntry(ctx, s.bindingPrefix(false), name)
+ if err != nil {
+ return 0, 0, err
+ }
+ if exists {
+ resourceID, methodID = published.record.ResourceID, published.record.MethodID
+ }
+ }
+ if resourceID <= 0 {
+ var err error
+ resourceID, err = s.allocateRuntimeID(ctx)
+ if err != nil {
+ return 0, 0, err
+ }
+ }
+ if methodID <= 0 {
+ // One AdminRouteBinding currently compiles to exactly one Method. Method
+ // IDs are scoped below the resource, so sharing the stable route ID is
+ // safe and avoids a second allocation transaction.
+ methodID = resourceID
+ }
+ return resourceID, methodID, nil
+}
+
+func (s *RouteBindingStore) commitDraft(ctx context.Context, name, draftPrefix string, value []byte, create bool, expectedRevision int64) error {
+ comparisons := make([]clientv3.Cmp, 0, 1)
+ if create {
+ comparisons = append(comparisons, clientv3.Compare(clientv3.CreateRevision(s.bindingKey(draftPrefix, name)), "=", 0))
+ } else if expectedRevision > 0 {
+ comparisons = append(comparisons, clientv3.Compare(clientv3.ModRevision(s.bindingKey(draftPrefix, name)), "=", expectedRevision))
+ }
+ operations := []clientv3.Op{
+ clientv3.OpPut(s.bindingKey(draftPrefix, name), string(value)),
+ }
+ transaction := s.kv.Txn(ctx)
+ if len(comparisons) > 0 {
+ transaction = transaction.If(comparisons...)
+ }
+ response, err := transaction.Then(operations...).Commit()
+ if err != nil {
+ return fmt.Errorf("save route binding %q: %w", name, err)
+ }
+ if response.Succeeded {
+ return nil
+ }
+ if create {
+ return fmt.Errorf("%w: %s", ErrRouteBindingAlreadyExists, name)
+ }
+ return fmt.Errorf("%w: %s", ErrRouteBindingConflict, name)
+}
+
+// DeleteAndPublish removes one route draft and its published runtime state in
+// the same etcd transaction. This keeps the delete flow atomic for callers:
+// there is no intermediate state where the draft is gone but the route still
+// remains active in Pixiu.
+func (s *RouteBindingStore) DeleteAndPublish(ctx context.Context, name string, expectedRevision int64) (RouteBindingPublishResult, error) {
+ ctx = routeBindingContext(ctx)
+ if expectedRevision < 0 {
+ return RouteBindingPublishResult{}, errors.New("expected revision must not be negative")
+ }
+ name, err := normalizeRouteBindingName(name)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ markerRevision, markerExists, err := s.markerRevision(ctx, s.publishedRevisionKey())
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ state, err := s.readPublishState(ctx, name)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ if expectedRevision > 0 && (!state.draftExists || state.draftRevision != expectedRevision) {
+ return RouteBindingPublishResult{}, fmt.Errorf("%w: %s", ErrRouteBindingConflict, name)
+ }
+ comparisons := s.buildPublishComparisons(state, markerRevision, markerExists)
+ operations := make([]clientv3.Op, 0, 4)
+ if state.draftExists {
+ operations = append(operations, clientv3.OpDelete(s.bindingKey(state.draftPrefix, name)))
+ }
+ deletedCount := 0
+ if state.publishedExists {
+ if state.published.record.ResourceID <= 0 || state.published.record.MethodID <= 0 {
+ return RouteBindingPublishResult{}, fmt.Errorf("published route binding %q has invalid runtime identity", name)
+ }
+ operations = append(operations, s.runtimeResourceDeleteOperations(state.published.record.ResourceID)...)
+ operations = append(operations, clientv3.OpDelete(s.bindingKey(state.publishedPrefix, name)))
+ deletedCount = 1
+ }
+ operations = append(operations,
+ clientv3.OpPut(s.publishedRevisionKey(), strconv.FormatInt(time.Now().UnixNano(), 10)))
+ response, err := s.kv.Txn(ctx).If(comparisons...).Then(operations...).Commit()
+ if err != nil {
+ return RouteBindingPublishResult{}, fmt.Errorf("delete route binding %q: %w", name, err)
+ }
+ if !response.Succeeded {
+ return RouteBindingPublishResult{}, fmt.Errorf("%w: %s", ErrRouteBindingPublishConflict, name)
+ }
+ return RouteBindingPublishResult{
+ Name: name,
+ Revision: response.Header.Revision,
+ DraftRevision: state.draftRevision,
+ PublishedRevision: 0,
+ DeletedCount: deletedCount,
+ }, nil
+}
+
+// Publish publishes exactly one route binding. The generated legacy resource
+// and method, the published high-level binding, and the internal generation
+// guard are written or deleted in one etcd transaction. Other routes' draft
+// and published values are left untouched.
+func (s *RouteBindingStore) Publish(ctx context.Context, name string, expectedDraftRevision int64) (RouteBindingPublishResult, error) {
+ ctx = routeBindingContext(ctx)
+ if expectedDraftRevision < 0 {
+ return RouteBindingPublishResult{}, errors.New("expected draft revision must not be negative")
+ }
+ name, err := normalizeRouteBindingName(name)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ // Observe the generation before reading any route snapshot. A concurrent
+ // publish after this point must invalidate the transaction comparison.
+ markerRevision, markerExists, err := s.markerRevision(ctx, s.publishedRevisionKey())
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ state, err := s.readPublishState(ctx, name)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ if expectedDraftRevision > 0 && (!state.draftExists || state.draftRevision != expectedDraftRevision) {
+ return RouteBindingPublishResult{}, fmt.Errorf("%w: %s", ErrRouteBindingPublishConflict, name)
+ }
+ publishedEntries, err := s.listEntries(ctx, state.publishedPrefix)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ candidate, err := s.compilePublishCandidate(name, state.draft, state.draftExists, publishedEntries)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ if err := s.checkRuntimeRouteConflict(ctx, candidate, state); err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ comparisons := s.buildPublishComparisons(state, markerRevision, markerExists)
+ operations, publishedCount, deletedCount, err := s.buildSinglePublishOperations(state, candidate)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ operations = append(operations,
+ clientv3.OpPut(s.publishedRevisionKey(), strconv.FormatInt(time.Now().UnixNano(), 10)))
+ response, err := s.kv.Txn(ctx).If(comparisons...).Then(operations...).Commit()
+ if err != nil {
+ return RouteBindingPublishResult{}, fmt.Errorf("publish route binding %q: %w", name, err)
+ }
+ if !response.Succeeded {
+ return RouteBindingPublishResult{}, fmt.Errorf("%w: %s", ErrRouteBindingPublishConflict, name)
+ }
+ publishedRevision, err := s.publishedRouteRevision(ctx, state.publishedPrefix, name, candidate)
+ if err != nil {
+ return RouteBindingPublishResult{}, err
+ }
+ return RouteBindingPublishResult{
+ Name: name,
+ Revision: response.Header.Revision,
+ DraftRevision: state.draftRevision,
+ PublishedRevision: publishedRevision,
+ PublishedCount: publishedCount,
+ DeletedCount: deletedCount,
+ }, nil
+}
+
+type routeBindingPublishState struct {
+ draftPrefix string
+ publishedPrefix string
+ draft routeBindingEntry
+ draftExists bool
+ draftRevision int64
+ published routeBindingEntry
+ publishedExists bool
+ publishedRevision int64
+}
+
+func (s *RouteBindingStore) readPublishState(ctx context.Context, name string) (routeBindingPublishState, error) {
+ state := routeBindingPublishState{
+ draftPrefix: s.bindingPrefix(true),
+ publishedPrefix: s.bindingPrefix(false),
+ }
+ var err error
+ state.draft, state.draftExists, state.draftRevision, err = s.getEntry(ctx, state.draftPrefix, name)
+ if err != nil {
+ return routeBindingPublishState{}, err
+ }
+ state.published, state.publishedExists, state.publishedRevision, err = s.getEntry(ctx, state.publishedPrefix, name)
+ if err != nil {
+ return routeBindingPublishState{}, err
+ }
+ if !state.draftExists && !state.publishedExists {
+ return routeBindingPublishState{}, fmt.Errorf("%w: %s", ErrRouteBindingNotFound, name)
+ }
+ return state, nil
+}
+
+func (s *RouteBindingStore) compilePublishCandidate(name string, draft routeBindingEntry, draftExists bool, published []routeBindingEntry) (*compiledRouteEntry, error) {
+ if !draftExists {
+ return nil, nil
+ }
+ entries := make([]routeBindingEntry, 0, len(published)+1)
+ for _, entry := range published {
+ if entry.record.Object.Metadata.Name != name {
+ entries = append(entries, entry)
+ }
+ }
+ entries = append(entries, draft)
+ compiled, err := s.compileSnapshot(entries)
+ if err != nil {
+ return nil, err
+ }
+ for index := range compiled {
+ if compiled[index].object.Metadata.Name == name {
+ return &compiled[index], nil
+ }
+ }
+ return nil, fmt.Errorf("route binding %q was not compiled", name)
+}
+
+func (s *RouteBindingStore) buildPublishComparisons(state routeBindingPublishState, markerRevision int64, markerExists bool) []clientv3.Cmp {
+ comparisons := make([]clientv3.Cmp, 0, 2)
+ if state.draftExists {
+ // Always compare the value observed above, even when the caller omitted
+ // expectedDraftRevision. This closes the read/modify/write race.
+ comparisons = append(comparisons,
+ clientv3.Compare(clientv3.ModRevision(s.bindingKey(state.draftPrefix, state.draft.record.Object.Metadata.Name)), "=", state.draftRevision))
+ if state.publishedExists {
+ comparisons = append(comparisons,
+ clientv3.Compare(clientv3.ModRevision(s.bindingKey(state.publishedPrefix, state.published.record.Object.Metadata.Name)), "=", state.publishedRevision))
+ } else {
+ comparisons = append(comparisons,
+ clientv3.Compare(clientv3.CreateRevision(s.bindingKey(state.publishedPrefix, state.draft.record.Object.Metadata.Name)), "=", 0))
+ }
+ } else {
+ comparisons = append(comparisons,
+ clientv3.Compare(clientv3.ModRevision(s.bindingKey(state.publishedPrefix, state.published.record.Object.Metadata.Name)), "=", state.publishedRevision))
+ }
+ if markerExists {
+ comparisons = append(comparisons,
+ clientv3.Compare(clientv3.ModRevision(s.publishedRevisionKey()), "=", markerRevision))
+ } else {
+ comparisons = append(comparisons,
+ clientv3.Compare(clientv3.CreateRevision(s.publishedRevisionKey()), "=", 0))
+ }
+ return comparisons
+}
+
+func (s *RouteBindingStore) buildSinglePublishOperations(state routeBindingPublishState, candidate *compiledRouteEntry) ([]clientv3.Op, int, int, error) {
+ if candidate == nil {
+ operations := s.runtimeResourceDeleteOperations(state.published.record.ResourceID)
+ operations = append(operations, clientv3.OpDelete(s.bindingKey(state.publishedPrefix, state.published.record.Object.Metadata.Name)))
+ return operations, 0, 1, nil
+ }
+ compiled := candidate.legacy
+ operations := make([]clientv3.Op, 0, 4)
+ if state.publishedExists && state.published.record.ResourceID != compiled.Resource.ID {
+ operations = append(operations, s.runtimeResourceDeleteOperations(state.published.record.ResourceID)...)
+ } else if state.publishedExists && state.published.record.MethodID != compiled.Method.ID {
+ operations = append(operations,
+ clientv3.OpDelete(s.runtimeMethodKey(state.published.record.ResourceID, state.published.record.MethodID)))
+ }
+ resourceValue, methodValue, err := marshalCompiledRuntimeRoute(compiled)
+ if err != nil {
+ return nil, 0, 0, fmt.Errorf("encode route binding %q for runtime: %w", candidate.object.Metadata.Name, err)
+ }
+ recordValue, err := json.Marshal(routeBindingRecord{
+ Object: candidate.object,
+ ResourceID: compiled.Resource.ID,
+ MethodID: compiled.Method.ID,
+ })
+ if err != nil {
+ return nil, 0, 0, fmt.Errorf("encode published route binding %q: %w", candidate.object.Metadata.Name, err)
+ }
+ operations = append(operations,
+ clientv3.OpPut(s.runtimeResourceKey(compiled.Resource.ID), string(resourceValue)),
+ clientv3.OpPut(s.runtimeMethodKey(compiled.Resource.ID, compiled.Method.ID), string(methodValue)),
+ clientv3.OpPut(s.bindingKey(state.publishedPrefix, candidate.object.Metadata.Name), string(recordValue)))
+ return operations, 1, 0, nil
+}
+
+func (s *RouteBindingStore) runtimeResourceDeleteOperations(resourceID int) []clientv3.Op {
+ key := s.runtimeResourceKey(resourceID)
+ return []clientv3.Op{
+ clientv3.OpDelete(key),
+ clientv3.OpDelete(key+"/", clientv3.WithPrefix()),
+ }
+}
+
+func (s *RouteBindingStore) publishedRouteRevision(ctx context.Context, prefix, name string, candidate *compiledRouteEntry) (int64, error) {
+ if candidate == nil {
+ return 0, nil
+ }
+ _, exists, revision, err := s.getEntry(ctx, prefix, name)
+ if err != nil {
+ return 0, err
+ }
+ if !exists {
+ return 0, fmt.Errorf("route binding %q disappeared after publish", name)
+ }
+ return revision, nil
+}
+
+// checkRuntimeRouteConflict protects the breaking migration boundary between
+// the legacy Resource/Method keys and AdminRouteBinding. Existing runtime
+// method keys are still consumed by Pixiu's watcher, even when they are not
+// visible through the new Admin API. Publishing a new route with the same
+// HTTP method and path would otherwise commit successfully and leave the
+// watcher with duplicate runtime routes.
+func (s *RouteBindingStore) checkRuntimeRouteConflict(ctx context.Context, candidate *compiledRouteEntry, state routeBindingPublishState) error {
+ if candidate == nil {
+ return nil
+ }
+ prefix := s.runtimeResourcePrefix()
+ response, err := s.kv.Get(ctx, prefix, clientv3.WithPrefix())
+ if err != nil {
+ return fmt.Errorf("list existing runtime resources and methods: %w", err)
+ }
+ resources, err := runtimeResourcesFromResponse(prefix, response)
+ if err != nil {
+ return err
+ }
+ resourcePaths, runtimeRoutes := indexRuntimeResourceRoutes(resources, len(response.Kvs))
+ methodRoutes, err := runtimeMethodRoutesFromResponse(prefix, response, resourcePaths, state)
+ if err != nil {
+ return err
+ }
+ runtimeRoutes = append(runtimeRoutes, methodRoutes...)
+ return findRuntimeRouteConflict(candidate, runtimeRoutes)
+}
+
+func runtimeResourcesFromResponse(prefix string, response *clientv3.GetResponse) (map[int]legacyconfig.Resource, error) {
+ resources := make(map[int]legacyconfig.Resource)
+ for _, kv := range response.Kvs {
+ resourceID, ok := runtimeResourceID(prefix, string(kv.Key))
+ if !ok {
+ continue
+ }
+ var resource legacyconfig.Resource
+ if err := commonyaml.UnmarshalYML(kv.Value, &resource); err != nil {
+ return nil, fmt.Errorf("decode existing runtime resource %q: %w", string(kv.Key), err)
+ }
+ resources[resourceID] = resource
+ }
+ return resources, nil
+}
+
+func indexRuntimeResourceRoutes(resources map[int]legacyconfig.Resource, capacity int) (map[int]string, []runtimeRouteBinding) {
+ resourcePaths := make(map[int]string)
+ runtimeRoutes := make([]runtimeRouteBinding, 0, capacity)
+ for resourceID, resource := range resources {
+ collectRuntimeResourceRoutes(resource, "", resourceID, resourcePaths, &runtimeRoutes)
+ }
+ return resourcePaths, runtimeRoutes
+}
+
+func runtimeMethodRoutesFromResponse(
+ prefix string,
+ response *clientv3.GetResponse,
+ resourcePaths map[int]string,
+ state routeBindingPublishState,
+) ([]runtimeRouteBinding, error) {
+ routes := make([]runtimeRouteBinding, 0, len(response.Kvs))
+ for _, kv := range response.Kvs {
+ route, ok, err := runtimeMethodRouteFromKV(prefix, string(kv.Key), kv.Value, resourcePaths, state)
+ if err != nil {
+ return nil, err
+ }
+ if ok {
+ routes = append(routes, route)
+ }
+ }
+ return routes, nil
+}
+
+func runtimeMethodRouteFromKV(
+ prefix string,
+ key string,
+ value []byte,
+ resourcePaths map[int]string,
+ state routeBindingPublishState,
+) (runtimeRouteBinding, bool, error) {
+ resourceID, methodID, ok, err := runtimeMethodIDs(prefix, key)
+ if err != nil || !ok {
+ return runtimeRouteBinding{}, false, err
+ }
+ // A republish of the same published AdminRouteBinding owns this runtime
+ // identity; a new route must not bypass the check by reusing orphaned IDs.
+ if state.publishedExists && resourceID == state.published.record.ResourceID && methodID == state.published.record.MethodID {
+ return runtimeRouteBinding{}, false, nil
+ }
+ var method legacyconfig.Method
+ if err := commonyaml.UnmarshalYML(value, &method); err != nil {
+ return runtimeRouteBinding{}, false, fmt.Errorf("decode existing runtime method %q: %w", key, err)
+ }
+ path := strings.TrimSpace(method.ResourcePath)
+ if path == "" {
+ path = resourcePaths[resourceID]
+ }
+ if path == "" {
+ return runtimeRouteBinding{}, false, nil
+ }
+ return runtimeRouteBinding{path: path, httpVerb: method.HTTPVerb, key: key}, true, nil
+}
+
+func findRuntimeRouteConflict(candidate *compiledRouteEntry, runtimeRoutes []runtimeRouteBinding) error {
+ candidatePath := strings.ToLower(candidate.legacy.Resource.Path)
+ candidateVerb := strings.TrimSpace(candidate.legacy.Method.HTTPVerb)
+ for _, route := range runtimeRoutes {
+ if strings.ToLower(route.path) == candidatePath && strings.EqualFold(route.httpVerb, candidateVerb) {
+ return fmt.Errorf("%w: %s %s already exists at %q", ErrRouteBindingRuntimeConflict, candidateVerb, candidate.legacy.Resource.Path, route.key)
+ }
+ }
+ return nil
+}
+
+type runtimeRouteBinding struct {
+ path string
+ httpVerb string
+ key string
+}
+
+func collectRuntimeResourceRoutes(resource legacyconfig.Resource, parentPath string, keyResourceID int, resourcePaths map[int]string, routes *[]runtimeRouteBinding) {
+ groupPath := parentPath
+ if groupPath == "/" {
+ groupPath = ""
+ }
+ if !strings.HasPrefix(resource.Path, "/") {
+ return
+ }
+ fullPath := groupPath + resource.Path
+ if keyResourceID > 0 {
+ resourcePaths[keyResourceID] = fullPath
+ }
+ if resource.ID > 0 {
+ resourcePaths[resource.ID] = fullPath
+ }
+ resourceKey := fmt.Sprintf("resource %d", keyResourceID)
+ for _, method := range resource.Methods {
+ *routes = append(*routes, runtimeRouteBinding{path: fullPath, httpVerb: method.HTTPVerb, key: resourceKey})
+ }
+ for _, nested := range resource.Resources {
+ // Match addAPIFromResource: nested resources are visited with their
+ // parent's declared path, and the router lowercases paths at insertion.
+ collectRuntimeResourceRoutes(nested, resource.Path, nested.ID, resourcePaths, routes)
+ }
+}
+
+// Status returns draft and published revisions for one route. The revisions
+// are independent of other route bindings in the same config namespace.
+func (s *RouteBindingStore) Status(ctx context.Context, name string) (RouteBindingPublishStatus, error) {
+ ctx = routeBindingContext(ctx)
+ name, err := normalizeRouteBindingName(name)
+ if err != nil {
+ return RouteBindingPublishStatus{}, err
+ }
+ draft, draftExists, draftRevision, err := s.getEntry(ctx, s.bindingPrefix(true), name)
+ if err != nil {
+ return RouteBindingPublishStatus{}, err
+ }
+ published, publishedExists, publishedRevision, err := s.getEntry(ctx, s.bindingPrefix(false), name)
+ if err != nil {
+ return RouteBindingPublishStatus{}, err
+ }
+ if !draftExists && !publishedExists {
+ return RouteBindingPublishStatus{}, fmt.Errorf("%w: %s", ErrRouteBindingNotFound, name)
+ }
+ dirty := draftExists != publishedExists
+ if draftExists && publishedExists {
+ dirty = !reflect.DeepEqual(draft.record.Object, published.record.Object)
+ }
+ return RouteBindingPublishStatus{
+ Name: name,
+ DraftRevision: draftRevision,
+ PublishedRevision: publishedRevision,
+ DraftExists: draftExists,
+ PublishedExists: publishedExists,
+ Dirty: dirty,
+ }, nil
+}
+
+// Diff compares one route's draft and published objects. It does not read or
+// mutate any other route's draft state.
+func (s *RouteBindingStore) Diff(ctx context.Context, name string) (RouteBindingDiff, error) {
+ ctx = routeBindingContext(ctx)
+ name, err := normalizeRouteBindingName(name)
+ if err != nil {
+ return RouteBindingDiff{}, err
+ }
+ draft, draftExists, _, err := s.getEntry(ctx, s.bindingPrefix(true), name)
+ if err != nil {
+ return RouteBindingDiff{}, err
+ }
+ published, publishedExists, _, err := s.getEntry(ctx, s.bindingPrefix(false), name)
+ if err != nil {
+ return RouteBindingDiff{}, err
+ }
+ if !draftExists && !publishedExists {
+ return RouteBindingDiff{}, fmt.Errorf("%w: %s", ErrRouteBindingNotFound, name)
+ }
+
+ var draftView, publishedView *RouteBinding
+ if draftExists {
+ view := routeBindingView(draft)
+ draftView = &view
+ }
+ if publishedExists {
+ view := routeBindingView(published)
+ publishedView = &view
+ }
+ changes, err := diffRouteBindingObjects(
+ func() schema.AdminObject {
+ if publishedExists {
+ return published.record.Object
+ }
+ return schema.AdminObject{}
+ }(),
+ func() schema.AdminObject {
+ if draftExists {
+ return draft.record.Object
+ }
+ return schema.AdminObject{}
+ }(),
+ publishedExists,
+ draftExists,
+ )
+ if err != nil {
+ return RouteBindingDiff{}, err
+ }
+ return RouteBindingDiff{
+ Name: name,
+ Draft: draftView,
+ Published: publishedView,
+ Changes: changes,
+ }, nil
+}
+
+func diffRouteBindingObjects(before, after schema.AdminObject, beforeExists, afterExists bool) ([]RouteBindingDiffChange, error) {
+ beforeValues := make(map[string]any)
+ afterValues := make(map[string]any)
+ if beforeExists {
+ if err := flattenRouteBindingValue("", before, beforeValues); err != nil {
+ return nil, err
+ }
+ }
+ if afterExists {
+ if err := flattenRouteBindingValue("", after, afterValues); err != nil {
+ return nil, err
+ }
+ }
+ keys := make(map[string]struct{}, len(beforeValues)+len(afterValues))
+ for key := range beforeValues {
+ keys[key] = struct{}{}
+ }
+ for key := range afterValues {
+ keys[key] = struct{}{}
+ }
+ paths := make([]string, 0, len(keys))
+ for key := range keys {
+ paths = append(paths, key)
+ }
+ sort.Strings(paths)
+ changes := make([]RouteBindingDiffChange, 0, len(paths))
+ for _, path := range paths {
+ beforeValue, beforeOK := beforeValues[path]
+ afterValue, afterOK := afterValues[path]
+ if beforeOK && afterOK && reflect.DeepEqual(beforeValue, afterValue) {
+ continue
+ }
+ changes = append(changes, RouteBindingDiffChange{
+ Path: path,
+ Before: valueOrNil(beforeValue, beforeOK),
+ After: valueOrNil(afterValue, afterOK),
+ })
+ }
+ return changes, nil
+}
+
+func flattenRouteBindingValue(path string, value any, result map[string]any) error {
+ switch typed := value.(type) {
+ case schema.AdminObject:
+ return flattenRouteBindingValue(path, map[string]any{
+ "kind": typed.Kind,
+ "metadata": typed.Metadata,
+ "spec": typed.Spec,
+ }, result)
+ case schema.ObjectMetadata:
+ return flattenRouteBindingValue(path, map[string]any{"name": typed.Name}, result)
+ case map[string]any:
+ if len(typed) == 0 {
+ result[path] = typed
+ return nil
+ }
+ keys := make([]string, 0, len(typed))
+ for key := range typed {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ childPath := key
+ if path != "" {
+ childPath = path + "." + key
+ }
+ if err := flattenRouteBindingValue(childPath, typed[key], result); err != nil {
+ return err
+ }
+ }
+ return nil
+ case []any:
+ if len(typed) == 0 {
+ result[path] = typed
+ return nil
+ }
+ for index, item := range typed {
+ childPath := fmt.Sprintf("%s[%d]", path, index)
+ if err := flattenRouteBindingValue(childPath, item, result); err != nil {
+ return err
+ }
+ }
+ return nil
+ default:
+ result[path] = typed
+ return nil
+ }
+}
+
+func valueOrNil(value any, exists bool) any {
+ if !exists {
+ return nil
+ }
+ return value
+}
+
+type compiledRouteEntry struct {
+ entry routeBindingEntry
+ object schema.AdminObject
+ legacy schema.CompiledRoute
+}
+
+func (s *RouteBindingStore) compileSnapshot(entries []routeBindingEntry) ([]compiledRouteEntry, error) {
+ result := make([]compiledRouteEntry, 0, len(entries))
+ paths := make(map[string]string, len(entries))
+ resourceIDs := make(map[int]string, len(entries))
+ for _, entry := range entries {
+ if entry.record.ResourceID <= 0 || entry.record.MethodID <= 0 {
+ return nil, fmt.Errorf("route binding %q has invalid runtime identity", entry.record.Object.Metadata.Name)
+ }
+ normalized, err := s.Normalize(entry.record.Object)
+ if err != nil {
+ return nil, fmt.Errorf("route binding %q: %w", entry.record.Object.Metadata.Name, err)
+ }
+ legacy, err := schema.CompileAdminRouteBinding(s.registry, normalized)
+ if err != nil {
+ return nil, fmt.Errorf("route binding %q: %w", entry.record.Object.Metadata.Name, err)
+ }
+ legacy.Resource.ID = entry.record.ResourceID
+ legacy.Method.ID = entry.record.MethodID
+ routeKey := legacy.Resource.Path + "\x00" + legacy.Method.HTTPVerb
+ if previous, exists := paths[routeKey]; exists {
+ return nil, fmt.Errorf("route binding %q conflicts with route binding %q for %s %s", entry.record.Object.Metadata.Name, previous, legacy.Method.HTTPVerb, legacy.Resource.Path)
+ }
+ if previous, exists := resourceIDs[legacy.Resource.ID]; exists && previous != entry.record.Object.Metadata.Name {
+ return nil, fmt.Errorf("route binding %q reuses runtime resource id %d from %q", entry.record.Object.Metadata.Name, legacy.Resource.ID, previous)
+ }
+ paths[routeKey] = entry.record.Object.Metadata.Name
+ resourceIDs[legacy.Resource.ID] = entry.record.Object.Metadata.Name
+ result = append(result, compiledRouteEntry{entry: entry, object: normalized, legacy: legacy})
+ }
+ return result, nil
+}
+
+func marshalCompiledRuntimeRoute(compiled schema.CompiledRoute) ([]byte, []byte, error) {
+ resource := routeBindingResourceYAML{
+ ID: compiled.Resource.ID,
+ Type: compiled.Resource.Type,
+ Path: compiled.Resource.Path,
+ Timeout: compiled.Resource.Timeout.String(),
+ }
+ method := routeBindingMethodYAML{
+ ID: compiled.Method.ID,
+ ResourcePath: compiled.Method.ResourcePath,
+ Enable: compiled.Method.Enable,
+ Timeout: compiled.Method.Timeout.String(),
+ Mock: compiled.Method.Mock,
+ Filters: compiled.Method.Filters,
+ HTTPVerb: compiled.Method.HTTPVerb,
+ InboundRequest: compiled.Method.InboundRequest,
+ IntegrationRequest: routeBindingIntegrationRequestYAMLFrom(compiled.Method.IntegrationRequest),
+ }
+ resourceValue, err := commonyaml.MarshalYML(resource)
+ if err != nil {
+ return nil, nil, err
+ }
+ methodValue, err := commonyaml.MarshalYML(method)
+ if err != nil {
+ return nil, nil, err
+ }
+ return resourceValue, methodValue, nil
+}
+
+type routeBindingResourceYAML struct {
+ ID int `yaml:"id,omitempty"`
+ Type string `yaml:"type"`
+ Path string `yaml:"path"`
+ Timeout string `yaml:"timeout"`
+}
+
+type routeBindingMethodYAML struct {
+ ID int `yaml:"id,omitempty"`
+ ResourcePath string `yaml:"resourcePath"`
+ Enable bool `yaml:"enable"`
+ Timeout string `yaml:"timeout"`
+ Mock bool `yaml:"mock"`
+ Filters []legacyconfig.Filter `yaml:"filters,omitempty"`
+ HTTPVerb string `yaml:"httpVerb"`
+ InboundRequest legacyconfig.InboundRequest `yaml:"inboundRequest"`
+ IntegrationRequest routeBindingIntegrationRequestYAML `yaml:"integrationRequest"`
+}
+
+type routeBindingIntegrationRequestYAML struct {
+ RequestType string `yaml:"requestType"`
+ ClusterName string `yaml:"clusterName"`
+ ApplicationName string `yaml:"applicationName"`
+ Protocol string `yaml:"protocol,omitempty"`
+ Group string `yaml:"group,omitempty"`
+ Version string `yaml:"version,omitempty"`
+ Interface string `yaml:"interface"`
+ Method string `yaml:"method"`
+ ParameterTypes []string `yaml:"parameterTypes,omitempty"`
+ Serialization string `yaml:"serialization,omitempty"`
+ Retries string `yaml:"retries,omitempty"`
+ MappingParams []legacyconfig.MappingParam `yaml:"mappingParams,omitempty"`
+}
+
+func routeBindingIntegrationRequestYAMLFrom(request legacyconfig.IntegrationRequest) routeBindingIntegrationRequestYAML {
+ return routeBindingIntegrationRequestYAML{
+ RequestType: request.RequestType,
+ ClusterName: request.ClusterName,
+ ApplicationName: request.ApplicationName,
+ Protocol: request.Protocol,
+ Group: request.Group,
+ Version: request.Version,
+ Interface: request.Interface,
+ Method: request.Method,
+ ParameterTypes: append([]string(nil), request.ParameterTypes...),
+ Serialization: request.Serialization,
+ Retries: request.Retries,
+ MappingParams: append([]legacyconfig.MappingParam(nil), request.MappingParams...),
+ }
+}
+
+func (s *RouteBindingStore) listEntries(ctx context.Context, prefix string) ([]routeBindingEntry, error) {
+ response, err := s.kv.Get(ctx, prefix, clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend))
+ if err != nil {
+ return nil, fmt.Errorf("list route bindings under %q: %w", prefix, err)
+ }
+ entries := make([]routeBindingEntry, 0, len(response.Kvs))
+ for _, kv := range response.Kvs {
+ name, err := routeBindingNameFromKey(prefix, string(kv.Key))
+ if err != nil {
+ return nil, err
+ }
+ var record routeBindingRecord
+ if err := json.Unmarshal(kv.Value, &record); err != nil {
+ return nil, fmt.Errorf("decode route binding %q: %w", name, err)
+ }
+ if record.Object.Metadata.Name != name {
+ return nil, fmt.Errorf("route binding key %q does not match metadata.name %q", name, record.Object.Metadata.Name)
+ }
+ entries = append(entries, routeBindingEntry{record: record, key: string(kv.Key), revision: kv.ModRevision})
+ }
+ return entries, nil
+}
+
+func (s *RouteBindingStore) getEntry(ctx context.Context, prefix, name string) (routeBindingEntry, bool, int64, error) {
+ key := s.bindingKey(prefix, name)
+ response, err := s.kv.Get(ctx, key)
+ if err != nil {
+ return routeBindingEntry{}, false, 0, fmt.Errorf("get route binding %q: %w", name, err)
+ }
+ if len(response.Kvs) == 0 {
+ return routeBindingEntry{}, false, 0, nil
+ }
+ var record routeBindingRecord
+ if err := json.Unmarshal(response.Kvs[0].Value, &record); err != nil {
+ return routeBindingEntry{}, false, 0, fmt.Errorf("decode route binding %q: %w", name, err)
+ }
+ if record.Object.Metadata.Name != name {
+ return routeBindingEntry{}, false, 0, fmt.Errorf("route binding key %q does not match metadata.name %q", name, record.Object.Metadata.Name)
+ }
+ entry := routeBindingEntry{record: record, key: key, revision: response.Kvs[0].ModRevision}
+ return entry, true, entry.revision, nil
+}
+
+// markerRevision reads the internal published generation used to protect a
+// single-route publish from publishing against a stale published snapshot.
+// It is intentionally not exposed as a global publish status API.
+func (s *RouteBindingStore) markerRevision(ctx context.Context, key string) (int64, bool, error) {
+ response, err := s.kv.Get(ctx, key)
+ if err != nil {
+ return 0, false, fmt.Errorf("get route binding revision marker %q: %w", key, err)
+ }
+ if len(response.Kvs) == 0 {
+ return 0, false, nil
+ }
+ return response.Kvs[0].ModRevision, true, nil
+}
+
+type routeBindingIDCounter struct {
+ value int
+ revision int64
+}
+
+func (s *RouteBindingStore) allocateRuntimeID(ctx context.Context) (int, error) {
+ counterKey := s.root + "/" + ResourceID
+ resourcePrefix := s.root + "/" + routeBindingRuntimeResourceDir + "/"
+ for attempt := 0; attempt < maxRouteBindingIDRetries; attempt++ {
+ id, allocated, err := s.tryAllocateRuntimeID(ctx, counterKey, resourcePrefix)
+ if err != nil {
+ return 0, err
+ }
+ if allocated {
+ return id, nil
+ }
+ }
+ return 0, fmt.Errorf("%w: resource id allocation retries exhausted", ErrRouteBindingConflict)
+}
+
+func (s *RouteBindingStore) tryAllocateRuntimeID(ctx context.Context, counterKey, resourcePrefix string) (int, bool, error) {
+ counter, err := s.readRuntimeIDCounter(ctx, counterKey)
+ if err != nil {
+ return 0, false, err
+ }
+ resourceResponse, err := s.kv.Get(ctx, resourcePrefix, clientv3.WithPrefix())
+ if err != nil {
+ return 0, false, fmt.Errorf("scan route binding resource ids: %w", err)
+ }
+ next := maxRuntimeResourceID(resourceResponse, resourcePrefix, counter.value) + 1
+ comparison := clientv3.Compare(clientv3.CreateRevision(counterKey), "=", 0)
+ if counter.revision > 0 {
+ comparison = clientv3.Compare(clientv3.ModRevision(counterKey), "=", counter.revision)
+ }
+ response, err := s.kv.Txn(ctx).
+ If(comparison).
+ Then(clientv3.OpPut(counterKey, strconv.Itoa(next))).
+ Commit()
+ if err != nil {
+ return 0, false, fmt.Errorf("allocate route binding resource id: %w", err)
+ }
+ return next, response.Succeeded, nil
+}
+
+func (s *RouteBindingStore) readRuntimeIDCounter(ctx context.Context, counterKey string) (routeBindingIDCounter, error) {
+ response, err := s.kv.Get(ctx, counterKey)
+ if err != nil {
+ return routeBindingIDCounter{}, fmt.Errorf("read route binding resource id counter: %w", err)
+ }
+ counter := routeBindingIDCounter{}
+ if len(response.Kvs) == 0 {
+ return counter, nil
+ }
+ value := string(response.Kvs[0].Value)
+ current, err := strconv.Atoi(value)
+ if err != nil || current < 0 {
+ return routeBindingIDCounter{}, fmt.Errorf("invalid resource id counter %q", value)
+ }
+ counter.value = current
+ counter.revision = response.Kvs[0].ModRevision
+ return counter, nil
+}
+
+func maxRuntimeResourceID(response *clientv3.GetResponse, resourcePrefix string, current int) int {
+ maxExisting := current
+ for _, kv := range response.Kvs {
+ relative := strings.TrimPrefix(string(kv.Key), resourcePrefix)
+ if strings.Contains(relative, "/") {
+ continue
+ }
+ id, parseErr := strconv.Atoi(relative)
+ if parseErr == nil && id > maxExisting {
+ maxExisting = id
+ }
+ }
+ return maxExisting
+}
+
+func routeBindingView(entry routeBindingEntry) RouteBinding {
+ return RouteBinding{
+ Object: entry.record.Object.Clone(),
+ ResourceID: entry.record.ResourceID,
+ MethodID: entry.record.MethodID,
+ Revision: entry.revision,
+ }
+}
+
+func normalizeRouteBindingName(name string) (string, error) {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return "", errors.New("route binding metadata.name is required")
+ }
+ if name == "." || name == ".." || strings.ContainsAny(name, `/\\`) {
+ return "", fmt.Errorf("route binding metadata.name %q is not a safe key", name)
+ }
+ if len(name) > 128 {
+ return "", errors.New("route binding metadata.name must be at most 128 characters")
+ }
+ return name, nil
+}
+
+func routeBindingNameFromKey(prefix, key string) (string, error) {
+ if !strings.HasPrefix(key, prefix) {
+ return "", fmt.Errorf("route binding key %q is outside prefix %q", key, prefix)
+ }
+ encodedName := strings.TrimPrefix(key, prefix)
+ if encodedName == "" || strings.Contains(encodedName, "/") {
+ return "", fmt.Errorf("route binding key %q is not a direct binding key", key)
+ }
+ name, err := url.PathUnescape(encodedName)
+ if err != nil {
+ return "", fmt.Errorf("decode route binding key %q: %w", key, err)
+ }
+ return normalizeRouteBindingName(name)
+}
+
+func (s *RouteBindingStore) bindingPrefix(unpublished bool) string {
+ if unpublished {
+ return s.root + "/" + Unpublished + "/" + routeBindingPathSegment + "/"
+ }
+ return s.root + "/" + routeBindingPathSegment + "/"
+}
+
+func (s *RouteBindingStore) bindingKey(prefix, name string) string {
+ return prefix + url.PathEscape(name)
+}
+
+func (s *RouteBindingStore) publishedRevisionKey() string {
+ return s.root + "/" + routeBindingRevisionSegment
+}
+
+func (s *RouteBindingStore) runtimeResourceKey(resourceID int) string {
+ return s.root + "/" + routeBindingRuntimeResourceDir + "/" + strconv.Itoa(resourceID)
+}
+
+func (s *RouteBindingStore) runtimeResourcePrefix() string {
+ return s.root + "/" + routeBindingRuntimeResourceDir + "/"
+}
+
+func (s *RouteBindingStore) runtimeMethodKey(resourceID, methodID int) string {
+ return s.runtimeResourceKey(resourceID) + "/" + Method + "/" + strconv.Itoa(methodID)
+}
+
+func runtimeResourceID(prefix, key string) (int, bool) {
+ if !strings.HasPrefix(key, prefix) {
+ return 0, false
+ }
+ relative := strings.Trim(strings.TrimPrefix(key, prefix), "/")
+ if relative == "" || strings.Contains(relative, "/") {
+ return 0, false
+ }
+ resourceID, err := strconv.Atoi(relative)
+ if err != nil {
+ return 0, false
+ }
+ return resourceID, true
+}
+
+func runtimeMethodIDs(prefix, key string) (int, int, bool, error) {
+ if !strings.HasPrefix(key, prefix) {
+ return 0, 0, false, nil
+ }
+ parts := strings.Split(strings.Trim(strings.TrimPrefix(key, prefix), "/"), "/")
+ if len(parts) != 3 || parts[1] != Method {
+ return 0, 0, false, nil
+ }
+ resourceID, err := strconv.Atoi(parts[0])
+ if err != nil {
+ return 0, 0, true, fmt.Errorf("invalid runtime resource key %q: %w", key, err)
+ }
+ methodID, err := strconv.Atoi(parts[2])
+ if err != nil {
+ return 0, 0, true, fmt.Errorf("invalid runtime method key %q: %w", key, err)
+ }
+ return resourceID, methodID, true, nil
+}
diff --git a/admin/logic/route_binding_test.go b/admin/logic/route_binding_test.go
new file mode 100644
index 000000000..6098fd8cb
--- /dev/null
+++ b/admin/logic/route_binding_test.go
@@ -0,0 +1,790 @@
+/*
+ * 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 (
+ "context"
+ "errors"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+import (
+ pb "go.etcd.io/etcd/api/v3/etcdserverpb"
+ "go.etcd.io/etcd/api/v3/mvccpb"
+
+ clientv3 "go.etcd.io/etcd/client/v3"
+)
+
+import (
+ commonyaml "github.com/apache/dubbo-go-pixiu/pkg/common/yaml"
+ legacyconfig "github.com/apache/dubbo-go-pixiu/pkg/config"
+ "github.com/apache/dubbo-go-pixiu/pkg/config/schema"
+)
+
+func TestRouteBindingStoreSavePublishAndDelete(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved := saveAndPublishTestRoute(t, store)
+ assertPublishedRuntimeRoute(t, store, saved)
+ assertPublishedTestRoute(t, store)
+ deleteAndAssertTestRoute(t, store, saved)
+}
+
+func TestRouteBindingStoreDeleteDraftAndPublishRemovesDraftOnly(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("draft-only", "/api/draft-only", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+ result, err := store.DeleteAndPublish(context.Background(), "draft-only", saved.Revision)
+ if err != nil {
+ t.Fatalf("DeleteAndPublish: %v", err)
+ }
+ if result.PublishedCount != 0 || result.DeletedCount != 0 {
+ t.Fatalf("draft-only delete result: %+v", result)
+ }
+ if _, err := store.Get(context.Background(), "draft-only", true); err == nil {
+ t.Fatal("draft-only binding still exists in draft namespace")
+ }
+ if _, err := store.Get(context.Background(), "draft-only", false); err == nil {
+ t.Fatal("draft-only binding was published during delete")
+ }
+ if fakeRouteBindingStoreKV(t, store).fakeHasKey(store.runtimeResourceKey(saved.ResourceID)) {
+ t.Fatal("draft-only delete created a runtime resource")
+ }
+}
+
+func TestRouteBindingStoreDeleteKeepsNeighboringResourceIDs(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved := saveAndPublishTestRoute(t, store)
+ fake := fakeRouteBindingStoreKV(t, store)
+ neighborResource := store.runtimeResourceKey(10)
+ neighborMethod := store.runtimeMethodKey(10, 10)
+ fake.fakePut(neighborResource, []byte("neighbor resource"))
+ fake.fakePut(neighborMethod, []byte("neighbor method"))
+
+ if _, err := store.DeleteAndPublish(context.Background(), saved.Object.Metadata.Name, saved.Revision); err != nil {
+ t.Fatalf("DeleteAndPublish: %v", err)
+ }
+ if !fake.fakeHasKey(neighborResource) || !fake.fakeHasKey(neighborMethod) {
+ t.Fatal("deleting resource 1 also removed resource 10")
+ }
+}
+
+func TestRouteBindingStoreListIncludesPublishStatus(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("status-route", "/api/status", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+
+ drafts, err := store.List(context.Background(), true)
+ if err != nil {
+ t.Fatalf("List drafts: %v", err)
+ }
+ if len(drafts) != 1 || drafts[0].PublishStatus == nil {
+ t.Fatalf("draft list status: %+v", drafts)
+ }
+ if !drafts[0].PublishStatus.DraftExists || drafts[0].PublishStatus.PublishedExists || !drafts[0].PublishStatus.Dirty {
+ t.Fatalf("draft publish status: %+v", drafts[0].PublishStatus)
+ }
+
+ if _, err := store.Publish(context.Background(), saved.Object.Metadata.Name, saved.Revision); err != nil {
+ t.Fatalf("Publish: %v", err)
+ }
+ drafts, err = store.List(context.Background(), true)
+ if err != nil {
+ t.Fatalf("List drafts after publish: %v", err)
+ }
+ status := drafts[0].PublishStatus
+ if status == nil || !status.DraftExists || !status.PublishedExists || status.Dirty {
+ t.Fatalf("published route status: %+v", status)
+ }
+}
+
+func saveAndPublishTestRoute(t *testing.T, store *RouteBindingStore) RouteBinding {
+ t.Helper()
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("user-get", "/api/users/:id", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+ if saved.ResourceID != 1 || saved.MethodID != 1 {
+ t.Fatalf("runtime identity: want 1/1, got %d/%d", saved.ResourceID, saved.MethodID)
+ }
+ if saved.Revision == 0 {
+ t.Fatal("SaveDraft returned zero key revision")
+ }
+
+ result, err := store.Publish(context.Background(), saved.Object.Metadata.Name, saved.Revision)
+ if err != nil {
+ t.Fatalf("Publish: %v", err)
+ }
+ if result.PublishedCount != 1 || result.DeletedCount != 0 {
+ t.Fatalf("publish result: %+v", result)
+ }
+ if result.Revision == 0 || result.DraftRevision != saved.Revision {
+ t.Fatalf("publish revisions: %+v, saved=%+v", result, saved)
+ }
+ return saved
+}
+
+func assertPublishedRuntimeRoute(t *testing.T, store *RouteBindingStore, saved RouteBinding) {
+ t.Helper()
+ fake := fakeRouteBindingStoreKV(t, store)
+ resourceValue := fake.fakeValue(store.runtimeResourceKey(saved.ResourceID))
+ methodValue := fake.fakeValue(store.runtimeMethodKey(saved.ResourceID, saved.MethodID))
+ var resource legacyconfig.Resource
+ if err := commonyaml.UnmarshalYML(resourceValue, &resource); err != nil {
+ t.Fatalf("decode generated Resource: %v\n%s", err, resourceValue)
+ }
+ var method legacyconfig.Method
+ if err := commonyaml.UnmarshalYML(methodValue, &method); err != nil {
+ t.Fatalf("decode generated Method: %v\n%s", err, methodValue)
+ }
+ if resource.ID != saved.ResourceID || resource.Path != "/api/users/:id" || resource.Timeout != time.Second {
+ t.Fatalf("generated resource: %+v", resource)
+ }
+ if method.ID != saved.MethodID || method.ResourcePath != resource.Path || method.HTTPVerb != "GET" || method.Timeout != time.Second {
+ t.Fatalf("generated method: %+v", method)
+ }
+ if method.IntegrationRequest.Interface != "com.example.UserService" || method.IntegrationRequest.Method != "GetUser" {
+ t.Fatalf("generated integration request: %+v", method.IntegrationRequest)
+ }
+}
+
+func assertPublishedTestRoute(t *testing.T, store *RouteBindingStore) {
+ t.Helper()
+ published, err := store.List(context.Background(), false)
+ if err != nil {
+ t.Fatalf("List published: %v", err)
+ }
+ if len(published) != 1 || published[0].Object.Metadata.Name != "user-get" {
+ t.Fatalf("published bindings: %+v", published)
+ }
+}
+
+func deleteAndAssertTestRoute(t *testing.T, store *RouteBindingStore, saved RouteBinding) {
+ t.Helper()
+ result, err := store.DeleteAndPublish(context.Background(), "user-get", saved.Revision)
+ if err != nil {
+ t.Fatalf("DeleteAndPublish: %v", err)
+ }
+ if result.PublishedCount != 0 || result.DeletedCount != 1 {
+ t.Fatalf("delete publish result: %+v", result)
+ }
+ fake := fakeRouteBindingStoreKV(t, store)
+ if fake.fakeHasKey(store.runtimeResourceKey(saved.ResourceID)) || fake.fakeHasKey(store.runtimeMethodKey(saved.ResourceID, saved.MethodID)) {
+ t.Fatal("published runtime keys remain after atomic deletion")
+ }
+ if _, err := store.Get(context.Background(), "user-get", false); err == nil {
+ t.Fatal("deleted binding still exists in published namespace")
+ }
+}
+
+func TestRouteBindingStorePublishOneKeepsOtherRoutesDraft(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ first, err := store.SaveDraft(context.Background(), testRouteBinding("user-get", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("first SaveDraft: %v", err)
+ }
+ second, err := store.SaveDraft(context.Background(), testRouteBinding("order-get", "/api/orders", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("second SaveDraft: %v", err)
+ }
+
+ result, err := store.Publish(context.Background(), "user-get", first.Revision)
+ if err != nil {
+ t.Fatalf("Publish one route: %v", err)
+ }
+ if result.Name != "user-get" || result.PublishedCount != 1 || result.DeletedCount != 0 {
+ t.Fatalf("single-route publish result: %+v", result)
+ }
+ if _, err := store.Get(context.Background(), "order-get", false); err == nil {
+ t.Fatal("publishing user-get unexpectedly published order-get")
+ }
+ if _, err := store.Get(context.Background(), "order-get", true); err != nil {
+ t.Fatalf("order-get draft disappeared: %v", err)
+ }
+
+ status, err := store.Status(context.Background(), "user-get")
+ if err != nil {
+ t.Fatalf("user-get Status: %v", err)
+ }
+ if !status.DraftExists || !status.PublishedExists || status.Dirty {
+ t.Fatalf("user-get status: %+v", status)
+ }
+ status, err = store.Status(context.Background(), "order-get")
+ if err != nil {
+ t.Fatalf("order-get Status: %v", err)
+ }
+ if !status.DraftExists || status.PublishedExists || !status.Dirty {
+ t.Fatalf("order-get status: %+v", status)
+ }
+
+ diff, err := store.Diff(context.Background(), "order-get")
+ if err != nil {
+ t.Fatalf("order-get Diff: %v", err)
+ }
+ if diff.Published != nil || len(diff.Changes) == 0 {
+ t.Fatalf("order-get diff: %+v", diff)
+ }
+
+ result, err = store.Publish(context.Background(), "order-get", second.Revision)
+ if err != nil {
+ t.Fatalf("Publish second route: %v", err)
+ }
+ if result.Name != "order-get" || result.PublishedCount != 1 {
+ t.Fatalf("second single-route publish result: %+v", result)
+ }
+ published, err := store.List(context.Background(), false)
+ if err != nil {
+ t.Fatalf("List published: %v", err)
+ }
+ if len(published) != 2 {
+ t.Fatalf("published route count: got %d, want 2", len(published))
+ }
+}
+
+func TestRouteBindingStorePublishesDisabledRuntimeMethod(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ object := testRouteBinding("user-disabled", "/api/users/disabled", "GET")
+ object.Spec["enabled"] = false
+
+ saved, err := store.SaveDraft(context.Background(), object, true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+ if _, err := store.Publish(context.Background(), "user-disabled", saved.Revision); err != nil {
+ t.Fatalf("Publish: %v", err)
+ }
+
+ fake := fakeRouteBindingStoreKV(t, store)
+ var method legacyconfig.Method
+ if err := commonyaml.UnmarshalYML(fake.fakeValue(store.runtimeMethodKey(saved.ResourceID, saved.MethodID)), &method); err != nil {
+ t.Fatalf("decode generated Method: %v", err)
+ }
+ if method.Enable {
+ t.Fatal("disabled route was published with enable=true")
+ }
+
+ published, err := store.Get(context.Background(), "user-disabled", false)
+ if err != nil {
+ t.Fatalf("Get published route: %v", err)
+ }
+ if published.Object.Spec["enabled"] != false {
+ t.Fatalf("published enabled state: %+v", published.Object.Spec["enabled"])
+ }
+}
+
+func TestRouteBindingStorePublishRejectsConcurrentDraftChange(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("user-get", "/api/users/:id", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("initial SaveDraft: %v", err)
+ }
+ changed := testRouteBinding("user-get", "/api/users/:id", "GET")
+ changed.Spec["target"].(map[string]any)["method"] = "GetUserByID"
+ if _, err := store.SaveDraft(context.Background(), changed, false, saved.Revision); err != nil {
+ t.Fatalf("concurrent SaveDraft: %v", err)
+ }
+ _, publishErr := store.Publish(context.Background(), "user-get", saved.Revision)
+ if publishErr == nil || !strings.Contains(publishErr.Error(), ErrRouteBindingPublishConflict.Error()) {
+ t.Fatalf("stale publish error: want %q, got %v", ErrRouteBindingPublishConflict, publishErr)
+ }
+ if fakeRouteBindingStoreKV(t, store).fakeHasKey(store.runtimeResourceKey(saved.ResourceID)) {
+ t.Fatal("stale publish changed runtime keys")
+ }
+ if _, err := store.Get(context.Background(), "user-get", false); err == nil {
+ t.Fatal("stale publish wrote a published binding")
+ }
+}
+
+func TestRouteBindingStorePublishRejectsConcurrentRouteConflict(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ first, err := store.SaveDraft(context.Background(), testRouteBinding("user-get-a", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("first SaveDraft: %v", err)
+ }
+ second, err := store.SaveDraft(context.Background(), testRouteBinding("user-get-b", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("second SaveDraft: %v", err)
+ }
+
+ var concurrentErr error
+ fired := false
+ firstStore := *store
+ firstStore.kv = &hookedRouteBindingKV{
+ routeBindingKV: store.kv,
+ afterGet: func(key string) {
+ if fired || key != store.runtimeResourcePrefix() {
+ return
+ }
+ fired = true
+ _, concurrentErr = store.Publish(context.Background(), second.Object.Metadata.Name, second.Revision)
+ },
+ }
+
+ _, err = firstStore.Publish(context.Background(), first.Object.Metadata.Name, first.Revision)
+ if concurrentErr != nil {
+ t.Fatalf("concurrent Publish: %v", concurrentErr)
+ }
+ if !fired {
+ t.Fatal("concurrent publish hook was not reached")
+ }
+ if !errors.Is(err, ErrRouteBindingPublishConflict) {
+ t.Fatalf("stale publish: want %v, got %v", ErrRouteBindingPublishConflict, err)
+ }
+ if _, err := store.Get(context.Background(), first.Object.Metadata.Name, false); !errors.Is(err, ErrRouteBindingNotFound) {
+ t.Fatalf("first route was published after conflict: %v", err)
+ }
+}
+
+func TestRouteBindingStoreUpdateRejectsNameChange(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("user-get", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("initial SaveDraft: %v", err)
+ }
+
+ if _, err := store.UpdateDraft(context.Background(), "user-get", testRouteBinding("renamed", "/api/users", "GET"), saved.Revision); !errors.Is(err, ErrRouteBindingNameImmutable) {
+ t.Fatalf("rename error: want %v, got %v", ErrRouteBindingNameImmutable, err)
+ }
+ if _, err := store.Get(context.Background(), "user-get", true); err != nil {
+ t.Fatalf("original route after rejected rename: %v", err)
+ }
+ if _, err := store.Get(context.Background(), "renamed", true); !errors.Is(err, ErrRouteBindingNotFound) {
+ t.Fatalf("renamed route after rejected rename: want %v, got %v", ErrRouteBindingNotFound, err)
+ }
+
+ updated := testRouteBinding("user-get", "/api/users/:id", "GET")
+ updatedBinding, err := store.UpdateDraft(context.Background(), "user-get", updated, saved.Revision)
+ if err != nil {
+ t.Fatalf("same-name UpdateDraft: %v", err)
+ }
+ if updatedBinding.Object.Spec["entry"].(map[string]any)["path"] != "/api/users/:id" {
+ t.Fatalf("same-name update was not saved: %+v", updatedBinding.Object)
+ }
+}
+
+func TestRouteBindingStoreRejectsDuplicatePublishedRoute(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ if _, err := store.SaveDraft(context.Background(), testRouteBinding("user-get-a", "/api/users", "GET"), true, 0); err != nil {
+ t.Fatalf("first SaveDraft: %v", err)
+ }
+ if _, err := store.SaveDraft(context.Background(), testRouteBinding("user-get-b", "/api/users", "GET"), true, 0); err != nil {
+ t.Fatalf("second SaveDraft: %v", err)
+ }
+ first, err := store.Get(context.Background(), "user-get-a", true)
+ if err != nil {
+ t.Fatalf("get first draft: %v", err)
+ }
+ if _, err := store.Publish(context.Background(), "user-get-a", first.Revision); err != nil {
+ t.Fatalf("publish first route: %v", err)
+ }
+ second, err := store.Get(context.Background(), "user-get-b", true)
+ if err != nil {
+ t.Fatalf("get second draft: %v", err)
+ }
+ if _, err := store.Publish(context.Background(), "user-get-b", second.Revision); err == nil || !strings.Contains(err.Error(), "conflicts") {
+ t.Fatalf("duplicate publish error: %v", err)
+ }
+ fake := fakeRouteBindingStoreKV(t, store)
+ if !fake.fakeHasKey(store.bindingKey(store.bindingPrefix(false), "user-get-a")) || fake.fakeHasKey(store.bindingKey(store.bindingPrefix(false), "user-get-b")) {
+ t.Fatal("duplicate publish changed the published route set")
+ }
+ if fake.fakeHasKey(store.runtimeResourceKey(second.ResourceID)) {
+ t.Fatal("duplicate publish wrote a partial runtime route")
+ }
+}
+
+func TestRouteBindingStoreRejectsExistingRuntimeRoute(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ fake := fakeRouteBindingStoreKV(t, store)
+ legacyMethod, err := commonyaml.MarshalYML(legacyconfig.Method{
+ ID: 7,
+ ResourcePath: "/api/users",
+ HTTPVerb: "GET",
+ })
+ if err != nil {
+ t.Fatalf("marshal legacy Method: %v", err)
+ }
+ fake.fakePut(store.runtimeMethodKey(99, 7)+"/", legacyMethod)
+
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("new-user-get", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+ if _, err := store.Publish(context.Background(), saved.Object.Metadata.Name, saved.Revision); !errors.Is(err, ErrRouteBindingRuntimeConflict) {
+ t.Fatalf("runtime conflict: want %v, got %v", ErrRouteBindingRuntimeConflict, err)
+ }
+ if fake.fakeHasKey(store.bindingKey(store.bindingPrefix(false), saved.Object.Metadata.Name)) {
+ t.Fatal("runtime conflict wrote a published binding")
+ }
+ if fake.fakeHasKey(store.runtimeResourceKey(saved.ResourceID)) {
+ t.Fatal("runtime conflict wrote a generated resource")
+ }
+}
+
+func TestRouteBindingStoreRejectsNestedRuntimeRouteWithoutMethodPath(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ fake := fakeRouteBindingStoreKV(t, store)
+ legacyResource, err := commonyaml.MarshalYML(legacyconfig.Resource{
+ ID: 99,
+ Path: "/api",
+ Resources: []legacyconfig.Resource{{
+ ID: 100,
+ Path: "/users",
+ }},
+ })
+ if err != nil {
+ t.Fatalf("marshal legacy Resource: %v", err)
+ }
+ legacyMethod, err := commonyaml.MarshalYML(legacyconfig.Method{
+ ID: 7,
+ HTTPVerb: "GET",
+ })
+ if err != nil {
+ t.Fatalf("marshal legacy Method: %v", err)
+ }
+ fake.fakePut(store.runtimeResourceKey(99), legacyResource)
+ fake.fakePut(store.runtimeMethodKey(100, 7), legacyMethod)
+
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("nested-user-get", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+ if _, err := store.Publish(context.Background(), saved.Object.Metadata.Name, saved.Revision); !errors.Is(err, ErrRouteBindingRuntimeConflict) {
+ t.Fatalf("nested runtime conflict: want %v, got %v", ErrRouteBindingRuntimeConflict, err)
+ }
+}
+
+func TestRouteBindingStoreRejectsCaseInsensitiveRuntimeRoute(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ fake := fakeRouteBindingStoreKV(t, store)
+ legacyMethod, err := commonyaml.MarshalYML(legacyconfig.Method{
+ ID: 7,
+ ResourcePath: "/API/USERS",
+ HTTPVerb: "get",
+ })
+ if err != nil {
+ t.Fatalf("marshal legacy Method: %v", err)
+ }
+ fake.fakePut(store.runtimeMethodKey(99, 7), legacyMethod)
+
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("case-insensitive-user-get", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+ if _, err := store.Publish(context.Background(), saved.Object.Metadata.Name, saved.Revision); !errors.Is(err, ErrRouteBindingRuntimeConflict) {
+ t.Fatalf("case-insensitive runtime conflict: want %v, got %v", ErrRouteBindingRuntimeConflict, err)
+ }
+}
+
+func TestRouteBindingStoreRepublishAllowsOwnRuntimeRoute(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved := saveAndPublishTestRoute(t, store)
+ if _, err := store.Publish(context.Background(), saved.Object.Metadata.Name, saved.Revision); err != nil {
+ t.Fatalf("republish route: %v", err)
+ }
+}
+
+func TestRouteBindingStoreSaveUsesPublishedRuntimeIdentity(t *testing.T) {
+ store := newTestRouteBindingStore(t)
+ saved, err := store.SaveDraft(context.Background(), testRouteBinding("user-get", "/api/users", "GET"), true, 0)
+ if err != nil {
+ t.Fatalf("SaveDraft: %v", err)
+ }
+ if _, err := store.Publish(context.Background(), "user-get", saved.Revision); err != nil {
+ t.Fatalf("Publish: %v", err)
+ }
+ updated := testRouteBinding("user-get", "/api/users/:id", "GET")
+ updated.Spec["target"].(map[string]any)["method"] = "GetUserByID"
+ restored, err := store.SaveDraft(context.Background(), updated, false, saved.Revision)
+ if err != nil {
+ t.Fatalf("SaveDraft from published identity: %v", err)
+ }
+ if restored.ResourceID != saved.ResourceID || restored.MethodID != saved.MethodID {
+ t.Fatalf("runtime identity changed: old=%+v new=%+v", saved, restored)
+ }
+ if _, err := store.Publish(context.Background(), "user-get", restored.Revision); err != nil {
+ t.Fatalf("Publish updated route: %v", err)
+ }
+}
+
+func newTestRouteBindingStore(t *testing.T) *RouteBindingStore {
+ t.Helper()
+ registry, err := schema.NewBuiltinRegistry()
+ if err != nil {
+ t.Fatalf("NewBuiltinRegistry: %v", err)
+ }
+ store, err := NewRouteBindingStore(newFakeRouteBindingKV(), "/pixiu/config/api", registry)
+ if err != nil {
+ t.Fatalf("NewRouteBindingStore: %v", err)
+ }
+ return store
+}
+
+func fakeRouteBindingStoreKV(t *testing.T, store *RouteBindingStore) *fakeRouteBindingKV {
+ t.Helper()
+ fake, ok := store.kv.(*fakeRouteBindingKV)
+ if !ok {
+ t.Fatalf("store is not using fake route binding kv: %T", store.kv)
+ }
+ return fake
+}
+
+func testRouteBinding(name, path, method string) schema.AdminObject {
+ return schema.AdminObject{
+ Kind: schema.KindAdminRouteBinding,
+ Metadata: schema.ObjectMetadata{
+ Name: name,
+ },
+ Spec: map[string]any{
+ "entry": map[string]any{
+ "path": path,
+ "method": method,
+ },
+ "target": map[string]any{
+ "application": "UserProvider",
+ "interface": "com.example.UserService",
+ "method": "GetUser",
+ "cluster": "user-dubbo",
+ },
+ "params": []any{
+ map[string]any{
+ "from": "uri.id",
+ "to": 0,
+ "type": "java.lang.String",
+ },
+ },
+ },
+ }
+}
+
+type fakeRouteBindingValue struct {
+ value []byte
+ createRev int64
+ modifyRev int64
+}
+
+type fakeRouteBindingKV struct {
+ mu sync.Mutex
+ revision int64
+ values map[string]fakeRouteBindingValue
+}
+
+type hookedRouteBindingKV struct {
+ routeBindingKV
+ afterGet func(string)
+}
+
+func (h *hookedRouteBindingKV) Get(ctx context.Context, key string, options ...clientv3.OpOption) (*clientv3.GetResponse, error) {
+ response, err := h.routeBindingKV.Get(ctx, key, options...)
+ if err == nil {
+ h.afterGet(key)
+ }
+ return response, err
+}
+
+func newFakeRouteBindingKV() *fakeRouteBindingKV {
+ return &fakeRouteBindingKV{values: make(map[string]fakeRouteBindingValue)}
+}
+
+func (f *fakeRouteBindingKV) Get(_ context.Context, key string, options ...clientv3.OpOption) (*clientv3.GetResponse, error) {
+ op := clientv3.OpGet(key, options...)
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ keys := f.matchingKeys(string(op.KeyBytes()), op.RangeBytes())
+ response := &clientv3.GetResponse{Header: &pb.ResponseHeader{Revision: f.revision}}
+ for _, matchedKey := range keys {
+ value := f.values[matchedKey]
+ response.Kvs = append(response.Kvs, &mvccpb.KeyValue{
+ Key: []byte(matchedKey),
+ Value: append([]byte(nil), value.value...),
+ CreateRevision: value.createRev,
+ ModRevision: value.modifyRev,
+ })
+ }
+ return response, nil
+}
+
+func (f *fakeRouteBindingKV) Txn(_ context.Context) clientv3.Txn {
+ return &fakeRouteBindingTxn{store: f}
+}
+
+func (f *fakeRouteBindingKV) matchingKeys(key string, end []byte) []string {
+ keys := make([]string, 0)
+ for candidate := range f.values {
+ if len(end) == 0 {
+ if candidate == key {
+ keys = append(keys, candidate)
+ }
+ continue
+ }
+ if candidate >= key && candidate < string(end) {
+ keys = append(keys, candidate)
+ }
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+func (f *fakeRouteBindingKV) fakeValue(key string) []byte {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]byte(nil), f.values[key].value...)
+}
+
+func (f *fakeRouteBindingKV) fakePut(key string, value []byte) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.revision++
+ entry := f.values[key]
+ if entry.createRev == 0 {
+ entry.createRev = f.revision
+ }
+ entry.modifyRev = f.revision
+ entry.value = append([]byte(nil), value...)
+ f.values[key] = entry
+}
+
+func (f *fakeRouteBindingKV) fakeHasKey(key string) bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ _, exists := f.values[key]
+ return exists
+}
+
+func (f *fakeRouteBindingKV) fakeHasPrefix(prefix string) bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for key := range f.values {
+ if strings.HasPrefix(key, prefix) {
+ return true
+ }
+ }
+ return false
+}
+
+type fakeRouteBindingTxn struct {
+ store *fakeRouteBindingKV
+ comparisons []clientv3.Cmp
+ thenOps []clientv3.Op
+ elseOps []clientv3.Op
+}
+
+func (t *fakeRouteBindingTxn) If(comparisons ...clientv3.Cmp) clientv3.Txn {
+ t.comparisons = append(t.comparisons, comparisons...)
+ return t
+}
+
+func (t *fakeRouteBindingTxn) Then(operations ...clientv3.Op) clientv3.Txn {
+ t.thenOps = append(t.thenOps, operations...)
+ return t
+}
+
+func (t *fakeRouteBindingTxn) Else(operations ...clientv3.Op) clientv3.Txn {
+ t.elseOps = append(t.elseOps, operations...)
+ return t
+}
+
+func (t *fakeRouteBindingTxn) Commit() (*clientv3.TxnResponse, error) {
+ t.store.mu.Lock()
+ defer t.store.mu.Unlock()
+ succeeded := true
+ for _, comparison := range t.comparisons {
+ if !t.store.evaluateComparison(comparison) {
+ succeeded = false
+ break
+ }
+ }
+ operations := t.thenOps
+ if !succeeded {
+ operations = t.elseOps
+ }
+ if len(operations) > 0 {
+ t.store.revision++
+ for _, operation := range operations {
+ t.store.applyOperation(operation)
+ }
+ }
+ return &clientv3.TxnResponse{
+ Header: &pb.ResponseHeader{Revision: t.store.revision},
+ Succeeded: succeeded,
+ }, nil
+}
+
+func (f *fakeRouteBindingKV) evaluateComparison(comparison clientv3.Cmp) bool {
+ value, exists := f.values[string(comparison.KeyBytes())]
+ actual := int64(0)
+ switch comparison.Target {
+ case pb.Compare_CREATE:
+ actual = value.createRev
+ case pb.Compare_MOD:
+ actual = value.modifyRev
+ default:
+ return false
+ }
+ var expected int64
+ switch target := comparison.TargetUnion.(type) {
+ case *pb.Compare_CreateRevision:
+ expected = target.CreateRevision
+ case *pb.Compare_ModRevision:
+ expected = target.ModRevision
+ default:
+ return false
+ }
+ if comparison.Result != pb.Compare_EQUAL {
+ return false
+ }
+ return actual == expected || (!exists && expected == 0)
+}
+
+func (f *fakeRouteBindingKV) applyOperation(operation clientv3.Op) {
+ if operation.IsPut() {
+ key := string(operation.KeyBytes())
+ value := append([]byte(nil), operation.ValueBytes()...)
+ entry := f.values[key]
+ if entry.createRev == 0 {
+ entry.createRev = f.revision
+ }
+ entry.modifyRev = f.revision
+ entry.value = value
+ f.values[key] = entry
+ return
+ }
+ if !operation.IsDelete() {
+ return
+ }
+ key := string(operation.KeyBytes())
+ end := operation.RangeBytes()
+ for candidate := range f.values {
+ if len(end) == 0 {
+ if candidate == key {
+ delete(f.values, candidate)
+ }
+ continue
+ }
+ if candidate >= key && candidate < string(end) {
+ delete(f.values, candidate)
+ }
+ }
+}
diff --git a/admin/web/package-lock.json b/admin/web/package-lock.json
index 2a6568ee3..975e13d02 100644
--- a/admin/web/package-lock.json
+++ b/admin/web/package-lock.json
@@ -21,6 +21,7 @@
"tailwindcss": "4.3.3",
"typescript": "6.0.3",
"vite": "8.2.2",
+ "yaml": "^2.9.1",
"zod": "^4.5.4"
},
"devDependencies": {
@@ -3478,6 +3479,21 @@
"node": ">=0.10.0"
}
},
+ "node_modules/yaml": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmmirror.com/yaml/-/yaml-2.9.1.tgz",
+ "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/eemeli"
+ }
+ },
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmmirror.com/yocto-queue/-/yocto-queue-0.1.0.tgz",
diff --git a/admin/web/package.json b/admin/web/package.json
index 1346ad831..a0b4c24e8 100644
--- a/admin/web/package.json
+++ b/admin/web/package.json
@@ -27,6 +27,7 @@
"tailwindcss": "4.3.3",
"typescript": "6.0.3",
"vite": "8.2.2",
+ "yaml": "^2.9.1",
"zod": "^4.5.4"
},
"devDependencies": {
diff --git a/admin/web/src/api.ts b/admin/web/src/api.ts
index 4a33291c3..0333413f8 100644
--- a/admin/web/src/api.ts
+++ b/admin/web/src/api.ts
@@ -20,19 +20,18 @@
/** Pixiu Admin API contract, aligned with admin/web controllers and API.md. */
export const pixiuAdminApi = {
base: '/config/api/base',
- resources: {
- list: '/config/api/resource/list',
- detail: '/config/api/resource/detail',
- create: '/config/api/resource',
- update: '/config/api/resource',
- remove: '/config/api/resource',
- },
- methods: {
- list: '/config/api/resource/method/list',
- detail: '/config/api/resource/method/detail',
- create: '/config/api/resource/method',
- update: '/config/api/resource/method',
- remove: '/config/api/resource/method',
+ routeBindings: {
+ schema: '/config/api/route/schema',
+ list: '/config/api/route/list',
+ detail: '/config/api/route/detail',
+ create: '/config/api/route',
+ update: '/config/api/route',
+ remove: '/config/api/route',
+ validate: '/config/api/route/validate',
+ preview: '/config/api/route/preview',
+ publish: '/config/api/route/publish',
+ status: '/config/api/route/status',
+ diff: '/config/api/route/diff',
},
clusters: {
list: '/config/api/cluster/list',
diff --git a/admin/web/src/app/App.tsx b/admin/web/src/app/App.tsx
index 9b4075fbb..a40cdc2be 100644
--- a/admin/web/src/app/App.tsx
+++ b/admin/web/src/app/App.tsx
@@ -36,10 +36,10 @@ import {
} from 'lucide-react'
import '../styles.css'
import { Providers } from './providers'
-import { resourceApi } from '../services/resource-api'
import { clusterApi } from '../services/cluster-api'
import { listenerApi } from '../services/listener-api'
import { profileApi } from '../services/profile-api'
+import { routeBindingApi } from '../services/route-binding-api'
import {
BaseInfoPage,
ClusterConfigPage,
@@ -99,7 +99,7 @@ function AppContent() {
const locale = language === 'zh' ? 'zh-CN' : 'en-US'
const tx = (value: string) => (language === 'zh' ? zhMap[value] || value : value)
useEffect(() => {
- Promise.allSettled([resourceApi.list(), clusterApi.list(), listenerApi.list()]).then(
+ Promise.allSettled([routeBindingApi.list('draft'), clusterApi.list(), listenerApi.list()]).then(
([resources, clusters, listeners]) =>
setCounts({
resources:
diff --git a/admin/web/src/features/config/ConfigPages.tsx b/admin/web/src/features/config/ConfigPages.tsx
index e619c067d..100f9ec60 100644
--- a/admin/web/src/features/config/ConfigPages.tsx
+++ b/admin/web/src/features/config/ConfigPages.tsx
@@ -36,11 +36,12 @@ import { listenerApi } from '../../services/listener-api'
import { pluginGroupApi } from '../../services/plugin-group-api'
import { rateLimitApi } from '../../services/rate-limit-api'
import { opaApi } from '../../services/opa-api'
-import { methodApi } from '../../services/method-api'
-import { resourceApi } from '../../services/resource-api'
import { baseApi } from '../../services/base-api'
import { Locale, translateText } from '../../i18n'
-import { asJsonObject, JsonObject, Method } from '../../types/api'
+import { RouteBindingEditor } from './RouteBindingEditor'
+import { routeBindingApi } from '../../services/route-binding-api'
+import { asJsonObject, JsonObject } from '../../types/api'
+import type { RouteBinding, RouteBindingPublishStatus } from '../../types/api'
type Kind = 'cluster' | 'listener' | 'plugin'
const templates = {
@@ -49,9 +50,6 @@ const templates = {
'name: http-listener\naddress:\n socket-address:\n address: 0.0.0.0\n port: 8888\nroute_config:\n routes: []\n',
plugin:
'groupName: group1\nplugins:\n - name: rate limit\n version: 0.0.1\n priority: 1000\n externalLookupName: ExternalPluginRateLimit\n',
- resource: 'path: /api/v1/example\ntype: restful\ndescription: example route\ntimeout: 1s\n',
- method:
- 'httpVerb: GET\nonAir: true\ntimeout: 1s\ninboundRequest:\n requestType: http\nintegrationRequest:\n requestType: http\n host: 127.0.0.1:8889\n path: /example\n',
}
function Editor({
@@ -507,56 +505,57 @@ export function PluginGroupConfigPage({ locale }: { locale: Locale }) {
return <ConfigListPage kind="plugin" locale={locale} />
}
-type RouteStatus = 'Published' | 'Draft' | 'Paused'
+type RouteStatus = 'Published' | 'Draft'
type RouteRow = {
- resource: JsonObject
- method: Method | null
+ binding: RouteBinding
id: string
name: string
path: string
verb: string
target: string
status: RouteStatus
+ publishedEnabled: boolean | null
+ publishedRevision: number
+ publishStatus: RouteBindingPublishStatus
}
-function routeIdentity(item: JsonObject) {
- return String(item.id ?? item.ID ?? '')
+function routeDisplayString(value: unknown, fallback: string) {
+ return typeof value === 'string' && value.trim() ? value : fallback
}
-function routeTarget(method: Method) {
- const request = asJsonObject(method.integrationRequest ?? method.integration_request)
- const application =
- request.applicationName ??
- request.application_name ??
- request.serviceName ??
- request.service_name
- const iface = request.interfaceName ?? request.interface_name ?? request.interface
- if (application || iface) return [application, iface].filter(Boolean).join(' / ')
- const host = request.host ?? request.address ?? request.url
- const path = request.path ?? request.requestPath ?? request.request_path
- if (host && path) return `${String(host)} ${String(path)}`
- return typeof host === 'string' ? host : typeof path === 'string' ? path : '未配置后端目标'
-}
-function routeTargetFromYaml(value: unknown) {
- if (typeof value !== 'string') return ''
- const scalar = (match: RegExpMatchArray | null) =>
- match?.[1]?.replace(/^['"]|['"]$/g, '').trim() || ''
- const hosts = [...value.matchAll(/(?:^|\n)\s+host:\s*([^\n]+)/g)].map((match) => scalar(match))
- const paths = [...value.matchAll(/(?:^|\n)\s+path:\s*([^\n]+)/g)].map((match) => scalar(match))
- const host = hosts[hosts.length - 1] || ''
- const path = paths[paths.length - 1] || ''
- return host && path ? `${host} ${path}` : host || path
-}
-function routeStatus(method: Method): RouteStatus {
- if (method?.status === 'Draft' || method?.status === 'draft' || method?.draft === true)
- return 'Draft'
- if (
- method?.onAir === false ||
- method?.on_air === false ||
- method?.status === 'Paused' ||
- method?.status === 'paused'
- )
- return 'Paused'
- return 'Published'
+
+function routeRow(
+ binding: RouteBinding,
+ published: Map<string, RouteBinding>,
+ publishStatus: RouteBindingPublishStatus,
+ locale: Locale,
+): RouteRow {
+ const object = binding.object
+ const spec = asJsonObject(object.spec)
+ const entry = asJsonObject(spec.entry)
+ const target = asJsonObject(spec.target)
+ const name = String(object.metadata?.name || `route.${binding.resourceId}`)
+ const publishedBinding = published.get(name)
+ const publishedSpec = publishedBinding ? asJsonObject(publishedBinding.object.spec) : null
+ const targetLabel = [target.application, target.interface]
+ .filter((value) => typeof value === 'string' && value.trim())
+ .join(' / ')
+
+ return {
+ binding,
+ id: name,
+ name,
+ path: routeDisplayString(entry.path, '-'),
+ verb: routeDisplayString(entry.method, 'GET').toUpperCase(),
+ target:
+ targetLabel ||
+ (typeof target.cluster === 'string' && target.cluster.trim()
+ ? target.cluster
+ : translateText(locale, '未配置后端目标')),
+ status: publishStatus.publishedExists && !publishStatus.dirty ? 'Published' : 'Draft',
+ publishedEnabled: publishedBinding ? publishedSpec?.enabled !== false : null,
+ publishedRevision: publishStatus.publishedRevision,
+ publishStatus,
+ }
}
export function ResourcePage({
@@ -572,73 +571,42 @@ export function ResourcePage({
const [query, setQuery] = useState('')
const [status, setStatus] = useState<'All' | RouteStatus>('All')
const [loading, setLoading] = useState(true)
+ const [deletingRoute, setDeletingRoute] = useState<string | null>(null)
const [error, setError] = useState('')
const [editor, setEditor] = useState<{
mode: 'create' | 'edit'
- id: string
- value: string
- } | null>(null)
- const [methods, setMethods] = useState<{ resourceId: string; items: Method[] } | null>(null)
- const [methodEditor, setMethodEditor] = useState<{
- mode: 'create' | 'edit'
- id: string
- value: string
+ name: string
+ binding: RouteBinding | null
+ loading: boolean
+ published: boolean
+ publishStatus: RouteBindingPublishStatus | null
} | null>(null)
- const [saving, setSaving] = useState(false)
- const buildRows = async (next: JsonObject[]) => {
- const grouped = await Promise.all(
- next.map(async (resource) => {
- const id = routeIdentity(resource)
- const resourceMethods = await methodApi.list(id)
- const name = String(
- resource.name ??
- resource.routeName ??
- resource.route_name ??
- resource.description ??
- `route.${id}`,
- )
- return resourceMethods.length
- ? Promise.all(
- resourceMethods.map(async (method) => {
- let target = routeTarget(method)
- if (target === '未配置后端目标' && method.id != null)
- target =
- routeTargetFromYaml(await methodApi.detail(id, String(method.id))) || target
- return {
- resource,
- method,
- id,
- name,
- path: String(method.resourcePath ?? method.resource_path ?? resource.path ?? '-'),
- verb: String(method.httpVerb ?? method.http_verb ?? 'GET').toUpperCase(),
- target: tx(target),
- status: routeStatus(method),
- }
- }),
- )
- : [
- {
- resource,
- method: null,
- id,
- name,
- path: String(resource.path ?? '-'),
- verb: '—',
- target: tx(String(resource.target ?? '未配置后端目标')),
- status: 'Draft' as RouteStatus,
- },
- ]
- }),
- )
- return grouped.flat()
- }
const load = useCallback(async () => {
setLoading(true)
setError('')
try {
- const next = await resourceApi.list()
- setRows(await buildRows(next))
- onCountChange?.(next.length)
+ const [draftBindings, publishedBindings] = await Promise.all([
+ routeBindingApi.list('draft'),
+ routeBindingApi.list('published'),
+ ])
+ const published = new Map(
+ publishedBindings.map((binding) => [binding.object.metadata.name, binding]),
+ )
+ const statuses = new Map(
+ draftBindings.map((binding) => {
+ const name = binding.object.metadata.name
+ if (!binding.publishStatus) {
+ throw new Error(`Route list did not include publish status for ${name}`)
+ }
+ return [name, binding.publishStatus] as const
+ }),
+ )
+ setRows(
+ draftBindings.map((binding) =>
+ routeRow(binding, published, statuses.get(binding.object.metadata.name)!, locale),
+ ),
+ )
+ onCountChange?.(draftBindings.length)
} catch (e) {
setError(e instanceof Error ? e.message : tx('加载路由失败'))
} finally {
@@ -653,7 +621,6 @@ export function ResourcePage({
All: rows.length,
Published: rows.filter((row) => row.status === 'Published').length,
Draft: rows.filter((row) => row.status === 'Draft').length,
- Paused: rows.filter((row) => row.status === 'Paused').length,
}),
[rows],
)
@@ -666,54 +633,83 @@ export function ResourcePage({
),
[query, rows, status],
)
- const saveResource = async () => {
- if (!editor) return
- setSaving(true)
- try {
- if (editor.mode === 'create') await resourceApi.create(editor.value)
- else await resourceApi.update(editor.id, editor.value)
- setEditor(null)
- await load()
- } catch (e) {
- setError(e instanceof Error ? e.message : tx('保存路由失败'))
- } finally {
- setSaving(false)
- }
- }
- const openMethods = async (row: RouteRow) => {
+ const openCreate = () =>
+ setEditor({
+ mode: 'create',
+ name: '',
+ binding: null,
+ loading: false,
+ published: false,
+ publishStatus: null,
+ })
+ const openEdit = async (row: RouteRow) => {
+ const name = row.binding.object.metadata.name
+ setEditor({
+ mode: 'edit',
+ name,
+ binding: null,
+ loading: true,
+ published: row.status === 'Published',
+ publishStatus: row.publishStatus,
+ })
try {
- const data = await methodApi.list(row.id)
- setMethods({ resourceId: row.id, items: Array.isArray(data) ? data : [] })
+ const [binding, routeStatus] = await Promise.all([
+ routeBindingApi.detail(name, 'draft'),
+ routeBindingApi.status(name),
+ ])
+ setEditor({
+ mode: 'edit',
+ name,
+ binding,
+ loading: false,
+ published: Boolean(routeStatus.publishedExists && !routeStatus.dirty),
+ publishStatus: routeStatus,
+ })
} catch (e) {
- setError(e instanceof Error ? e.message : tx('加载方法失败'))
+ setError(e instanceof Error ? e.message : tx('加载路由详情失败'))
+ setEditor(null)
}
}
- const saveMethod = async () => {
- if (!methodEditor || !methods) return
- setSaving(true)
+ const removeRoute = async (row: RouteRow) => {
+ if (deletingRoute !== null) return
+ const name = row.binding.object.metadata.name
+ if (
+ !window.confirm(
+ locale === 'en-US'
+ ? `Delete API route “${name}” and remove it from Pixiu?`
+ : `确认删除 API 路由“${name}”并从 Pixiu 中移除吗?`,
+ )
+ )
+ return
+ setError('')
+ setDeletingRoute(name)
try {
- if (methodEditor.mode === 'create')
- await methodApi.create(methods.resourceId, methodEditor.value)
- else await methodApi.update(methods.resourceId, methodEditor.id, methodEditor.value)
- setMethodEditor(null)
- setMethods({ ...methods, items: await methodApi.list(methods.resourceId) })
+ await routeBindingApi.remove(name, row.binding.revision)
await load()
} catch (e) {
- setError(e instanceof Error ? e.message : tx('保存方法失败'))
+ setError(e instanceof Error ? e.message : tx('删除路由失败'))
} finally {
- setSaving(false)
+ setDeletingRoute(null)
}
}
- const statusLabel = (value: RouteStatus) =>
- value === 'Published' ? tx('已发布') : value === 'Draft' ? tx('草稿') : tx('已暂停')
- const actionLabel = (mode: 'create' | 'edit') =>
- locale === 'en-US'
- ? mode === 'create'
- ? 'Create '
- : 'Edit '
- : mode === 'create'
- ? '新建'
- : '编辑'
+ const statusLabel = (value: RouteStatus) => (value === 'Published' ? tx('已发布') : tx('草稿'))
+ if (editor) {
+ return (
+ <RouteBindingEditor
+ locale={locale}
+ mode={editor.mode}
+ binding={editor.binding}
+ loading={editor.loading}
+ published={editor.published}
+ publishStatus={editor.publishStatus}
+ onBack={() => {
+ setEditor(null)
+ void load()
+ }}
+ onSaved={() => load()}
+ />
+ )
+ }
return (
<div className="page-resource route-prototype">
<div className="placeholder-head">
@@ -731,10 +727,7 @@ export function ResourcePage({
<RefreshCw size={14} />
{tx('刷新')}
</button>
- <button
- className="primary"
- onClick={() => setEditor({ mode: 'create', id: '', value: templates.resource })}
- >
+ <button className="primary" onClick={openCreate}>
<Plus size={15} />
{locale === 'en-US' ? 'Create API route' : '新建 API 路由'}
</button>
@@ -756,7 +749,7 @@ export function ResourcePage({
/>
</label>
<div className="filters">
- {(['All', 'Published', 'Draft', 'Paused'] as const).map((value) => (
+ {(['All', 'Published', 'Draft'] as const).map((value) => (
<button
key={value}
className={`filter ${status === value ? 'active' : ''}`}
@@ -781,10 +774,7 @@ export function ResourcePage({
? 'No live resources yet. Use the button above to create the first route.'
: '真实资源列表为空,点击右上角创建第一条路由。'}
</span>
- <button
- className="primary"
- onClick={() => setEditor({ mode: 'create', id: '', value: templates.resource })}
- >
+ <button className="primary" onClick={openCreate}>
{locale === 'en-US' ? 'Create API route' : '新建 API 路由'}
</button>
</div>
@@ -796,7 +786,8 @@ export function ResourcePage({
<th>Route</th>
<th>{tx('请求方法')}</th>
<th>{tx('后端目标')}</th>
- <th>Status</th>
+ <th>{tx('发布状态')}</th>
+ <th>{tx('已发布配置')}</th>
<th>Requests</th>
<th>Updated</th>
<th aria-label={tx('操作')} />
@@ -825,24 +816,38 @@ export function ResourcePage({
</span>
</td>
<td>
- <span className="mono unavailable-value">—</span>
+ {row.publishedEnabled === null ? (
+ <span className="badge draft">
+ <i />
+ {tx('未发布')}
+ </span>
+ ) : (
+ <span className={`badge ${row.publishedEnabled ? 'enabled' : 'disabled'}`}>
+ <i />
+ {row.publishedEnabled ? tx('已启用') : tx('已停用')}
+ </span>
+ )}
</td>
<td>
- <span className="muted">—</span>
+ <span className="mono unavailable-value">-</span>
+ </td>
+ <td>
+ <span className="muted">-</span>
</td>
<td>
- <button
- className="row-menu"
- title={tx('查看路由操作')}
- aria-label={
- locale === 'en-US'
- ? `View actions for ${row.name}`
- : `查看 ${row.name} 的路由操作`
- }
- onClick={() => void openMethods(row)}
- >
- •••
- </button>
+ <div className="row-actions route-row-actions">
+ <button className="link-btn" onClick={() => void openEdit(row)}>
+ {tx('编辑')}
+ </button>
+ <button
+ className="link-btn danger-link"
+ disabled={deletingRoute !== null}
+ onClick={() => void removeRoute(row)}
+ >
+ <Trash2 size={13} />
+ {deletingRoute === row.name ? tx('删除中…') : tx('删除')}
+ </button>
+ </div>
</td>
</tr>
))}
@@ -856,79 +861,6 @@ export function ResourcePage({
</div>
)}
</div>
- {editor && (
- <Editor
- locale={locale}
- title={`${locale === 'en-US' ? (editor.mode === 'create' ? 'Create' : 'Edit') + ' API route' : editor.mode === 'create' ? '新建 API 路由' : '编辑 API 路由'}`}
- value={editor.value}
- onChange={(value) => setEditor({ ...editor, value })}
- onClose={() => setEditor(null)}
- onSave={() => void saveResource()}
- saving={saving}
- />
- )}{' '}
- {methods && (
- <div className="drawer-backdrop" onClick={() => setMethods(null)}>
- <aside className="drawer" onClick={(e) => e.stopPropagation()}>
- <div className="drawer-head">
- <div>
- <span className="eyebrow">RESOURCE METHODS</span>
- <h2>
- {locale === 'en-US' ? 'Route methods ·' : '路由方法 ·'} {methods.resourceId}
- </h2>
- </div>
- <button className="icon-btn" onClick={() => setMethods(null)}>
- <X size={18} />
- </button>
- </div>
- <div className="form" style={{ flex: 1 }}>
- {methods.items.length === 0 ? (
- <div className="empty">{tx('暂无方法')}</div>
- ) : (
- methods.items.map((item, index) => (
- <div className="panel" key={item.id || index}>
- <b>
- {item.id || index + 1} · {item.httpVerb || 'GET'}
- </b>
- <small className="muted">{item.resourcePath || '-'}</small>
- <button
- className="link-btn"
- onClick={async () => {
- try {
- const value = await methodApi.detail(methods.resourceId, String(item.id))
- setMethodEditor({ mode: 'edit', id: String(item.id), value: value || '' })
- } catch (e) {
- setError(e instanceof Error ? e.message : tx('加载方法详情失败'))
- }
- }}
- >
- {tx('编辑 YAML')}
- </button>
- </div>
- ))
- )}
- <button
- className="secondary"
- onClick={() => setMethodEditor({ mode: 'create', id: '', value: templates.method })}
- >
- <Plus size={14} />
- {tx('新建方法')}
- </button>
- </div>
- </aside>
- </div>
- )}
- {methodEditor && (
- <Editor
- locale={locale}
- title={`${actionLabel(methodEditor.mode)}${locale === 'en-US' ? 'method' : '方法'}`}
- value={methodEditor.value}
- onChange={(value) => setMethodEditor({ ...methodEditor, value })}
- onClose={() => setMethodEditor(null)}
- onSave={() => void saveMethod()}
- saving={saving}
- />
- )}
</div>
)
}
diff --git a/admin/web/src/features/config/RouteBindingEditor.tsx b/admin/web/src/features/config/RouteBindingEditor.tsx
new file mode 100644
index 000000000..269c88be0
--- /dev/null
+++ b/admin/web/src/features/config/RouteBindingEditor.tsx
@@ -0,0 +1,628 @@
+/*
+ * 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { API_STATUS } from '../../app/constants'
+import { Locale, translateText } from '../../i18n'
+import { routeBindingApi } from '../../services/route-binding-api'
+import { ApiError } from '../../services/http'
+import type {
+ AdminRouteBindingObject,
+ RouteBinding,
+ RouteBindingDiff,
+ RouteBindingObjectSchema,
+ RouteBindingParam,
+ RouteBindingPublishStatus,
+ RouteBindingValidationIssue,
+} from '../../types/api'
+import {
+ RouteEditorContent,
+ RouteEditorContract,
+ RouteEditorHeader,
+ RouteEditorNotice,
+ RouteEditorTabs,
+} from './RouteBindingEditorSections'
+import type { BusyAction, EditorTab, Notice } from './RouteBindingEditorSections'
+import {
+ createDefaultRouteBinding,
+ hasLegacyPublishPreference,
+ normaliseRouteBindingObject,
+ parseRouteBindingYaml,
+ routeEditorOptions,
+ stringifyRouteBindingYaml,
+} from './RouteBindingEditorModel'
+
+type RouteBindingEditorProps = {
+ readonly locale: Locale
+ readonly mode: 'create' | 'edit'
+ readonly binding?: RouteBinding | null
+ readonly loading: boolean
+ readonly published: boolean
+ readonly publishStatus?: RouteBindingPublishStatus | null
+ readonly onBack: () => void
+ readonly onSaved: () => void | Promise<void>
+}
+
+function createEmptyObject(): AdminRouteBindingObject {
+ return {
+ kind: 'AdminRouteBinding',
+ metadata: { name: '' },
+ spec: {
+ entry: { protocol: '', path: '', method: '' },
+ target: {
+ protocol: '',
+ application: '',
+ interface: '',
+ method: '',
+ version: '',
+ group: '',
+ cluster: '',
+ },
+ params: [],
+ enabled: false,
+ extensions: {},
+ },
+ }
+}
+
+function errorMessage(error: unknown, fallback: string) {
+ return error instanceof Error ? error.message : fallback
+}
+
+function routeBindingHydrationKey(
+ binding: RouteBinding | null | undefined,
+ mode: RouteBindingEditorProps['mode'],
+) {
+ if (binding) return `${binding.object.metadata.name}:${binding.revision}`
+ if (mode === 'create') return 'new-route'
+ return ''
+}
+
+function errorIssues(error: unknown) {
+ return error instanceof ApiError ? error.issues : []
+}
+
+function issueFor(issues: RouteBindingValidationIssue[], path: string) {
+ return issues.find((issue) => issue.path === path)?.message || ''
+}
+
+function currentStatusLabel(
+ isEnglish: boolean,
+ dirty: boolean,
+ published: boolean,
+ translate: (value: string) => string,
+) {
+ if (dirty) return isEnglish ? 'Unsaved changes' : '有未保存改动'
+ if (published) return translate('已发布')
+ return translate('草稿')
+}
+
+function lifecycleStatusLabel(isEnglish: boolean, enabled: boolean) {
+ if (enabled) return isEnglish ? 'Draft enabled' : '草稿启用'
+ return isEnglish ? 'Draft disabled' : '草稿停用'
+}
+
+function publishSuccessMessage(isEnglish: boolean, deleted: boolean) {
+ if (isEnglish) {
+ return deleted
+ ? 'The route was removed atomically from etcd. Pixiu runtime loading is not acknowledged here.'
+ : 'The route was committed atomically to etcd. Pixiu runtime loading is not acknowledged here.'
+ }
+ return deleted
+ ? '当前路由已通过 etcd 事务原子删除;此处不会确认 Pixiu 运行时是否已完成加载。'
+ : '当前路由已通过 etcd 事务原子写入;此处不会确认 Pixiu 运行时是否已完成加载。'
+}
+
+export function RouteBindingEditor({
+ locale,
+ mode: initialMode,
+ binding,
+ loading,
+ published: initialPublished,
+ publishStatus: initialPublishStatus,
+ onBack,
+ onSaved,
+}: RouteBindingEditorProps) {
+ const isEnglish = locale === 'en-US'
+ const tx = (value: string) => translateText(locale, value)
+ const [mode, setMode] = useState(initialMode)
+ const [object, setObject] = useState<AdminRouteBindingObject>(createEmptyObject)
+ const [revision, setRevision] = useState(binding?.revision || 0)
+ const [published, setPublished] = useState(initialPublished)
+ const [publishStatus, setPublishStatus] = useState<RouteBindingPublishStatus | null>(
+ initialPublishStatus || null,
+ )
+ const [activeTab, setActiveTab] = useState<EditorTab>('form')
+ const [busy, setBusy] = useState<BusyAction>('')
+ const [dirty, setDirty] = useState(initialMode === 'create')
+ const [issues, setIssues] = useState<RouteBindingValidationIssue[]>([])
+ const [notice, setNotice] = useState<Notice | null>(null)
+ const [previewYaml, setPreviewYaml] = useState('')
+ const [routeYaml, setRouteYaml] = useState('')
+ const [yamlError, setYamlError] = useState('')
+ const [yamlDefaultsApplied, setYamlDefaultsApplied] = useState(false)
+ const [schema, setSchema] = useState<RouteBindingObjectSchema | null>(null)
+ const [schemaLoading, setSchemaLoading] = useState(true)
+ const [schemaError, setSchemaError] = useState('')
+ const [diffData, setDiffData] = useState<RouteBindingDiff | null>(null)
+ const hydratedBindingKey = useRef('')
+
+ const loadSchema = useCallback(async () => {
+ setSchemaLoading(true)
+ setSchemaError('')
+ try {
+ setSchema(await routeBindingApi.schema())
+ } catch (error: unknown) {
+ setSchema(null)
+ setSchemaError(
+ errorMessage(
+ error,
+ isEnglish ? 'Could not load the route schema.' : '无法加载路由 Schema。',
+ ),
+ )
+ } finally {
+ setSchemaLoading(false)
+ }
+ }, [isEnglish])
+
+ useEffect(() => {
+ void loadSchema()
+ }, [loadSchema])
+
+ useEffect(() => {
+ if (loading || schemaLoading || !schema) return
+ const bindingKey = routeBindingHydrationKey(binding, initialMode)
+ if (!bindingKey) return
+ if (hydratedBindingKey.current === bindingKey) return
+ let normalized: AdminRouteBindingObject
+ const removedLegacyPublish = binding ? hasLegacyPublishPreference(binding.object) : false
+ try {
+ normalized = binding
+ ? normaliseRouteBindingObject(binding.object, schema, true)
+ : createDefaultRouteBinding(schema)
+ } catch (error: unknown) {
+ const message = errorMessage(
+ error,
+ isEnglish ? 'Route data does not match the schema.' : '路由数据不符合 Schema。',
+ )
+ if (binding) {
+ hydratedBindingKey.current = bindingKey
+ setObject(createDefaultRouteBinding(schema))
+ setRouteYaml(stringifyRouteBindingYaml(binding.object))
+ setYamlError(message)
+ setDirty(true)
+ setActiveTab('yaml')
+ setNotice({ tone: 'error', text: message })
+ } else {
+ setSchemaError(message)
+ }
+ return
+ }
+ hydratedBindingKey.current = bindingKey
+ setMode(initialMode)
+ setObject(normalized)
+ setRevision(binding?.revision || 0)
+ setPublished(initialPublished)
+ setPublishStatus(initialPublishStatus || null)
+ setDirty(initialMode === 'create' || removedLegacyPublish)
+ setIssues([])
+ setNotice(
+ removedLegacyPublish
+ ? {
+ tone: 'success',
+ text: isEnglish
+ ? 'An obsolete no-op spec.publish field was removed. Save this draft to persist the cleanup.'
+ : '已移除旧的无效 spec.publish 字段;保存草稿后才会持久化这次清理。',
+ }
+ : null,
+ )
+ setPreviewYaml('')
+ setRouteYaml(stringifyRouteBindingYaml(normalized))
+ setYamlError('')
+ setYamlDefaultsApplied(false)
+ setDiffData(null)
+ setActiveTab('form')
+ }, [
+ binding,
+ initialMode,
+ initialPublishStatus,
+ initialPublished,
+ isEnglish,
+ loading,
+ schema,
+ schemaLoading,
+ ])
+
+ const entry = object.spec.entry
+ const signature = useMemo(() => JSON.stringify(object), [object])
+ const routeLabel = object.metadata.name || (isEnglish ? 'New API route' : '新建 API 路由')
+ const currentStatus = currentStatusLabel(isEnglish, dirty, published, tx)
+ const lifecycleStatus = lifecycleStatusLabel(isEnglish, object.spec.enabled)
+ const options = useMemo(() => (schema ? routeEditorOptions(schema) : undefined), [schema])
+
+ const editorBlocked = schemaLoading || !schema || Boolean(schemaError)
+
+ const updateObject = (next: AdminRouteBindingObject) => {
+ setObject(next)
+ setRouteYaml(stringifyRouteBindingYaml(next))
+ setYamlError('')
+ setYamlDefaultsApplied(false)
+ setDirty(true)
+ setIssues([])
+ setNotice(null)
+ setPreviewYaml('')
+ setDiffData(null)
+ }
+
+ const updateYaml = (value: string) => {
+ setRouteYaml(value)
+ setDirty(true)
+ setIssues([])
+ setNotice(null)
+ setPreviewYaml('')
+ setDiffData(null)
+
+ if (!schema) {
+ setYamlError(isEnglish ? 'Route schema is not loaded.' : '路由 Schema 尚未加载。')
+ return
+ }
+ const parsed = parseRouteBindingYaml(value, schema)
+ if (!parsed.object) {
+ setYamlError(parsed.error)
+ setYamlDefaultsApplied(false)
+ return
+ }
+ if (mode === 'edit' && parsed.object.metadata.name !== object.metadata.name) {
+ setYamlError(
+ isEnglish ? 'metadata.name cannot change while editing.' : '编辑时不能修改 metadata.name。',
+ )
+ return
+ }
+ setYamlError('')
+ setYamlDefaultsApplied(parsed.defaultsApplied)
+ setObject(parsed.object)
+ }
+
+ const applyYamlToForm = () => {
+ if (!schema) {
+ setYamlError(isEnglish ? 'Route schema is not loaded.' : '路由 Schema 尚未加载。')
+ return
+ }
+ const parsed = parseRouteBindingYaml(routeYaml, schema)
+ if (!parsed.object) {
+ setYamlError(parsed.error)
+ return
+ }
+ if (mode === 'edit' && parsed.object.metadata.name !== object.metadata.name) {
+ setYamlError(
+ isEnglish ? 'metadata.name cannot change while editing.' : '编辑时不能修改 metadata.name。',
+ )
+ return
+ }
+ setObject(parsed.object)
+ setRouteYaml(stringifyRouteBindingYaml(parsed.object))
+ setYamlError('')
+ setYamlDefaultsApplied(false)
+ setIssues([])
+ setNotice({
+ tone: 'success',
+ text: isEnglish ? 'YAML is synced to the form.' : 'YAML 已同步到表单。',
+ })
+ }
+
+ const updateEntry = (key: 'path' | 'method', value: string) =>
+ updateObject({
+ ...object,
+ spec: { ...object.spec, entry: { ...object.spec.entry, [key]: value } },
+ })
+
+ const updateTarget = (
+ key: 'application' | 'interface' | 'method' | 'version' | 'group' | 'cluster',
+ value: string,
+ ) =>
+ updateObject({
+ ...object,
+ spec: { ...object.spec, target: { ...object.spec.target, [key]: value } },
+ })
+
+ const updateParam = (index: number, patch: Partial<RouteBindingParam>) => {
+ const params = object.spec.params.map((param, paramIndex) =>
+ paramIndex === index ? { ...param, ...patch } : param,
+ )
+ updateObject({ ...object, spec: { ...object.spec, params } })
+ }
+
+ const addParam = () => {
+ const nextParam: RouteBindingParam = {
+ from: '',
+ to: object.spec.params.length,
+ type: options?.paramTypes[0] || '',
+ }
+ updateObject({
+ ...object,
+ spec: { ...object.spec, params: [...object.spec.params, nextParam] },
+ })
+ }
+
+ const removeParam = (index: number) =>
+ updateObject({
+ ...object,
+ spec: {
+ ...object.spec,
+ params: object.spec.params.filter((_, paramIndex) => paramIndex !== index),
+ },
+ })
+
+ const setRouteEnabled = (enabled: boolean) =>
+ updateObject({ ...object, spec: { ...object.spec, enabled } })
+
+ const validate = async () => {
+ if (yamlError || editorBlocked || !schema) return
+ setBusy('validate')
+ setNotice(null)
+ try {
+ const result = await routeBindingApi.validate(object)
+ const normalized = normaliseRouteBindingObject(result.object, schema)
+ const changed = JSON.stringify(normalized) !== signature
+ setObject(normalized)
+ setRouteYaml(stringifyRouteBindingYaml(normalized))
+ setYamlError('')
+ setYamlDefaultsApplied(false)
+ setDirty((current) => current || changed)
+ setIssues([])
+ setNotice({
+ tone: 'success',
+ text: isEnglish
+ ? 'Configuration is valid. Schema defaults are applied.'
+ : '配置校验通过,默认值已补齐。',
+ })
+ } catch (error: unknown) {
+ setIssues(errorIssues(error))
+ setNotice({ tone: 'error', text: errorMessage(error, tx('配置校验失败')) })
+ } finally {
+ setBusy('')
+ }
+ }
+
+ const saveDraft = async (): Promise<RouteBinding | null> => {
+ if (yamlError || editorBlocked || !schema) return null
+ if (!object.metadata.name.trim()) {
+ const missingName = [
+ { path: 'metadata.name', code: 'required', message: tx('请输入路由名称') },
+ ]
+ setIssues(missingName)
+ setNotice({ tone: 'error', text: tx('请先补充必填字段') })
+ setActiveTab('form')
+ return null
+ }
+ setBusy('save')
+ setNotice(null)
+ try {
+ const saved =
+ mode === 'create'
+ ? await routeBindingApi.create(object)
+ : await routeBindingApi.update(
+ binding?.object.metadata.name || object.metadata.name,
+ object,
+ revision,
+ )
+ const normalized = normaliseRouteBindingObject(saved.object, schema)
+ setObject(normalized)
+ setRouteYaml(stringifyRouteBindingYaml(normalized))
+ setYamlError('')
+ setYamlDefaultsApplied(false)
+ setMode('edit')
+ setRevision(saved.revision || 0)
+ setDirty(false)
+ setIssues([])
+ setPreviewYaml('')
+ setDiffData(null)
+ setPublished(false)
+ setNotice({ tone: 'success', text: isEnglish ? 'Draft saved.' : '草稿已保存。' })
+ try {
+ const nextStatus = await routeBindingApi.status(normalized.metadata.name)
+ setPublishStatus(nextStatus)
+ setPublished(Boolean(nextStatus.publishedExists && !nextStatus.dirty))
+ } catch {
+ // The draft was saved successfully. A status refresh is best effort.
+ }
+ await onSaved()
+ return saved
+ } catch (error: unknown) {
+ setIssues(errorIssues(error))
+ setNotice({ tone: 'error', text: errorMessage(error, tx('保存草稿失败')) })
+ setActiveTab('form')
+ return null
+ } finally {
+ setBusy('')
+ }
+ }
+
+ const publish = async () => {
+ if (yamlError || editorBlocked || !schema) return
+ let publishRevision = revision
+ if (dirty || mode === 'create' || revision === 0) {
+ const saved = await saveDraft()
+ if (!saved) return
+ publishRevision = saved.revision
+ }
+ if (!publishRevision) {
+ setNotice({
+ tone: 'error',
+ text: isEnglish
+ ? 'Draft revision is missing. Refresh and try again.'
+ : '草稿版本缺失,请刷新后重试。',
+ })
+ return
+ }
+ setBusy('publish')
+ setNotice(null)
+ try {
+ const routeName = object.metadata.name
+ const result = await routeBindingApi.publish(routeName, publishRevision)
+ const nextStatus = await routeBindingApi.status(routeName)
+ setPublishStatus(nextStatus)
+ setPublished(Boolean(nextStatus.publishedExists && !nextStatus.dirty))
+ setDirty(false)
+ setDiffData(null)
+ setNotice({
+ tone: 'success',
+ text: publishSuccessMessage(isEnglish, result.deletedCount > 0),
+ })
+ await onSaved()
+ } catch (error: unknown) {
+ setIssues(errorIssues(error))
+ const conflict = error instanceof ApiError && error.code === API_STATUS.CONCURRENT
+ let message = errorMessage(error, tx('发布失败,请刷新后重试'))
+ if (conflict) {
+ message = isEnglish
+ ? 'The draft changed. Refresh and review it before publishing.'
+ : '草稿已更新,请刷新并确认内容后再发布。'
+ }
+ setNotice({
+ tone: 'error',
+ text: message,
+ })
+ } finally {
+ setBusy('')
+ }
+ }
+
+ const loadDiff = async () => {
+ if (mode === 'create' || dirty) {
+ setActiveTab('form')
+ setNotice({
+ tone: 'error',
+ text: isEnglish ? 'Save the draft before viewing Diff.' : '请先保存草稿,再查看 Diff。',
+ })
+ return
+ }
+ setActiveTab('diff')
+ setBusy('diff')
+ setNotice(null)
+ try {
+ setDiffData(await routeBindingApi.diff(object.metadata.name))
+ setIssues([])
+ } catch (error: unknown) {
+ setIssues(errorIssues(error))
+ setNotice({ tone: 'error', text: errorMessage(error, tx('加载 Diff 失败')) })
+ } finally {
+ setBusy('')
+ }
+ }
+
+ const preview = async (tab: 'preview' | 'yaml' = 'preview') => {
+ if (yamlError || editorBlocked || !schema) return
+ setActiveTab(tab)
+ setBusy('preview')
+ setNotice(null)
+ try {
+ const result = await routeBindingApi.preview(object)
+ const normalized = normaliseRouteBindingObject(result.object, schema)
+ setObject(normalized)
+ setRouteYaml(stringifyRouteBindingYaml(normalized))
+ setYamlError('')
+ setYamlDefaultsApplied(false)
+ setDirty((current) => current || JSON.stringify(normalized) !== signature)
+ setPreviewYaml(result.yaml)
+ setIssues([])
+ } catch (error: unknown) {
+ setIssues(errorIssues(error))
+ setNotice({ tone: 'error', text: errorMessage(error, tx('生成预览失败')) })
+ } finally {
+ setBusy('')
+ }
+ }
+
+ const changeTab = (tab: EditorTab) => {
+ setActiveTab(tab)
+ if (tab === 'diff' && !diffData) {
+ void loadDiff()
+ return
+ }
+ if (tab === 'preview' && !previewYaml) void preview()
+ }
+
+ const issueMessage = (path: string) => issueFor(issues, path)
+
+ return (
+ <div className="page-resource route-editor-page route-binding-editor">
+ <RouteEditorHeader
+ isEnglish={isEnglish}
+ routeLabel={routeLabel}
+ entry={entry}
+ publishStatus={publishStatus}
+ dirty={dirty}
+ published={published}
+ enabled={object.spec.enabled}
+ currentStatus={currentStatus}
+ lifecycleStatus={lifecycleStatus}
+ busy={busy}
+ yamlError={yamlError}
+ actionsDisabled={editorBlocked}
+ onBack={onBack}
+ onValidate={() => void validate()}
+ onSave={() => void saveDraft()}
+ onPublish={() => void publish()}
+ />
+ <RouteEditorContract isEnglish={isEnglish} />
+ {notice && <RouteEditorNotice notice={notice} />}
+ {schemaError && (
+ <div className="route-editor-notice error" role="alert">
+ <span>{schemaError}</span>
+ <button className="secondary" type="button" onClick={() => void loadSchema()}>
+ {isEnglish ? 'Retry schema' : '重试加载 Schema'}
+ </button>
+ </div>
+ )}
+ <RouteEditorTabs isEnglish={isEnglish} activeTab={activeTab} onChange={changeTab} />
+ <RouteEditorContent
+ isEnglish={isEnglish}
+ loading={loading || schemaLoading || Boolean(schemaError) || !schema}
+ activeTab={activeTab}
+ mode={mode}
+ object={object}
+ busy={busy}
+ diffData={diffData}
+ previewYaml={previewYaml}
+ routeYaml={routeYaml}
+ yamlError={yamlError}
+ yamlDefaultsApplied={yamlDefaultsApplied}
+ options={options}
+ issueMessage={issueMessage}
+ onNameChange={(name) =>
+ updateObject({
+ ...object,
+ metadata: { ...object.metadata, name },
+ })
+ }
+ onEntryChange={updateEntry}
+ onTargetChange={updateTarget}
+ onParamAdd={addParam}
+ onParamUpdate={updateParam}
+ onParamRemove={removeParam}
+ onEnabledChange={setRouteEnabled}
+ onRefreshDiff={() => void loadDiff()}
+ onApplyYaml={applyYamlToForm}
+ onChangeYaml={updateYaml}
+ onPreview={() => void preview()}
+ />
+ </div>
+ )
+}
diff --git a/admin/web/src/features/config/RouteBindingEditorModel.test.ts b/admin/web/src/features/config/RouteBindingEditorModel.test.ts
new file mode 100644
index 000000000..a45021ab8
--- /dev/null
+++ b/admin/web/src/features/config/RouteBindingEditorModel.test.ts
@@ -0,0 +1,179 @@
+/*
+ * 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 { describe, expect, it } from 'vitest'
+import type { RouteBindingObjectSchema } from '../../types/api'
+import {
+ createDefaultRouteBinding,
+ hasLegacyPublishPreference,
+ normaliseRouteBindingObject,
+ parseRouteBindingYaml,
+ routeEditorOptions,
+} from './RouteBindingEditorModel'
+
+const schema: RouteBindingObjectSchema = {
+ kind: 'AdminRouteBinding',
+ fields: {
+ entry: {
+ type: 'object',
+ required: true,
+ properties: {
+ protocol: { type: 'string', default: 'http', enum: ['http'] },
+ path: { type: 'string', required: true, default: '/api/v1/example', pattern: '^/' },
+ method: { type: 'string', required: true, default: 'GET', enum: ['GET', 'POST'] },
+ },
+ },
+ target: {
+ type: 'object',
+ required: true,
+ properties: {
+ protocol: { type: 'string', default: 'dubbo', enum: ['dubbo'] },
+ application: { type: 'string', required: true },
+ interface: { type: 'string', required: true },
+ method: { type: 'string', required: true },
+ version: { type: 'string', default: '' },
+ group: { type: 'string', default: '' },
+ cluster: { type: 'string', required: true },
+ },
+ },
+ params: {
+ type: 'array',
+ default: [],
+ items: {
+ type: 'object',
+ properties: {
+ from: { type: 'string', required: true },
+ to: { type: 'integer', required: true, minimum: 0 },
+ type: { type: 'string', required: true, enum: ['string', 'int'] },
+ },
+ },
+ },
+ enabled: { type: 'boolean', default: true },
+ extensions: { type: 'object', default: {}, properties: {} },
+ },
+}
+
+function routeObject(spec: Record<string, unknown> = {}) {
+ return {
+ kind: 'AdminRouteBinding',
+ metadata: { name: 'gender-user' },
+ spec: {
+ entry: { protocol: 'http', path: '/smoke/gender/:id', method: 'GET' },
+ target: {
+ protocol: 'dubbo',
+ application: 'dubbo.io',
+ interface: 'org.apache.dubbo.sample.UserProvider',
+ method: 'GetGender',
+ version: '',
+ group: '',
+ cluster: 'failover',
+ },
+ params: [{ from: 'uri.id', to: 0, type: 'int' }],
+ enabled: true,
+ extensions: {},
+ ...spec,
+ },
+ }
+}
+
+describe('route binding editor model', () => {
+ it('takes create defaults and enum options from the backend schema', () => {
+ const object = createDefaultRouteBinding(schema)
+ expect(object.spec.entry).toMatchObject({
+ protocol: 'http',
+ path: '/api/v1/example',
+ method: 'GET',
+ })
+ expect(object.spec.target.protocol).toBe('dubbo')
+ expect(object.spec.enabled).toBe(true)
+ expect(routeEditorOptions(schema)).toEqual({
+ entryProtocols: ['http'],
+ targetProtocols: ['dubbo'],
+ httpMethods: ['GET', 'POST'],
+ paramTypes: ['string', 'int'],
+ })
+ })
+
+ it('rejects scalar coercion instead of silently changing the YAML value', () => {
+ expect(() => normaliseRouteBindingObject(routeObject({ enabled: 'false' }), schema)).toThrow(
+ 'spec.enabled: must be a boolean',
+ )
+ expect(() =>
+ normaliseRouteBindingObject(
+ routeObject({ params: [{ from: 'uri.id', to: '0', type: 'int' }] }),
+ schema,
+ ),
+ ).toThrow('spec.params[0].to: must be an integer')
+ })
+
+ it('keeps scalar pattern, range, and enum validation', () => {
+ expect(() =>
+ normaliseRouteBindingObject(
+ routeObject({ entry: { protocol: 'http', path: 'smoke', method: 'GET' } }),
+ schema,
+ ),
+ ).toThrow('spec.entry.path: must match ^/')
+ expect(() =>
+ normaliseRouteBindingObject(
+ routeObject({ params: [{ from: 'uri.id', to: -1, type: 'int' }] }),
+ schema,
+ ),
+ ).toThrow('spec.params[0].to: must be at least 0')
+ expect(() =>
+ normaliseRouteBindingObject(
+ routeObject({ params: [{ from: 'uri.id', to: 0, type: 'bool' }] }),
+ schema,
+ ),
+ ).toThrow('spec.params[0].type: must be one of: string, int')
+ })
+
+ it('rejects unknown and deprecated fields that would be dropped on save', () => {
+ expect(() =>
+ normaliseRouteBindingObject(routeObject({ publish: { mode: 'draft' } }), schema),
+ ).toThrow('spec.publish: is no longer supported')
+ expect(() => normaliseRouteBindingObject(routeObject({ typo: true }), schema)).toThrow(
+ 'spec.typo: is not defined by the route schema',
+ )
+ })
+
+ it('removes the obsolete no-op publish preference only when loading a stored draft', () => {
+ const storedDraft = routeObject({ publish: { mode: 'draft' } })
+ expect(hasLegacyPublishPreference(storedDraft)).toBe(true)
+ const loaded = normaliseRouteBindingObject(storedDraft, schema, true)
+ expect(loaded.spec).not.toHaveProperty('publish')
+ expect(hasLegacyPublishPreference(loaded)).toBe(false)
+ })
+
+ it('reports type errors while parsing YAML and identifies applied schema defaults', () => {
+ const invalid = parseRouteBindingYaml(
+ `kind: AdminRouteBinding\nmetadata:\n name: gender-user\nspec:\n enabled: "false"\n`,
+ schema,
+ )
+ expect(invalid.object).toBeNull()
+ expect(invalid.error).toContain('spec.enabled: must be a boolean')
+
+ const withDefaults = parseRouteBindingYaml(
+ `kind: AdminRouteBinding\nmetadata:\n name: gender-user\nspec:\n entry:\n protocol: http\n path: /smoke/gender/:id\n method: GET\n target:\n protocol: dubbo\n application: dubbo.io\n interface: org.apache.dubbo.sample.UserProvider\n method: GetGender\n cluster: failover\n`,
+ schema,
+ )
+ expect(withDefaults.error).toBe('')
+ expect(withDefaults.defaultsApplied).toBe(true)
+ expect(withDefaults.object?.spec.enabled).toBe(true)
+ })
+})
diff --git a/admin/web/src/features/config/RouteBindingEditorModel.ts b/admin/web/src/features/config/RouteBindingEditorModel.ts
new file mode 100644
index 000000000..d9f6d4e32
--- /dev/null
+++ b/admin/web/src/features/config/RouteBindingEditorModel.ts
@@ -0,0 +1,281 @@
+/*
+ * 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 { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
+import type {
+ AdminRouteBindingObject,
+ RouteBindingFieldSchema,
+ RouteBindingObjectSchema,
+} from '../../types/api'
+
+type RouteEditorOptions = {
+ entryProtocols: string[]
+ targetProtocols: string[]
+ httpMethods: string[]
+ paramTypes: string[]
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function hasOwn(value: object, key: PropertyKey) {
+ return Object.prototype.hasOwnProperty.call(value, key)
+}
+
+function cloneValue(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(cloneValue)
+ if (isRecord(value)) {
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, cloneValue(child)]))
+ }
+ return value
+}
+
+function fail(path: string, message: string): never {
+ throw new Error(`${path}: ${message}`)
+}
+
+function emptyValue(field: RouteBindingFieldSchema): unknown {
+ if (hasOwn(field, 'default') && field.type !== 'object') return cloneValue(field.default)
+ switch (field.type) {
+ case 'string':
+ return ''
+ case 'integer':
+ return 0
+ case 'boolean':
+ return false
+ case 'array':
+ return []
+ case 'map':
+ return {}
+ case 'object': {
+ const defaults = isRecord(field.default)
+ ? (cloneValue(field.default) as Record<string, unknown>)
+ : {}
+ const properties = Object.fromEntries(
+ Object.entries(field.properties || {}).map(([key, child]) => [
+ key,
+ hasOwn(defaults, key) && !hasOwn(child, 'default')
+ ? cloneValue(defaults[key])
+ : emptyValue(child),
+ ]),
+ )
+ return { ...defaults, ...properties }
+ }
+ }
+}
+
+export function createDefaultRouteBinding(
+ schema: RouteBindingObjectSchema,
+): AdminRouteBindingObject {
+ const defaultValues = Object.fromEntries(
+ Object.entries(schema.fields).map(([key, field]) => [key, emptyValue(field)]),
+ )
+ return {
+ kind: schema.kind,
+ metadata: { name: '' },
+ spec: defaultValues as AdminRouteBindingObject['spec'],
+ }
+}
+
+function validateEnum(value: unknown, field: RouteBindingFieldSchema, path: string) {
+ if (field.enum && !field.enum.some((item) => Object.is(item, value))) {
+ fail(path, `must be one of: ${field.enum.map(String).join(', ')}`)
+ }
+ return value
+}
+
+function validateString(value: unknown, field: RouteBindingFieldSchema, path: string) {
+ if (typeof value !== 'string') fail(path, 'must be a string')
+ if (field.pattern && !new RegExp(field.pattern).test(value)) {
+ fail(path, `must match ${field.pattern}`)
+ }
+ return validateEnum(value, field, path)
+}
+
+function validateInteger(value: unknown, field: RouteBindingFieldSchema, path: string) {
+ if (typeof value !== 'number' || !Number.isInteger(value)) fail(path, 'must be an integer')
+ if (field.minimum !== undefined && value < field.minimum) {
+ fail(path, `must be at least ${field.minimum}`)
+ }
+ return validateEnum(value, field, path)
+}
+
+function validateBoolean(value: unknown, field: RouteBindingFieldSchema, path: string) {
+ if (typeof value !== 'boolean') fail(path, 'must be a boolean')
+ return validateEnum(value, field, path)
+}
+
+function validateObject(value: unknown, field: RouteBindingFieldSchema, path: string) {
+ if (!isRecord(value)) fail(path, 'must be an object')
+ return validateFields(value, field.properties || {}, path, Boolean(field.allowUnknown))
+}
+
+function validateArray(value: unknown, field: RouteBindingFieldSchema, path: string) {
+ if (!Array.isArray(value)) fail(path, 'must be an array')
+ const itemSchema = field.items
+ if (!itemSchema) return value.map(cloneValue)
+ return value.map((item, index) => validateField(item, itemSchema, `${path}[${index}]`))
+}
+
+function validateMap(value: unknown, field: RouteBindingFieldSchema, path: string) {
+ if (!isRecord(value)) fail(path, 'must be an object')
+ const valueSchema = field.additionalProperties
+ if (!valueSchema) return { ...value }
+ return Object.fromEntries(
+ Object.entries(value).map(([key, child]) => [
+ key,
+ validateField(child, valueSchema, `${path}.${key}`),
+ ]),
+ )
+}
+
+type FieldValueValidator = (value: unknown, field: RouteBindingFieldSchema, path: string) => unknown
+
+const fieldValueValidators: Record<RouteBindingFieldSchema['type'], FieldValueValidator> = {
+ string: validateString,
+ integer: validateInteger,
+ boolean: validateBoolean,
+ object: validateObject,
+ array: validateArray,
+ map: validateMap,
+}
+
+function validateField(value: unknown, field: RouteBindingFieldSchema, path: string): unknown {
+ return fieldValueValidators[field.type](value, field, path)
+}
+
+function validateFields(
+ source: Record<string, unknown>,
+ fields: Record<string, RouteBindingFieldSchema>,
+ path: string,
+ allowUnknown: boolean,
+) {
+ const result: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(source)) {
+ const field = fields[key]
+ if (!field) {
+ if (allowUnknown) result[key] = cloneValue(value)
+ else fail(`${path}.${key}`, 'is not defined by the route schema')
+ continue
+ }
+ result[key] = validateField(value, field, `${path}.${key}`)
+ }
+
+ for (const [key, field] of Object.entries(fields)) {
+ if (hasOwn(result, key)) continue
+ if (hasOwn(field, 'default')) {
+ result[key] = validateField(cloneValue(field.default), field, `${path}.${key}`)
+ } else if (field.required) fail(`${path}.${key}`, 'is required')
+ }
+ return result
+}
+
+export function normaliseRouteBindingObject(
+ value: unknown,
+ schema: RouteBindingObjectSchema,
+ stripLegacyPublishPreference = false,
+): AdminRouteBindingObject {
+ if (!isRecord(value)) fail('YAML', 'top level must be an object')
+ for (const key of Object.keys(value)) {
+ if (!['kind', 'metadata', 'spec'].includes(key)) fail(key, 'is not part of AdminRouteBinding')
+ }
+ if (value.kind !== schema.kind) fail('kind', `must be ${schema.kind}`)
+ if (!isRecord(value.metadata)) fail('metadata', 'must be an object')
+ for (const key of Object.keys(value.metadata)) {
+ if (key !== 'name') fail(`metadata.${key}`, 'is not defined by the route schema')
+ }
+ if (typeof value.metadata.name !== 'string') fail('metadata.name', 'must be a string')
+ if (!isRecord(value.spec)) fail('spec', 'must be an object')
+
+ // The old publish preference was a no-op and is deliberately removed by the
+ // backend normalizer. Reject it in edited YAML so it cannot appear synced
+ // while being omitted from the submitted object.
+ const specInput = { ...value.spec }
+ const hasLegacyPublishPreference = hasOwn(specInput, 'publish')
+ if (hasLegacyPublishPreference && !stripLegacyPublishPreference) {
+ fail('spec.publish', 'is no longer supported; remove this field')
+ }
+ if (hasLegacyPublishPreference) delete specInput.publish
+ const spec = validateFields(specInput, schema.fields, 'spec', false)
+ return {
+ kind: schema.kind,
+ metadata: { name: value.metadata.name },
+ spec: spec as AdminRouteBindingObject['spec'],
+ }
+}
+
+export function hasLegacyPublishPreference(value: unknown) {
+ return isRecord(value) && isRecord(value.spec) && hasOwn(value.spec, 'publish')
+}
+
+function yamlErrorMessage(error: unknown) {
+ if (!(error instanceof Error)) return String(error)
+ const linePosition = (error as Error & { linePos?: Array<{ line: number; col: number }> })
+ .linePos?.[0]
+ return linePosition
+ ? `${error.message} (${linePosition.line}:${linePosition.col})`
+ : error.message
+}
+
+export function parseRouteBindingYaml(value: string, schema: RouteBindingObjectSchema) {
+ try {
+ const parsed = parseYaml(value) as unknown
+ const object = normaliseRouteBindingObject(parsed, schema)
+ const defaultsApplied = stableStringify(parsed) !== stableStringify(object)
+ return { object, error: '', defaultsApplied }
+ } catch (error: unknown) {
+ return { object: null, error: yamlErrorMessage(error), defaultsApplied: false }
+ }
+}
+
+function stableStringify(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
+ if (isRecord(value)) {
+ return `{${Object.keys(value)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`)
+ .join(',')}}`
+ }
+ return JSON.stringify(value) ?? String(value)
+}
+
+export function stringifyRouteBindingYaml(value: AdminRouteBindingObject) {
+ return stringifyYaml(value, { indent: 2, lineWidth: 0 })
+}
+
+function stringEnum(field?: RouteBindingFieldSchema) {
+ return (field?.enum || []).filter((value): value is string => typeof value === 'string')
+}
+
+function property(field: RouteBindingFieldSchema | undefined, key: string) {
+ return field?.properties?.[key]
+}
+
+export function routeEditorOptions(schema: RouteBindingObjectSchema): RouteEditorOptions {
+ const entry = schema.fields.entry
+ const target = schema.fields.target
+ const params = schema.fields.params?.items
+ return {
+ entryProtocols: stringEnum(property(entry, 'protocol')),
+ targetProtocols: stringEnum(property(target, 'protocol')),
+ httpMethods: stringEnum(property(entry, 'method')),
+ paramTypes: stringEnum(property(params, 'type')),
+ }
+}
diff --git a/admin/web/src/features/config/RouteBindingEditorSections.tsx b/admin/web/src/features/config/RouteBindingEditorSections.tsx
new file mode 100644
index 000000000..80a22dc4e
--- /dev/null
+++ b/admin/web/src/features/config/RouteBindingEditorSections.tsx
@@ -0,0 +1,1164 @@
+/*
+ * 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 {
+ AlertCircle,
+ ArrowLeft,
+ CheckCircle2,
+ Eye,
+ FileCode2,
+ GitCompareArrows,
+ Plus,
+ Save,
+ Send,
+ Trash2,
+} from 'lucide-react'
+import { translateText } from '../../i18n'
+import type {
+ AdminRouteBindingObject,
+ RouteBindingDiff,
+ RouteBindingParam,
+ RouteBindingPublishStatus,
+} from '../../types/api'
+
+export type EditorTab = 'form' | 'preview' | 'diff' | 'yaml'
+export type BusyAction = '' | 'save' | 'publish' | 'validate' | 'preview' | 'diff'
+export type Notice = { tone: 'success' | 'error'; text: string }
+export type RouteEditorOptions = {
+ readonly entryProtocols: string[]
+ readonly targetProtocols: string[]
+ readonly httpMethods: string[]
+ readonly paramTypes: string[]
+}
+export type IssueMessage = (path: string) => string
+export type RouteEntry = AdminRouteBindingObject['spec']['entry']
+export type RouteTarget = AdminRouteBindingObject['spec']['target']
+type EditableTargetKey = Exclude<keyof RouteTarget, 'protocol'>
+
+type HeaderProps = {
+ readonly isEnglish: boolean
+ readonly routeLabel: string
+ readonly entry: RouteEntry
+ readonly publishStatus: RouteBindingPublishStatus | null
+ readonly dirty: boolean
+ readonly published: boolean
+ readonly enabled: boolean
+ readonly currentStatus: string
+ readonly lifecycleStatus: string
+ readonly busy: BusyAction
+ readonly yamlError: string
+ readonly actionsDisabled: boolean
+ readonly onBack: () => void
+ readonly onValidate: () => void
+ readonly onSave: () => void
+ readonly onPublish: () => void
+}
+
+type TabsProps = {
+ readonly isEnglish: boolean
+ readonly activeTab: EditorTab
+ readonly onChange: (tab: EditorTab) => void
+}
+
+type IdentityCardProps = {
+ readonly isEnglish: boolean
+ readonly mode: 'create' | 'edit'
+ readonly entry: RouteEntry
+ readonly name: string
+ readonly issueMessage: IssueMessage
+ readonly onNameChange: (value: string) => void
+ readonly onPathChange: (value: string) => void
+ readonly onMethodChange: (value: string) => void
+ readonly entryProtocols: string[]
+ readonly httpMethods: string[]
+}
+
+type TargetCardProps = {
+ readonly isEnglish: boolean
+ readonly target: RouteTarget
+ readonly issueMessage: IssueMessage
+ readonly onChange: (key: EditableTargetKey, value: string) => void
+ readonly targetProtocols: string[]
+}
+
+type ParamCardProps = {
+ readonly isEnglish: boolean
+ readonly params: RouteBindingParam[]
+ readonly issueMessage: IssueMessage
+ readonly paramTypes: string[]
+ readonly onAdd: () => void
+ readonly onUpdate: (index: number, patch: Partial<RouteBindingParam>) => void
+ readonly onRemove: (index: number) => void
+}
+
+type PublishCardProps = {
+ readonly isEnglish: boolean
+ readonly enabled: boolean
+ readonly onEnabledChange: (enabled: boolean) => void
+}
+
+type FormViewProps = IdentityCardProps & TargetCardProps & ParamCardProps & PublishCardProps
+
+type DiffViewProps = {
+ readonly isEnglish: boolean
+ readonly diffData: RouteBindingDiff | null
+ readonly busy: BusyAction
+ readonly onRefresh: () => void
+}
+
+type PreviewViewProps = {
+ readonly isEnglish: boolean
+ readonly activeTab: 'preview' | 'yaml'
+ readonly busy: BusyAction
+ readonly previewYaml: string
+ readonly routeYaml: string
+ readonly yamlError: string
+ readonly yamlDefaultsApplied: boolean
+ readonly onApplyYaml: () => void
+ readonly onChangeYaml: (value: string) => void
+ readonly onPreview: () => void
+}
+
+type ContentProps = {
+ readonly isEnglish: boolean
+ readonly loading: boolean
+ readonly activeTab: EditorTab
+ readonly mode: 'create' | 'edit'
+ readonly object: AdminRouteBindingObject
+ readonly busy: BusyAction
+ readonly diffData: RouteBindingDiff | null
+ readonly previewYaml: string
+ readonly routeYaml: string
+ readonly yamlError: string
+ readonly yamlDefaultsApplied: boolean
+ readonly options?: RouteEditorOptions
+ readonly issueMessage: IssueMessage
+ readonly onNameChange: (value: string) => void
+ readonly onEntryChange: (key: 'path' | 'method', value: string) => void
+ readonly onTargetChange: (key: EditableTargetKey, value: string) => void
+ readonly onParamAdd: () => void
+ readonly onParamUpdate: (index: number, patch: Partial<RouteBindingParam>) => void
+ readonly onParamRemove: (index: number) => void
+ readonly onEnabledChange: (enabled: boolean) => void
+ readonly onRefreshDiff: () => void
+ readonly onApplyYaml: () => void
+ readonly onChangeYaml: (value: string) => void
+ readonly onPreview: () => void
+}
+
+function actionLabel(
+ isEnglish: boolean,
+ busy: BusyAction,
+ action: Exclude<BusyAction, ''>,
+ idleLabel: string,
+) {
+ if (busy !== action) return idleLabel
+ const labels: Record<Exclude<BusyAction, ''>, [string, string]> = {
+ save: ['Saving...', '保存中...'],
+ publish: ['Publishing...', '发布中...'],
+ validate: ['Checking...', '校验中...'],
+ preview: ['Generating...', '生成中...'],
+ diff: ['Loading...', '加载中...'],
+ }
+ return isEnglish ? labels[action][0] : labels[action][1]
+}
+
+function routeNameHelp(isEnglish: boolean, mode: 'create' | 'edit') {
+ if (mode === 'edit')
+ return isEnglish ? 'The key stays stable while editing.' : '编辑时保持路由键稳定。'
+ return isEnglish
+ ? 'Used as the AdminRouteBinding metadata.name.'
+ : '对应 AdminRouteBinding 的 metadata.name。'
+}
+
+function previewTitle(isEnglish: boolean, activeTab: 'preview' | 'yaml') {
+ if (activeTab === 'yaml') return 'YAML'
+ return isEnglish ? 'Runtime preview' : '运行时预览'
+}
+
+function previewDescription(isEnglish: boolean, activeTab: 'preview' | 'yaml') {
+ if (activeTab === 'yaml') {
+ return isEnglish
+ ? 'Edit the AdminRouteBinding source. Valid changes sync back to the form.'
+ : '编辑 AdminRouteBinding 源配置,语法有效的改动会同步回表单。'
+ }
+ return isEnglish
+ ? 'Generated by the current AdminRouteBinding compiler.'
+ : '由当前 AdminRouteBinding 编译器生成。'
+}
+
+function routeStateClass(dirty: boolean, published: boolean) {
+ if (dirty || !published) return 'draft'
+ return 'published'
+}
+
+function yamlSyncLabel(isEnglish: boolean, yamlError: string, defaultsApplied: boolean) {
+ if (yamlError) return isEnglish ? 'Invalid YAML / schema' : 'YAML / Schema 错误'
+ if (defaultsApplied) {
+ return isEnglish ? 'Form synced · schema defaults applied' : '表单已同步 · 已应用 Schema 默认值'
+ }
+ return isEnglish ? 'Synced with form' : '已与表单同步'
+}
+
+function yamlSyncClass(yamlError: string) {
+ return yamlError ? 'error' : 'synced'
+}
+
+export function RouteEditorHeader({
+ isEnglish,
+ routeLabel,
+ entry,
+ publishStatus,
+ dirty,
+ published,
+ enabled,
+ currentStatus,
+ lifecycleStatus,
+ busy,
+ yamlError,
+ actionsDisabled,
+ onBack,
+ onValidate,
+ onSave,
+ onPublish,
+}: HeaderProps) {
+ return (
+ <>
+ <div className="route-editor-backbar">
+ <button className="route-editor-back" type="button" onClick={onBack}>
+ <ArrowLeft size={15} />
+ {isEnglish ? 'Back to API routes' : '返回 API 路由'}
+ </button>
+ <div
+ className="route-editor-revisions"
+ aria-label={isEnglish ? 'Route revisions' : '路由版本'}
+ >
+ <span className="route-revision draft">
+ {isEnglish ? 'Draft rev' : '草稿 rev'} {publishStatus?.draftRevision || '-'}
+ </span>
+ <span className="route-revision published">
+ {isEnglish ? 'Published rev' : '已发布 rev'} {publishStatus?.publishedRevision || '-'}
+ </span>
+ </div>
+ </div>
+
+ <div className="route-editor-titlebar">
+ <div>
+ <p className="eyebrow">API ROUTE</p>
+ <h1>{routeLabel}</h1>
+ <div className="route-editor-summary">
+ <span className={`method ${entry.method.toLowerCase()}`}>{entry.method || 'GET'}</span>
+ <span className="route-editor-path">
+ {entry.path || (isEnglish ? 'Path required' : '需要填写路径')}
+ </span>
+ <span className={`route-editor-state ${routeStateClass(dirty, published)}`}>
+ <i /> {currentStatus}
+ </span>
+ <span className={`route-editor-lifecycle ${enabled ? 'enabled' : 'disabled'}`}>
+ <i /> {lifecycleStatus}
+ </span>
+ </div>
+ </div>
+ <div className="route-editor-actions">
+ <button
+ className="secondary"
+ type="button"
+ disabled={busy !== '' || Boolean(yamlError) || actionsDisabled}
+ onClick={onValidate}
+ >
+ <CheckCircle2 size={14} />
+ {actionLabel(
+ isEnglish,
+ busy,
+ 'validate',
+ translateText(isEnglish ? 'en-US' : 'zh-CN', '校验'),
+ )}
+ </button>
+ <button
+ className="secondary"
+ type="button"
+ disabled={busy !== '' || Boolean(yamlError) || actionsDisabled}
+ onClick={onSave}
+ >
+ <Save size={14} />
+ {actionLabel(isEnglish, busy, 'save', isEnglish ? 'Save draft' : '保存草稿')}
+ </button>
+ <button
+ className="primary"
+ type="button"
+ disabled={busy !== '' || Boolean(yamlError) || actionsDisabled}
+ onClick={onPublish}
+ >
+ <Send size={14} />
+ {actionLabel(isEnglish, busy, 'publish', isEnglish ? 'Publish' : '发布')}
+ </button>
+ </div>
+ </div>
+ </>
+ )
+}
+
+type ContractProps = {
+ readonly isEnglish: boolean
+}
+
+export function RouteEditorContract({ isEnglish }: ContractProps) {
+ return (
+ <div className="route-editor-contract">
+ <span className="route-contract-mark">{isEnglish ? 'ATOMIC PUBLISH' : '原子发布'}</span>
+ <span>
+ {isEnglish
+ ? 'Saving updates this route draft. Publishing replaces only this route in one etcd transaction; runtime loading is not acknowledged.'
+ : '保存只更新当前路由草稿。发布会通过一次 etcd 事务只替换当前路由;此处不代表 Pixiu 运行时已确认加载。'}
+ </span>
+ </div>
+ )
+}
+
+type NoticeProps = {
+ readonly notice: Notice
+}
+
+export function RouteEditorNotice({ notice }: NoticeProps) {
+ if (notice.tone === 'error') {
+ return (
+ <div className="route-editor-notice error" role="alert">
+ <AlertCircle size={16} />
+ <span>{notice.text}</span>
+ </div>
+ )
+ }
+ return (
+ <output className="route-editor-notice success">
+ <CheckCircle2 size={16} />
+ <span>{notice.text}</span>
+ </output>
+ )
+}
+
+export function RouteEditorTabs({ isEnglish, activeTab, onChange }: TabsProps) {
+ return (
+ <div
+ className="route-editor-tabs"
+ role="tablist"
+ aria-label={isEnglish ? 'Route editor views' : '路由编辑视图'}
+ >
+ <button
+ className={activeTab === 'form' ? 'active' : ''}
+ type="button"
+ role="tab"
+ aria-selected={activeTab === 'form'}
+ onClick={() => onChange('form')}
+ >
+ {isEnglish ? 'Form' : '表单'}
+ </button>
+ <button
+ className={activeTab === 'preview' ? 'active' : ''}
+ type="button"
+ role="tab"
+ aria-selected={activeTab === 'preview'}
+ onClick={() => onChange('preview')}
+ >
+ <Eye size={14} /> {isEnglish ? 'Preview' : '预览'}
+ </button>
+ <button
+ className={activeTab === 'diff' ? 'active' : ''}
+ type="button"
+ role="tab"
+ aria-selected={activeTab === 'diff'}
+ onClick={() => onChange('diff')}
+ >
+ <GitCompareArrows size={14} /> Diff
+ </button>
+ <button
+ className="unavailable-tab"
+ type="button"
+ disabled
+ title={
+ isEnglish
+ ? 'History is not exposed by the current Admin API.'
+ : '当前 Admin API 尚未提供历史接口。'
+ }
+ >
+ {isEnglish ? 'History' : '历史'}
+ </button>
+ <button
+ className={activeTab === 'yaml' ? 'active' : ''}
+ type="button"
+ role="tab"
+ aria-selected={activeTab === 'yaml'}
+ onClick={() => onChange('yaml')}
+ >
+ <FileCode2 size={14} /> YAML
+ </button>
+ </div>
+ )
+}
+
+function RouteIdentityCard({
+ isEnglish,
+ mode,
+ entry,
+ name,
+ issueMessage,
+ onNameChange,
+ onPathChange,
+ onMethodChange,
+ entryProtocols,
+ httpMethods,
+}: IdentityCardProps) {
+ const nameIssue = issueMessage('metadata.name')
+ const pathIssue = issueMessage('spec.entry.path')
+ const methodIssue = issueMessage('spec.entry.method')
+ return (
+ <section className="panel route-editor-card">
+ <div className="panel-head">
+ <div>
+ <h2>{isEnglish ? 'Identity and entry' : '身份与入口'}</h2>
+ <span>
+ {isEnglish
+ ? 'Define the HTTP route exposed by Pixiu.'
+ : '定义 Pixiu 对外暴露的 HTTP 路由。'}
+ </span>
+ </div>
+ </div>
+ <div className="route-entry-fields">
+ <label className="route-field">
+ <span>{isEnglish ? 'Route name' : '路由名称'}</span>
+ <input
+ value={name}
+ readOnly={mode === 'edit'}
+ aria-invalid={Boolean(nameIssue)}
+ aria-describedby="route-name-help route-name-error"
+ placeholder="create-user"
+ onChange={(event) => onNameChange(event.target.value)}
+ />
+ <small id="route-name-help">{routeNameHelp(isEnglish, mode)}</small>
+ {nameIssue && (
+ <small id="route-name-error" className="route-field-error">
+ {nameIssue}
+ </small>
+ )}
+ </label>
+ <label className="route-field">
+ <span>{isEnglish ? 'Entry protocol' : '入口协议'}</span>
+ <select value={entry.protocol} disabled>
+ {entryProtocols.map((protocol) => (
+ <option key={protocol} value={protocol}>
+ {protocol.toUpperCase()}
+ </option>
+ ))}
+ </select>
+ <small>
+ {isEnglish ? 'The current schema accepts HTTP only.' : '当前 schema 仅支持 HTTP。'}
+ </small>
+ </label>
+ <label className="route-field route-field-wide">
+ <span>{isEnglish ? 'Path' : '路径'}</span>
+ <input
+ value={entry.path}
+ aria-invalid={Boolean(pathIssue)}
+ placeholder="/api/v1/users/:id"
+ onChange={(event) => onPathChange(event.target.value)}
+ />
+ {pathIssue && <small className="route-field-error">{pathIssue}</small>}
+ </label>
+ <fieldset className="route-field route-field-wide route-method-fieldset">
+ <legend>{isEnglish ? 'HTTP method' : '请求方法'}</legend>
+ <div className="route-method-options">
+ {httpMethods.map((method) => (
+ <button
+ className={entry.method === method ? 'active' : ''}
+ key={method}
+ type="button"
+ aria-pressed={entry.method === method}
+ onClick={() => onMethodChange(method)}
+ >
+ {method}
+ </button>
+ ))}
+ </div>
+ {methodIssue && <small className="route-field-error">{methodIssue}</small>}
+ </fieldset>
+ </div>
+ </section>
+ )
+}
+
+type TargetFieldProps = {
+ readonly label: string
+ readonly value: string
+ readonly placeholder: string
+ readonly issue: string
+ readonly onChange: (value: string) => void
+}
+
+function TargetField({ label, value, placeholder, issue, onChange }: TargetFieldProps) {
+ return (
+ <label className="route-field">
+ <span>{label}</span>
+ <input
+ value={value}
+ placeholder={placeholder}
+ onChange={(event) => onChange(event.target.value)}
+ />
+ {issue && <small className="route-field-error">{issue}</small>}
+ </label>
+ )
+}
+
+function RouteTargetCard({
+ isEnglish,
+ target,
+ issueMessage,
+ onChange,
+ targetProtocols,
+}: TargetCardProps) {
+ const fields: Array<{
+ key: EditableTargetKey
+ label: string
+ placeholder: string
+ issuePath: string
+ }> = [
+ {
+ key: 'cluster',
+ label: 'Cluster',
+ placeholder: 'user-service',
+ issuePath: 'spec.target.cluster',
+ },
+ {
+ key: 'application',
+ label: 'Application',
+ placeholder: 'UserProvider',
+ issuePath: 'spec.target.application',
+ },
+ {
+ key: 'interface',
+ label: 'Interface',
+ placeholder: 'com.example.user.UserService',
+ issuePath: 'spec.target.interface',
+ },
+ { key: 'method', label: 'Method', placeholder: 'GetUser', issuePath: 'spec.target.method' },
+ { key: 'group', label: 'Group', placeholder: 'stable', issuePath: '' },
+ { key: 'version', label: 'Version', placeholder: '1.0.0', issuePath: '' },
+ ]
+ return (
+ <section className="panel route-editor-card">
+ <div className="panel-head">
+ <div>
+ <h2>{isEnglish ? 'Backend target' : '后端目标'}</h2>
+ <span>
+ {isEnglish
+ ? 'Map the request to one Dubbo service method.'
+ : '将请求映射到一个 Dubbo 服务方法。'}
+ </span>
+ </div>
+ </div>
+ <div className="route-target-fields">
+ <label className="route-field">
+ <span>{isEnglish ? 'Target protocol' : '目标协议'}</span>
+ <select value={target.protocol} disabled>
+ {targetProtocols.map((protocol) => (
+ <option key={protocol} value={protocol}>
+ {protocol.toUpperCase()}
+ </option>
+ ))}
+ </select>
+ <small>
+ {isEnglish ? 'The current compiler targets Dubbo.' : '当前编译器目标为 Dubbo。'}
+ </small>
+ </label>
+ {fields.map((field) => (
+ <TargetField
+ key={field.key}
+ label={field.label}
+ value={target[field.key]}
+ placeholder={field.placeholder}
+ issue={field.issuePath ? issueMessage(field.issuePath) : ''}
+ onChange={(value) => onChange(field.key, value)}
+ />
+ ))}
+ </div>
+ </section>
+ )
+}
+
+type ParamRowProps = {
+ readonly isEnglish: boolean
+ readonly param: RouteBindingParam
+ readonly index: number
+ readonly issueMessage: IssueMessage
+ readonly types: string[]
+ readonly onUpdate: (index: number, patch: Partial<RouteBindingParam>) => void
+ readonly onRemove: (index: number) => void
+}
+
+function RouteParamRow({
+ isEnglish,
+ param,
+ index,
+ issueMessage,
+ types,
+ onUpdate,
+ onRemove,
+}: ParamRowProps) {
+ const fromIssue = issueMessage(`spec.params[${index}].from`)
+ const toIssue = issueMessage(`spec.params[${index}].to`)
+ const typeIssue = issueMessage(`spec.params[${index}].type`)
+ return (
+ <div className="route-param-row" key={`${index}-${param.from}`}>
+ <label className="route-param-field">
+ <span>{isEnglish ? 'HTTP source' : 'HTTP 来源'}</span>
+ <input
+ value={param.from}
+ aria-invalid={Boolean(fromIssue)}
+ placeholder="queryStrings.page"
+ onChange={(event) => onUpdate(index, { from: event.target.value })}
+ />
+ {fromIssue && <small className="route-field-error">{fromIssue}</small>}
+ </label>
+ <label className="route-param-field">
+ <span>{isEnglish ? 'Argument index' : '参数位置'}</span>
+ <input
+ type="number"
+ min="0"
+ value={param.to}
+ aria-invalid={Boolean(toIssue)}
+ onChange={(event) => onUpdate(index, { to: Number(event.target.value) })}
+ />
+ {toIssue && <small className="route-field-error">{toIssue}</small>}
+ </label>
+ <label className="route-param-field">
+ <span>{isEnglish ? 'Dubbo type' : 'Dubbo 类型'}</span>
+ <select
+ value={param.type}
+ onChange={(event) => onUpdate(index, { type: event.target.value })}
+ >
+ {types.map((type) => (
+ <option key={type} value={type}>
+ {type}
+ </option>
+ ))}
+ </select>
+ {typeIssue && <small className="route-field-error">{typeIssue}</small>}
+ </label>
+ <button
+ className="route-icon-action"
+ type="button"
+ aria-label={isEnglish ? `Remove parameter ${index + 1}` : `删除第 ${index + 1} 个参数`}
+ onClick={() => onRemove(index)}
+ >
+ <Trash2 size={15} />
+ </button>
+ </div>
+ )
+}
+
+function RouteParamsCard({
+ isEnglish,
+ params,
+ issueMessage,
+ paramTypes,
+ onAdd,
+ onUpdate,
+ onRemove,
+}: ParamCardProps) {
+ return (
+ <section className="panel route-param-panel">
+ <div className="panel-head route-param-head">
+ <div>
+ <h2>{isEnglish ? 'Inbound request' : '入站请求'}</h2>
+ <span>
+ {isEnglish
+ ? 'Map HTTP values to zero-based Dubbo argument indexes.'
+ : '将 HTTP 参数映射到从 0 开始的 Dubbo 参数位置。'}
+ </span>
+ </div>
+ <button className="secondary route-add-param" type="button" onClick={onAdd}>
+ <Plus size={14} /> {isEnglish ? 'Add parameter' : '添加参数'}
+ </button>
+ </div>
+ <div className="route-param-table">
+ {params.length === 0 ? (
+ <div className="route-param-empty">
+ <span>{isEnglish ? 'No parameter mappings yet.' : '暂未配置参数映射。'}</span>
+ <small>
+ {isEnglish
+ ? 'Add a mapping when the Dubbo method expects HTTP input.'
+ : '当 Dubbo 方法需要接收 HTTP 参数时,再添加映射。'}
+ </small>
+ </div>
+ ) : (
+ <>
+ <div className="route-param-header" aria-hidden="true">
+ <span>{isEnglish ? 'HTTP source' : 'HTTP 来源'}</span>
+ <span>{isEnglish ? 'Argument index' : '参数位置'}</span>
+ <span>{isEnglish ? 'Dubbo type' : 'Dubbo 类型'}</span>
+ <span />
+ </div>
+ {params.map((param, index) => (
+ <RouteParamRow
+ key={`${index}-${param.from}`}
+ isEnglish={isEnglish}
+ param={param}
+ index={index}
+ issueMessage={issueMessage}
+ types={paramTypes}
+ onUpdate={onUpdate}
+ onRemove={onRemove}
+ />
+ ))}
+ </>
+ )}
+ </div>
+ </section>
+ )
+}
+
+function RoutePublishCard({ isEnglish, enabled, onEnabledChange }: PublishCardProps) {
+ return (
+ <section className="panel route-publish-panel">
+ <div>
+ <h2>{isEnglish ? 'Release and lifecycle' : '发布与生命周期'}</h2>
+ <span>
+ {isEnglish
+ ? 'This is the draft setting. It enters the published configuration only after this route is published.'
+ : '这里配置的是草稿启停状态,只有发布后才会进入已发布配置。'}
+ </span>
+ </div>
+ <div className="route-switches">
+ <label className="route-switch">
+ <input
+ type="checkbox"
+ checked={enabled}
+ aria-label={isEnglish ? 'Enable route' : '启用路由'}
+ onChange={(event) => onEnabledChange(event.target.checked)}
+ />
+ <span className="route-switch-track" />
+ <span>{isEnglish ? 'Route enabled' : '启用路由'}</span>
+ </label>
+ </div>
+ </section>
+ )
+}
+
+function RouteFormView(props: FormViewProps) {
+ const {
+ isEnglish,
+ mode,
+ entry,
+ name,
+ target,
+ params,
+ enabled,
+ issueMessage,
+ entryProtocols,
+ targetProtocols,
+ httpMethods,
+ paramTypes,
+ onNameChange,
+ onPathChange,
+ onMethodChange,
+ onChange,
+ onAdd,
+ onUpdate,
+ onRemove,
+ onEnabledChange,
+ } = props
+ return (
+ <>
+ <div className="route-editor-layout">
+ <RouteIdentityCard
+ isEnglish={isEnglish}
+ mode={mode}
+ entry={entry}
+ name={name}
+ issueMessage={issueMessage}
+ onNameChange={onNameChange}
+ onPathChange={onPathChange}
+ onMethodChange={onMethodChange}
+ entryProtocols={entryProtocols}
+ httpMethods={httpMethods}
+ />
+ <RouteTargetCard
+ isEnglish={isEnglish}
+ target={target}
+ issueMessage={issueMessage}
+ onChange={onChange}
+ targetProtocols={targetProtocols}
+ />
+ </div>
+ <RouteParamsCard
+ isEnglish={isEnglish}
+ params={params}
+ issueMessage={issueMessage}
+ paramTypes={paramTypes}
+ onAdd={onAdd}
+ onUpdate={onUpdate}
+ onRemove={onRemove}
+ />
+ <RoutePublishCard isEnglish={isEnglish} enabled={enabled} onEnabledChange={onEnabledChange} />
+ </>
+ )
+}
+
+function DiffRow({
+ isEnglish,
+ change,
+}: {
+ readonly isEnglish: boolean
+ readonly change: RouteBindingDiff['changes'][number]
+}) {
+ return (
+ <div className="route-diff-row" key={change.path}>
+ <code>{change.path}</code>
+ <div className="route-diff-value before">
+ <small>{isEnglish ? 'Published' : '已发布'}</small>
+ <pre>{formatDiffValue(change.before)}</pre>
+ </div>
+ <div className="route-diff-value after">
+ <small>{isEnglish ? 'Draft' : '草稿'}</small>
+ <pre>{formatDiffValue(change.after)}</pre>
+ </div>
+ </div>
+ )
+}
+
+function RouteDiffContent({
+ isEnglish,
+ diffData,
+ busy,
+}: Pick<DiffViewProps, 'isEnglish' | 'diffData' | 'busy'>) {
+ if (!diffData) {
+ return busy === 'diff' ? (
+ <div className="route-diff-empty">
+ <div className="loading-skeleton" />
+ </div>
+ ) : (
+ <div className="route-diff-empty">
+ <GitCompareArrows size={22} />
+ <b>{isEnglish ? 'Diff is not loaded' : '尚未加载 Diff'}</b>
+ </div>
+ )
+ }
+ if (diffData.changes.length === 0) {
+ return (
+ <div className="route-diff-empty">
+ <CheckCircle2 size={22} />
+ <b>{isEnglish ? 'No unpublished changes' : '当前路由没有未发布改动'}</b>
+ <span>
+ {isEnglish
+ ? 'The draft and published versions are identical.'
+ : '草稿版本与已发布版本内容一致。'}
+ </span>
+ </div>
+ )
+ }
+ return (
+ <div className="route-diff-list">
+ {diffData.changes.map((change) => (
+ <DiffRow key={change.path} isEnglish={isEnglish} change={change} />
+ ))}
+ </div>
+ )
+}
+
+function RouteDiffView({ isEnglish, diffData, busy, onRefresh }: DiffViewProps) {
+ return (
+ <section className="panel route-diff-panel">
+ <div className="panel-head">
+ <div>
+ <h2>Diff</h2>
+ <span>
+ {isEnglish
+ ? 'Compare this route draft with its published version.'
+ : '对比当前路由草稿与已发布版本。'}
+ </span>
+ </div>
+ <button className="secondary" type="button" disabled={busy !== ''} onClick={onRefresh}>
+ <GitCompareArrows size={14} />
+ {actionLabel(
+ isEnglish,
+ busy,
+ 'diff',
+ translateText(isEnglish ? 'en-US' : 'zh-CN', '刷新 Diff'),
+ )}
+ </button>
+ </div>
+ <RouteDiffContent isEnglish={isEnglish} diffData={diffData} busy={busy} />
+ </section>
+ )
+}
+
+function RoutePreviewBody({
+ isEnglish,
+ activeTab,
+ previewYaml,
+ routeYaml,
+ yamlError,
+ onChangeYaml,
+}: Pick<
+ PreviewViewProps,
+ 'isEnglish' | 'activeTab' | 'previewYaml' | 'routeYaml' | 'yamlError' | 'onChangeYaml'
+>) {
+ if (activeTab === 'yaml') {
+ return (
+ <>
+ <textarea
+ className="route-preview-code route-yaml-editor"
+ value={routeYaml}
+ spellCheck={false}
+ aria-label={isEnglish ? 'Editable route YAML' : '可编辑路由 YAML'}
+ aria-invalid={Boolean(yamlError)}
+ aria-describedby={yamlError ? 'route-yaml-error' : undefined}
+ onChange={(event) => onChangeYaml(event.target.value)}
+ />
+ {yamlError && (
+ <div className="route-yaml-error" id="route-yaml-error" role="alert">
+ <AlertCircle size={15} />
+ <span>{isEnglish ? `YAML error: ${yamlError}` : `YAML 错误:${yamlError}`}</span>
+ </div>
+ )}
+ </>
+ )
+ }
+ if (previewYaml) return <pre className="route-preview-code">{previewYaml}</pre>
+ return (
+ <div className="route-preview-empty">
+ <FileCode2 size={22} />
+ <b>{isEnglish ? 'Preview is not generated' : '还没有生成预览'}</b>
+ <span>
+ {isEnglish
+ ? 'Generate a preview to inspect the legacy runtime configuration.'
+ : '生成预览后查看将写入运行时的 legacy 配置。'}
+ </span>
+ </div>
+ )
+}
+
+type PreviewActionProps = Pick<
+ PreviewViewProps,
+ 'isEnglish' | 'activeTab' | 'busy' | 'yamlError' | 'onApplyYaml' | 'onPreview'
+>
+
+function RoutePreviewAction({
+ isEnglish,
+ activeTab,
+ busy,
+ yamlError,
+ onApplyYaml,
+ onPreview,
+}: PreviewActionProps) {
+ if (activeTab === 'yaml') {
+ return (
+ <button
+ className="secondary"
+ type="button"
+ disabled={busy !== '' || Boolean(yamlError)}
+ onClick={onApplyYaml}
+ >
+ <CheckCircle2 size={14} />
+ {isEnglish ? 'Sync to form' : '同步到表单'}
+ </button>
+ )
+ }
+ return (
+ <button className="secondary" type="button" disabled={busy !== ''} onClick={onPreview}>
+ <Eye size={14} />
+ {actionLabel(isEnglish, busy, 'preview', isEnglish ? 'Generate preview' : '生成预览')}
+ </button>
+ )
+}
+
+type PreviewMetaProps = Pick<
+ PreviewViewProps,
+ 'isEnglish' | 'activeTab' | 'yamlError' | 'yamlDefaultsApplied'
+>
+
+function RoutePreviewMeta({
+ isEnglish,
+ activeTab,
+ yamlError,
+ yamlDefaultsApplied,
+}: PreviewMetaProps) {
+ const isYaml = activeTab === 'yaml'
+ return (
+ <div className="route-preview-meta">
+ <FileCode2 size={15} />
+ <span>{isYaml ? 'route-binding.yaml' : 'api_config.yaml'}</span>
+ {isYaml ? (
+ <span className={`route-yaml-sync ${yamlSyncClass(yamlError)}`}>
+ {yamlSyncLabel(isEnglish, yamlError, yamlDefaultsApplied)}
+ </span>
+ ) : (
+ <span className="muted">{isEnglish ? 'Read only' : '只读'}</span>
+ )}
+ </div>
+ )
+}
+
+function RoutePreviewView({
+ isEnglish,
+ activeTab,
+ busy,
+ previewYaml,
+ routeYaml,
+ yamlError,
+ yamlDefaultsApplied,
+ onApplyYaml,
+ onChangeYaml,
+ onPreview,
+}: PreviewViewProps) {
+ return (
+ <section className="panel route-preview-panel">
+ <div className="panel-head">
+ <div>
+ <h2>{previewTitle(isEnglish, activeTab)}</h2>
+ <span>{previewDescription(isEnglish, activeTab)}</span>
+ </div>
+ <RoutePreviewAction
+ isEnglish={isEnglish}
+ activeTab={activeTab}
+ busy={busy}
+ yamlError={yamlError}
+ onApplyYaml={onApplyYaml}
+ onPreview={onPreview}
+ />
+ </div>
+ <RoutePreviewMeta
+ isEnglish={isEnglish}
+ activeTab={activeTab}
+ yamlError={yamlError}
+ yamlDefaultsApplied={yamlDefaultsApplied}
+ />
+ <RoutePreviewBody
+ isEnglish={isEnglish}
+ activeTab={activeTab}
+ previewYaml={previewYaml}
+ routeYaml={routeYaml}
+ yamlError={yamlError}
+ onChangeYaml={onChangeYaml}
+ />
+ </section>
+ )
+}
+
+export function RouteEditorContent({
+ isEnglish,
+ loading,
+ activeTab,
+ mode,
+ object,
+ busy,
+ diffData,
+ previewYaml,
+ routeYaml,
+ yamlError,
+ yamlDefaultsApplied,
+ options,
+ issueMessage,
+ onNameChange,
+ onEntryChange,
+ onTargetChange,
+ onParamAdd,
+ onParamUpdate,
+ onParamRemove,
+ onEnabledChange,
+ onRefreshDiff,
+ onApplyYaml,
+ onChangeYaml,
+ onPreview,
+}: ContentProps) {
+ if (loading) {
+ return (
+ <div
+ className="route-binding-loading"
+ aria-label={isEnglish ? 'Loading route' : '正在加载路由'}
+ >
+ <div className="loading-skeleton" />
+ <div className="loading-skeleton" />
+ </div>
+ )
+ }
+ if (activeTab === 'form') {
+ return (
+ <RouteFormView
+ isEnglish={isEnglish}
+ mode={mode}
+ entry={object.spec.entry}
+ name={object.metadata.name}
+ target={object.spec.target}
+ params={object.spec.params}
+ enabled={object.spec.enabled}
+ issueMessage={issueMessage}
+ entryProtocols={options?.entryProtocols || []}
+ targetProtocols={options?.targetProtocols || []}
+ httpMethods={options?.httpMethods || []}
+ paramTypes={options?.paramTypes || []}
+ onNameChange={onNameChange}
+ onPathChange={(value) => onEntryChange('path', value)}
+ onMethodChange={(value) => onEntryChange('method', value)}
+ onChange={onTargetChange}
+ onAdd={onParamAdd}
+ onUpdate={onParamUpdate}
+ onRemove={onParamRemove}
+ onEnabledChange={onEnabledChange}
+ />
+ )
+ }
+ if (activeTab === 'diff') {
+ return (
+ <RouteDiffView
+ isEnglish={isEnglish}
+ diffData={diffData}
+ busy={busy}
+ onRefresh={onRefreshDiff}
+ />
+ )
+ }
+ return (
+ <RoutePreviewView
+ isEnglish={isEnglish}
+ activeTab={activeTab}
+ busy={busy}
+ previewYaml={previewYaml}
+ routeYaml={routeYaml}
+ yamlError={yamlError}
+ yamlDefaultsApplied={yamlDefaultsApplied}
+ onApplyYaml={onApplyYaml}
+ onChangeYaml={onChangeYaml}
+ onPreview={() => onPreview()}
+ />
+ )
+}
+
+export function formatDiffValue(value: unknown) {
+ if (value === null || value === undefined) return '∅'
+ if (typeof value === 'string') return value
+ if (typeof value === 'bigint') return `${value}n`
+ if (typeof value === 'function') return `[Function ${value.name || 'anonymous'}]`
+ if (typeof value === 'symbol') return value.toString()
+ try {
+ const formatted = JSON.stringify(value, null, 2)
+ if (formatted !== undefined) return formatted
+ } catch {
+ return '<unserializable value>'
+ }
+ return '<unserializable value>'
+}
diff --git a/admin/web/src/hooks/use-resources.ts b/admin/web/src/hooks/use-resources.ts
deleted file mode 100644
index 964986a68..000000000
--- a/admin/web/src/hooks/use-resources.ts
+++ /dev/null
@@ -1,24 +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.
- */
-
-import { useQuery } from '@tanstack/react-query'
-import { resourceApi } from '../services/resource-api'
-export function useResources() {
- return useQuery({ queryKey: ['resources'], queryFn: resourceApi.list })
-}
diff --git a/admin/web/src/i18n/index.ts b/admin/web/src/i18n/index.ts
index a14b209a9..2dbdae03a 100644
--- a/admin/web/src/i18n/index.ts
+++ b/admin/web/src/i18n/index.ts
@@ -34,6 +34,13 @@ const textMessages: Record<Locale, Record<string, string>> = {
已发布: 'Published',
草稿: 'Draft',
已暂停: 'Paused',
+ 已启用: 'Enabled',
+ 已停用: 'Disabled',
+ 发布状态: 'Publication',
+ 已发布配置: 'Published config',
+ 未发布: 'Not published',
+ 草稿启用: 'Draft enabled',
+ 草稿停用: 'Draft disabled',
'由 Pixiu Admin 校验': 'Validated by Pixiu Admin',
取消: 'Cancel',
'保存中…': 'Saving…',
diff --git a/admin/web/src/services/http.ts b/admin/web/src/services/http.ts
index da9666bd0..fd82589e6 100644
--- a/admin/web/src/services/http.ts
+++ b/admin/web/src/services/http.ts
@@ -23,10 +23,17 @@ import { clearSession, readSession, redirectToLogin } from './session'
export class ApiError extends Error {
code: string
raw: string
- constructor(message: string, code = '', raw = '') {
+ issues: Array<{ path: string; code: string; message: string }>
+ constructor(
+ message: string,
+ code = '',
+ raw = '',
+ issues: Array<{ path: string; code: string; message: string }> = [],
+ ) {
super(message)
this.code = code
this.raw = raw
+ this.issues = issues
}
}
@@ -45,6 +52,58 @@ function isAuthFailure(status: number, bodyData: unknown) {
return /token|login|access|authoriz|认证|登录|权限/.test(message)
}
+function errorDetails(data: unknown) {
+ if (!data || typeof data !== 'object' || Array.isArray(data))
+ return { message: '', issues: [] as Array<{ path: string; code: string; message: string }> }
+ const value = data as { message?: unknown; issues?: unknown }
+ const issues = Array.isArray(value.issues)
+ ? value.issues.filter(
+ (issue): issue is { path: string; code: string; message: string } =>
+ Boolean(issue) &&
+ typeof issue === 'object' &&
+ typeof (issue as { path?: unknown }).path === 'string' &&
+ typeof (issue as { code?: unknown }).code === 'string' &&
+ typeof (issue as { message?: unknown }).message === 'string',
+ )
+ : []
+ return {
+ message: typeof value.message === 'string' ? value.message : '',
+ issues,
+ }
+}
+
+function primitiveString(value: unknown, fallback = '') {
+ if (typeof value === 'string') return value
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
+ return value.toString()
+ }
+ return fallback
+}
+
+function responseDataString(value: unknown, fallback = '') {
+ return primitiveString(value, fallback)
+}
+
+function httpErrorMessage(
+ data: unknown,
+ details: ReturnType<typeof errorDetails>,
+ envelopeMessage: unknown,
+ fallback: string,
+) {
+ if (typeof data === 'string') return data
+ if (details.message) return details.message
+ if (typeof envelopeMessage === 'string') return envelopeMessage
+ return fallback
+}
+
+function codeErrorMessage(data: unknown, details: ReturnType<typeof errorDetails>, code: unknown) {
+ if (typeof data === 'string') return data
+ if (details.message) return details.message
+ if (code === API_STATUS.NOT_FOUND) return '数据不存在'
+ if (code === API_STATUS.CONCURRENT) return '操作冲突,请刷新后重试'
+ return '请求失败'
+}
+
export function isNotFoundError(error: unknown) {
return error instanceof ApiError && error.code === API_STATUS.NOT_FOUND
}
@@ -58,12 +117,12 @@ export function parseArrayResponse<T>(data: unknown): T[] {
... 3765 lines suppressed ...