fix(openapi): 隔离不同根契约的递归组件引用
This commit is contained in:
1 parent
98c28520ef
commit
4f707550ba
3 files changed
+95
-1
No files matched your search
@@ -2,6 +2,7 @@ package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
@@ -68,6 +69,23 @@ func filteredContractSchema(t reflect.Type, schemas openapi3.Schemas, hidden map
|
||||
if ref == nil {
|
||||
return nil, fmt.Errorf("unsupported contract type %s", t)
|
||||
}
|
||||
// 递归组件按根契约隔离,避免不同方向或嵌入上下文产生同名不同定义。
|
||||
namespace := fmt.Sprintf("%s/%s/%t/%v", t.PkgPath(), t, response, hidden)
|
||||
names := map[string]string{}
|
||||
for name := range local {
|
||||
identity := sha256.Sum256([]byte(namespace + "/" + name))
|
||||
names[name] = fmt.Sprintf("Schema_%x", identity[:16])
|
||||
}
|
||||
visited := map[*openapi3.Schema]bool{}
|
||||
renameContractReferences(ref, names, visited)
|
||||
for _, component := range local {
|
||||
renameContractReferences(component, names, visited)
|
||||
}
|
||||
renamed := openapi3.Schemas{}
|
||||
for name, component := range local {
|
||||
renamed[names[name]] = component
|
||||
}
|
||||
local = renamed
|
||||
for name, component := range local {
|
||||
if previous := schemas[name]; previous != nil {
|
||||
left, leftErr := json.Marshal(previous)
|
||||
@@ -388,3 +406,33 @@ func setContractDefault(schema *openapi3.Schema, tag reflect.StructTag) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// renameContractReferences 只重命名本次生成的循环引用,保持原生生成器的内联和可空语义。
|
||||
// 入参:ref 为当前节点,names 为本地名称映射,visited 防止共享图重复遍历。
|
||||
func renameContractReferences(ref *openapi3.SchemaRef, names map[string]string, visited map[*openapi3.Schema]bool) {
|
||||
if ref == nil {
|
||||
return
|
||||
}
|
||||
const prefix = "#/components/schemas/"
|
||||
if strings.HasPrefix(ref.Ref, prefix) {
|
||||
if name, exists := names[strings.TrimPrefix(ref.Ref, prefix)]; exists {
|
||||
ref.Ref = prefix + name
|
||||
}
|
||||
}
|
||||
schema := ref.Value
|
||||
if schema == nil || visited[schema] {
|
||||
return
|
||||
}
|
||||
visited[schema] = true
|
||||
for _, child := range schema.Properties {
|
||||
renameContractReferences(child, names, visited)
|
||||
}
|
||||
for _, group := range []openapi3.SchemaRefs{schema.AllOf, schema.AnyOf, schema.OneOf} {
|
||||
for _, child := range group {
|
||||
renameContractReferences(child, names, visited)
|
||||
}
|
||||
}
|
||||
for _, child := range []*openapi3.SchemaRef{schema.Not, schema.Items, schema.AdditionalProperties.Schema} {
|
||||
renameContractReferences(child, names, visited)
|
||||
}
|
||||
}
|
||||
@@ -319,3 +319,49 @@ func TestOpenAPIUnsupportedReferenceAliasReturnsError(t *testing.T) {
|
||||
t.Fatal("unsupported scalar Ref alias did not return an error")
|
||||
}
|
||||
}
|
||||
|
||||
// 同一递归类型在根响应和匿名嵌入响应中会经过不同展开路径。
|
||||
type embeddedRecursiveOutput struct {
|
||||
recursiveValue
|
||||
Label string `json:"label"`
|
||||
}
|
||||
type recursiveBaseForm struct {
|
||||
Meta `path:"/recursive/base" method:"GET"`
|
||||
}
|
||||
type recursiveExtendedForm struct {
|
||||
Meta `path:"/recursive/extended" method:"GET"`
|
||||
}
|
||||
type embeddedRecursiveController struct{}
|
||||
|
||||
func (*embeddedRecursiveController) Base(*gin.Context, *recursiveBaseForm) (recursiveValue, error) {
|
||||
return recursiveValue{}, nil
|
||||
}
|
||||
func (*embeddedRecursiveController) Extended(*gin.Context, *recursiveExtendedForm) (embeddedRecursiveOutput, error) {
|
||||
return embeddedRecursiveOutput{}, nil
|
||||
}
|
||||
|
||||
// TestOpenAPIRecursiveComponentsAreIsolatedByContract 验证同一递归类型的不同根契约互不污染。
|
||||
func TestOpenAPIRecursiveComponentsAreIsolatedByContract(t *testing.T) {
|
||||
server, _ := NewServer(Config{}, Options{})
|
||||
if err := server.Group("", nil, &embeddedRecursiveController{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc, err := server.OpenAPI(OpenAPIOptions{Title: "Recursive variants", Version: "1"})
|
||||
if err != nil {
|
||||
t.Fatal(err, errors.Unwrap(err))
|
||||
}
|
||||
for _, path := range []string{"/recursive/base", "/recursive/extended"} {
|
||||
recorder := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", path, nil))
|
||||
var (
|
||||
actual any
|
||||
)
|
||||
if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := doc.Paths.Value(path).Get.Responses.Status(200).Value.Content["application/json"].Schema.Value
|
||||
if err = schema.VisitJSON(actual); err != nil {
|
||||
t.Fatalf("%s contract disagrees with wire JSON: %v", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||