Codex/model dispatch integration #2
No files matched your search
@@ -221,7 +221,7 @@ go run ./examples/openapi -out /tmp/ginframework-openapi.json
|
||||
|
||||
合并来源的语义:GET/HEAD/OPTIONS 只生成路径与查询;有 Body 的方法同时生成可选查询和可选 RequestBody。必填发生在合并、默认值、可信注入之后,因此根 Body 不使用会误拒绝其他来源的 required,而用 `x-gin-required-after-merge` 保留无条件必填清单。普通查询中带 default 的字段不强制出现。JSON Schema 的 required 只表达存在性,不能替代 validator 对零值的检查。
|
||||
|
||||
所有非空 binding 声明保留在 `x-gin-binding`。跨字段、自定义、OR、omitempty/omitnil 等规则不冒充等价的标准约束;Map keys/endkeys 的值规则也不自动推断。复杂场景以运行时校验为准,并由应用通过 Customize 补充。固定长度 Go 数组标记 `x-gin-schema-unresolved`;自定义 JSON 序列化类型标记 `x-gin-custom-json`,其形状不自动推断。any 保持开放结构。循环组件同名但定义不一致时明确失败,需使用不同 DTO 名称。没有完整未知字段、字段存在性或自定义序列化分析器。
|
||||
所有非空 binding 声明保留在 `x-gin-binding`。跨字段、自定义、OR、omitempty/omitnil 等规则不冒充等价的标准约束;Map keys/endkeys 的值规则也不自动推断。复杂场景以运行时校验为准,并由应用通过 Customize 补充。固定长度 Go 数组标记 `x-gin-schema-unresolved`;自定义 JSON 序列化类型标记 `x-gin-custom-json`,其形状不自动推断。any 保持开放结构。循环组件按根契约、输入输出方向和可信字段集合生成独立的稳定名称,同一递归 DTO 在不同嵌入上下文中不会互相覆盖。单个根契约内部仍不支持不同包中同名且定义不同的递归 DTO;此时需使用不同 DTO 名称。没有完整未知字段、字段存在性或自定义序列化分析器。
|
||||
|
||||
当前原生类型生成器不支持名称以 Ref 结尾的非结构体别名;框架会返回明确错误,避免反射 panic。此类字段先转换为普通标量对外 DTO。响应侧只推导序列化结构与属性存在性,不把输入 binding 标签当作已经执行的输出校验。
|
||||
|
||||
@@ -231,6 +231,12 @@ go run ./examples/openapi -out /tmp/ginframework-openapi.json
|
||||
|
||||
文档和 options 中的数据生成后互不共享到 Server,返回后可由调用方继续编辑;继续编辑后应再次执行 `doc.Validate(ctx)`。如需在线展示,可由应用显式注册原生 `/openapi.json` 路由提供预先序列化的字节,并自行配置访问权限;库不打包 UI、不开后台任务、不持有输出文件。现有 Routes、请求绑定、响应及认证行为均保持原契约,新增依赖固定为 kin-openapi v0.152.0。
|
||||
|
||||
### 5.4 原生路由的批次接入
|
||||
|
||||
已有业务传输适配可用 `HandleBatch(...NativeRoute)` 原子注册。NativeRoute.Metadata 提供最终方法/路径/文档信息,Handlers 是原生 Gin 链,注册时复制;冲突或冻结会拒绝整个批次,不执行应用 Handler。InputType、OutputType 可成对声明为 reflect.Type,仅用于 OpenAPI Schema,框架不重复绑定、注入、调用或套 Controller 预算。缺省响应按 Envelope 推导,SSE 或既有业务响应须通过 OpenAPIOptions.Customize 覆盖。未提供类型则保留原生未推断契约。
|
||||
|
||||
`Use(...gin.HandlerFunc)` 可在首次 Handler/Serve/Shutdown 前追加全局中间件,并重建全部既有路由链;失败原子回退。`Options.NoRoute` 显式提供应用静态资源回退或特殊 404,未配置仍使用安全 JSON 404。两项均不暴露可绕过冻结的可变 Gin Engine。框架拥有路由校验和 HTTP 生命周期,认证、业务 Hook、响应格式及资源所有权继续由应用负责。
|
||||
|
||||
## 6. 配置、日志与诊断
|
||||
|
||||
### 6.1 配置
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// NativeRoute 是应用已经完成业务策略装配的原生路由,不再触发 Controller 调用。
|
||||
type NativeRoute struct {
|
||||
Metadata `dc:"最终路径、方法及公开文档元数据"`
|
||||
Handlers []gin.HandlerFunc `json:"-" dc:"应用装配的中间件和处理器,注册时复制"`
|
||||
InputType reflect.Type `json:"-" dc:"可选 Form 类型,仅用于契约生成,不参与绑定或执行"`
|
||||
OutputType reflect.Type `json:"-" dc:"可选公开 DTO 类型,与 InputType 同时提供"`
|
||||
}
|
||||
|
||||
// HandleBatch 原子注册原生路由,复用框架的路由冲突检查和冻结边界。
|
||||
// 入参:routes 为已装配的路由;返回任一配置或冲突错误,失败不部分注册。
|
||||
// 隐式逻辑:类型仅作 OpenAPI 声明,默认按 Envelope 推导;特殊响应通过 Customize 覆盖。
|
||||
func (s *Server) HandleBatch(routes ...NativeRoute) error {
|
||||
planned := make([]route, 0, len(routes))
|
||||
for _, item := range routes {
|
||||
if len(item.Handlers) == 0 {
|
||||
return failure.Wrap(codeRouteHandler, "validate native route handler failed", errors.New("route handler is required"))
|
||||
}
|
||||
if (item.InputType == nil) != (item.OutputType == nil) {
|
||||
return failure.Wrap(codeControllerForm, "validate native route contract failed", errors.New("input and output types must be declared together"))
|
||||
}
|
||||
input := item.InputType
|
||||
if input != nil {
|
||||
for input.Kind() == reflect.Ptr {
|
||||
input = input.Elem()
|
||||
}
|
||||
if input.Kind() != reflect.Struct {
|
||||
return failure.Wrap(codeControllerForm, "validate native request contract failed", errors.New("input type must be a struct or struct pointer"))
|
||||
}
|
||||
}
|
||||
planned = append(planned, route{meta: item.Metadata, handlers: append([]gin.HandlerFunc(nil), item.Handlers...), input: input, output: item.OutputType})
|
||||
}
|
||||
return s.commit(planned)
|
||||
}
|
||||
|
||||
// Use 在启动阶段追加全局中间件,并原子重建既有路由链。
|
||||
// 入参:handlers 为明确的应用中间件;返回配置或冻结错误,不改变原引擎。
|
||||
func (s *Server) Use(handlers ...gin.HandlerFunc) error {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
if s.frozen || s.stopping {
|
||||
return failure.Wrap(codeRouteFrozen, "configure frozen HTTP middleware failed", errors.New("HTTP routes are frozen"))
|
||||
}
|
||||
if len(s.options.Middleware)+len(handlers) > 58 {
|
||||
return failure.Wrap(codeMiddlewareCount, "validate HTTP middleware count failed", errors.New("too many global middleware handlers"))
|
||||
}
|
||||
for _, handler := range handlers {
|
||||
if handler == nil {
|
||||
return failure.Wrap(codeMiddlewareHandler, "validate HTTP middleware failed", errors.New("nil global middleware"))
|
||||
}
|
||||
}
|
||||
previous := s.options.Middleware
|
||||
s.options.Middleware = append(append([]gin.HandlerFunc(nil), previous...), handlers...)
|
||||
engine, err := s.buildEngine(s.routes)
|
||||
if err != nil {
|
||||
s.options.Middleware = previous
|
||||
return err
|
||||
}
|
||||
s.engine = engine
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestNativeBatchAtomicRegistrationAndMiddlewareFreeze(t *testing.T) {
|
||||
server, _ := NewServer(Config{}, Options{NoRoute: func(ctx *gin.Context) { ctx.String(404, "application fallback") }})
|
||||
ok := func(ctx *gin.Context) { ctx.Status(204) }
|
||||
if err := server.HandleBatch(NativeRoute{Metadata: Metadata{Method: "GET", Path: "/first"}, Handlers: []gin.HandlerFunc{ok}}, NativeRoute{Metadata: Metadata{Method: "GET", Path: "/first"}, Handlers: []gin.HandlerFunc{ok}}); err == nil {
|
||||
t.Fatal("duplicate batch accepted")
|
||||
}
|
||||
if len(server.Routes()) != 0 {
|
||||
t.Fatal("failed batch partially registered")
|
||||
}
|
||||
if err := server.HandleBatch(NativeRoute{Metadata: Metadata{Method: "GET", Path: "/first"}, Handlers: []gin.HandlerFunc{ok}, InputType: reflect.TypeOf(flowForm{}), OutputType: reflect.TypeOf(exampleOutput{})}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := server.Use(func(ctx *gin.Context) { ctx.Header("X-Application", "ready"); ctx.Next() }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc, err := server.OpenAPI(OpenAPIOptions{Title: "Native", Version: "1"})
|
||||
if err != nil || doc.Paths.Value("/first").Get.Responses.Status(200) == nil {
|
||||
t.Fatal("typed native contract lost", err)
|
||||
}
|
||||
handler := server.Handler()
|
||||
for _, path := range []string{"/first", "/missing"} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest("GET", path, nil))
|
||||
if recorder.Header().Get("X-Application") != "ready" {
|
||||
t.Fatal("late middleware not applied")
|
||||
}
|
||||
if path == "/missing" && recorder.Body.String() != "application fallback" {
|
||||
t.Fatal("application fallback lost")
|
||||
}
|
||||
}
|
||||
if server.Use(ok) == nil || server.Handle("GET", "/late", ok) == nil {
|
||||
t.Fatal("runtime registration was not frozen")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -45,10 +45,7 @@ type TrustedField func(ctx *gin.Context) (any, error)
|
||||
// 入参:method 为大写 HTTP 方法,routePath 为完整路径,handlers 为中间件和处理器。
|
||||
// 返回:路由冲突、配置无效或服务已冻结时返回错误,不部分注册。
|
||||
func (s *Server) Handle(method string, routePath string, handlers ...gin.HandlerFunc) error {
|
||||
if len(handlers) == 0 {
|
||||
return failure.Wrap(codeRouteHandler, "validate native route handler failed", errors.New("route handler is required"))
|
||||
}
|
||||
return s.commit([]route{{meta: Metadata{Method: method, Path: routePath}, handlers: append([]gin.HandlerFunc(nil), handlers...)}})
|
||||
return s.HandleBatch(NativeRoute{Metadata: Metadata{Method: method, Path: routePath}, Handlers: handlers})
|
||||
}
|
||||
|
||||
// Group 解析 Controller 的 Form/Meta 方法并作为一个批次注册。
|
||||
@@ -277,9 +274,13 @@ func (s *Server) buildEngine(routes []route) (engine *gin.Engine, err error) {
|
||||
}
|
||||
engine.Use(s.initialize)
|
||||
engine.Use(s.options.Middleware...)
|
||||
if s.options.NoRoute != nil {
|
||||
engine.NoRoute(s.options.NoRoute)
|
||||
} else {
|
||||
engine.NoRoute(func(ctx *gin.Context) {
|
||||
s.writeResult(ctx, nil, &PublicError{Code: 404, Message: "Not Found", Status: 404}, 0)
|
||||
})
|
||||
}
|
||||
for _, item := range routes {
|
||||
if item.meta.Path == "" || !strings.HasPrefix(item.meta.Path, "/") || item.meta.Method == "" {
|
||||
return nil, failure.Wrap(codeRoutePath, "validate HTTP route path failed", errors.New("method and absolute route path are required"))
|
||||
|
||||
@@ -38,6 +38,7 @@ type Options struct {
|
||||
Middleware []gin.HandlerFunc `json:"-" dc:"业务认证等全局中间件,启动时复制"`
|
||||
ErrorMapper ErrorMapper `json:"-" dc:"业务错误到公开响应的转换函数"`
|
||||
AccessLogger *zap.Logger `json:"-" dc:"访问日志实例,nil 表示关闭"`
|
||||
NoRoute gin.HandlerFunc `json:"-" dc:"应用可选的未匹配路由处理器,未配置使用安全 404"`
|
||||
}
|
||||
|
||||
// Server 拥有单个 Gin 引擎及 HTTP 生命周期,不拥有数据库和业务协程。
|
||||
|
||||