阶段六:完成生成契约迁移并永久关闭旁路
This commit is contained in:
1 parent
5675f60e52
commit
76f4e2e87d
117 files changed
+5833
-2204
No files matched your search
+97
-73
@@ -6,22 +6,12 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/getkin/kin-openapi/openapi3"
|
||||
)
|
||||
|
||||
// routeKey 是路由方法与路径的稳定组合键。
|
||||
type routeKey struct {
|
||||
// method 是小写 HTTP 方法。
|
||||
method string
|
||||
// path 是 chi 路由路径。
|
||||
path string
|
||||
}
|
||||
|
||||
// main 加载并验证 OpenAPI 文档,同时检查真实版本化路由的双向覆盖。
|
||||
// main 加载并验证 OpenAPI 文档的静态结构;真实 chi 路由双向覆盖由 Server 契约测试执行。
|
||||
func main() {
|
||||
// root 是待检查仓库根目录,默认使用当前工作目录。
|
||||
root := "."
|
||||
@@ -43,7 +33,7 @@ func main() {
|
||||
fmt.Println("api-check: 通过")
|
||||
}
|
||||
|
||||
// check 执行规范语法、operation 元数据和路由双向覆盖检查。
|
||||
// check 执行规范语法和 operation 元数据检查。
|
||||
func check(root string) ([]string, error) {
|
||||
// specPath 是仓库中唯一 OpenAPI 契约文件路径。
|
||||
specPath := filepath.Join(root, "api", "openapi.yaml")
|
||||
@@ -63,12 +53,18 @@ func check(root string) ([]string, error) {
|
||||
item := document.Paths.Find(path)
|
||||
for method, operation := range item.Operations() { // method、operation 是当前 HTTP 方法和定义。
|
||||
method = strings.ToLower(method)
|
||||
// exceptionKind 是当前 operation 显式声明的成功响应特殊校验类型;空值表示必须具备普通成功响应。
|
||||
exceptionKind := contractSuccessExceptionKind(operation)
|
||||
if operation.OperationID == "" {
|
||||
violations = append(violations, fmt.Sprintf("%s %s 缺少 operationId", strings.ToUpper(method), path))
|
||||
}
|
||||
if operation.Responses == nil || !hasSuccessResponse(operation.Responses) {
|
||||
if operation.Responses == nil || exceptionKind == "" && !hasSuccessResponse(operation.Responses) {
|
||||
violations = append(violations, fmt.Sprintf("%s %s 缺少成功响应", strings.ToUpper(method), path))
|
||||
}
|
||||
// exceptionViolations 是特殊成功校验元数据不满足其受限语义时产生的全部错误。
|
||||
for _, exceptionViolation := range validateContractSuccessException(operation) {
|
||||
violations = append(violations, fmt.Sprintf("%s %s %s", strings.ToUpper(method), path, exceptionViolation))
|
||||
}
|
||||
if operation.Responses == nil || operation.Responses.Value("400") == nil || operation.Responses.Value("401") == nil {
|
||||
violations = append(violations, fmt.Sprintf("%s %s 缺少统一错误响应", strings.ToUpper(method), path))
|
||||
}
|
||||
@@ -77,34 +73,97 @@ func check(root string) ([]string, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// routes、err 分别是真实版本化路由集合和收集失败原因。
|
||||
routes, err := sourceRoutes(filepath.Join(root, "internal", "server"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// specRoutes 保存规范登记的路由方法和路径组合键。
|
||||
specRoutes := make(map[routeKey]struct{})
|
||||
for _, path := range document.Paths.Keys() { // path 是当前规范路径模板。
|
||||
for method := range document.Paths.Find(path).Operations() { // method 是当前规范 HTTP 方法。
|
||||
specRoutes[routeKey{method: strings.ToLower(method), path: path}] = struct{}{}
|
||||
}
|
||||
}
|
||||
for route := range routes { // route 是真实 Router 中发现的 operation。
|
||||
// exists 表示真实 operation 是否已经登记到 OpenAPI。
|
||||
if _, exists := specRoutes[route]; !exists {
|
||||
violations = append(violations, fmt.Sprintf("真实路由 %s %s 未登记到 api/openapi.yaml", strings.ToUpper(route.method), route.path))
|
||||
}
|
||||
}
|
||||
for route := range specRoutes { // route 是规范中声明的 operation。
|
||||
// exists 表示规范 operation 是否存在真实版本化路由。
|
||||
if _, exists := routes[route]; !exists {
|
||||
violations = append(violations, fmt.Sprintf("OpenAPI 登记 %s %s 不存在真实版本化路由", strings.ToUpper(route.method), route.path))
|
||||
}
|
||||
}
|
||||
sort.Strings(violations)
|
||||
return violations, nil
|
||||
}
|
||||
|
||||
// contractSuccessExceptionKind 返回 operation 显式登记的成功响应特殊校验类型;无法解析的值交给校验函数报错。
|
||||
func contractSuccessExceptionKind(operation *openapi3.Operation) string {
|
||||
if operation == nil || operation.Extensions == nil {
|
||||
return ""
|
||||
}
|
||||
// rawException、exists 分别是 YAML 扩展原值及其是否已登记。
|
||||
rawException, exists := operation.Extensions["x-contract-success-exception"]
|
||||
if !exists {
|
||||
return ""
|
||||
}
|
||||
// exception、ok 分别是扩展对象及其结构是否符合 OpenAPI 扩展的 YAML 解码结果。
|
||||
exception, ok := rawException.(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
// kind、ok 分别是特殊校验类别及其字符串类型断言结果。
|
||||
kind, ok := exception["kind"].(string)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return kind
|
||||
}
|
||||
|
||||
// validateContractSuccessException 只允许 WebSocket、二进制和永久关闭接口跳过普通 2xx 成功响应,并验证各自的强制契约。
|
||||
func validateContractSuccessException(operation *openapi3.Operation) []string {
|
||||
if operation == nil || operation.Extensions == nil {
|
||||
return nil
|
||||
}
|
||||
// rawException、exists 分别是特殊校验扩展原值及是否显式登记。
|
||||
rawException, exists := operation.Extensions["x-contract-success-exception"]
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
// exception、ok 分别是解码后的扩展对象及其结构是否有效。
|
||||
exception, ok := rawException.(map[string]any)
|
||||
if !ok {
|
||||
return []string{"x-contract-success-exception 必须是包含 kind 的对象"}
|
||||
}
|
||||
// kind、ok 分别是特殊校验类别及其是否为字符串。
|
||||
kind, ok := exception["kind"].(string)
|
||||
if !ok {
|
||||
return []string{"x-contract-success-exception.kind 必须是字符串"}
|
||||
}
|
||||
switch kind {
|
||||
case "websocket":
|
||||
if operation.Responses == nil || operation.Responses.Value("101") == nil {
|
||||
return []string{"WebSocket 特殊校验必须声明 101 协议升级响应"}
|
||||
}
|
||||
// exists 表示 WebSocket operation 是否同时登记了可校验的服务端事件 schema。
|
||||
if _, exists := operation.Extensions["x-websocket-message-schema"]; !exists {
|
||||
return []string{"WebSocket 特殊校验必须声明 x-websocket-message-schema"}
|
||||
}
|
||||
case "binary":
|
||||
if !hasBinarySuccessResponse(operation.Responses) {
|
||||
return []string{"二进制特殊校验必须声明含 binary format 的 2xx 响应"}
|
||||
}
|
||||
case "permanently_disabled":
|
||||
if hasSuccessResponse(operation.Responses) || operation.Responses == nil || operation.Responses.Value("501") == nil {
|
||||
return []string{"永久关闭特殊校验只能声明 501 错误响应,不得保留 2xx 或 101 成功响应"}
|
||||
}
|
||||
default:
|
||||
return []string{fmt.Sprintf("不支持的 x-contract-success-exception.kind %q", kind)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hasBinarySuccessResponse 判断 operation 是否声明内容格式为 binary 的普通 HTTP 成功响应。
|
||||
func hasBinarySuccessResponse(responses *openapi3.Responses) bool {
|
||||
if responses == nil {
|
||||
return false
|
||||
}
|
||||
// status 是当前待检查的 2xx 成功状态码。
|
||||
for _, status := range []string{"200", "201", "202", "204"} {
|
||||
// responseRef 是当前状态码对应的 OpenAPI 响应定义。
|
||||
responseRef := responses.Value(status)
|
||||
if responseRef == nil || responseRef.Value == nil {
|
||||
continue
|
||||
}
|
||||
// mediaType、media 分别是当前响应声明的媒体类型及其 schema 定义。
|
||||
for mediaType, media := range responseRef.Value.Content {
|
||||
if media != nil && media.Schema != nil && media.Schema.Value != nil && media.Schema.Value.Format == "binary" && !strings.HasPrefix(mediaType, "application/json") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// hasSuccessResponse 判断 operation 是否声明了至少一个合法成功或协议升级状态。
|
||||
func hasSuccessResponse(responses *openapi3.Responses) bool {
|
||||
if responses == nil {
|
||||
@@ -118,38 +177,3 @@ func hasSuccessResponse(responses *openapi3.Responses) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// sourceRoutes 从版本化 route 文件和动态订单刷新挂载点收集真实路由。
|
||||
func sourceRoutes(serverDir string) (map[routeKey]struct{}, error) {
|
||||
// methodPattern 匹配版本化文件中的静态 chi 方法调用。
|
||||
methodPattern := regexp.MustCompile(`r\.(Get|Post|Put|Patch|Delete)\("([^"\n]+)"`)
|
||||
// routes 保存扫描到的真实版本化路由。
|
||||
routes := make(map[routeKey]struct{})
|
||||
// entries、err 分别是路由目录项和读取失败原因。
|
||||
entries, err := os.ReadDir(serverDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 Server 路由目录失败: %w", err)
|
||||
}
|
||||
for _, entry := range entries { // entry 是当前版本化路由源文件目录项。
|
||||
if entry.IsDir() || !strings.HasPrefix(entry.Name(), "versioned_") || !strings.HasSuffix(entry.Name(), ".go") {
|
||||
continue
|
||||
}
|
||||
// source、readErr 分别是路由源码和读取失败原因。
|
||||
source, readErr := os.ReadFile(filepath.Join(serverDir, entry.Name()))
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf("读取路由文件 %s 失败: %w", entry.Name(), readErr)
|
||||
}
|
||||
for _, match := range methodPattern.FindAllSubmatch(source, -1) { // match 是当前静态路由匹配结果。
|
||||
// path 是匹配结果中的 chi 路由路径。
|
||||
path := string(match[2])
|
||||
if path == "/health" || strings.HasPrefix(path, "/api/v1/") {
|
||||
routes[routeKey{method: strings.ToLower(string(match[1])), path: path}] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
// mountOrderRefreshJobRoutes 使用 prefix 拼接路径,静态正则无法看到其三个 operation。
|
||||
routes[routeKey{method: "post", path: "/api/v1/orders/refresh"}] = struct{}{}
|
||||
routes[routeKey{method: "get", path: "/api/v1/orders/refresh/{job_id}"}] = struct{}{}
|
||||
routes[routeKey{method: "delete", path: "/api/v1/orders/refresh/{job_id}"}] = struct{}{}
|
||||
return routes, nil
|
||||
}
|
||||
+67
-29
@@ -1,40 +1,78 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/getkin/kin-openapi/openapi3"
|
||||
)
|
||||
|
||||
// TestSourceRoutesIncludesDynamicOrderRefresh 验证动态 prefix 挂载的订单刷新 operation 不会从路由登记中遗漏。
|
||||
func TestSourceRoutesIncludesDynamicOrderRefresh(t *testing.T) {
|
||||
// serverDir 是本测试构造的版本化路由源码目录。
|
||||
serverDir := t.TempDir()
|
||||
// source 是包含一个静态路由的最小 chi 路由源码夹具。
|
||||
source := []byte(`package server
|
||||
func mount(r any) {
|
||||
r.Get("/api/v1/session", nil)
|
||||
}
|
||||
`)
|
||||
// writeErr 是写入路由源码夹具失败的原因。
|
||||
if writeErr := os.WriteFile(filepath.Join(serverDir, "versioned_session_routes.go"), source, 0o600); writeErr != nil {
|
||||
t.Fatal(writeErr)
|
||||
// TestContractSuccessExceptionValidation 验证特殊成功校验只接受 WebSocket、二进制和永久关闭三类受限契约。
|
||||
func TestContractSuccessExceptionValidation(t *testing.T) {
|
||||
// websocketResponses 是包含 101 协议升级响应的 WebSocket 最小响应集合。
|
||||
websocketResponses := openapi3.NewResponses(openapi3.WithStatus(101, &openapi3.ResponseRef{Value: openapi3.NewResponse().WithDescription("upgrade")}))
|
||||
// websocketOperation 是登记消息 schema 的合法 WebSocket operation。
|
||||
websocketOperation := &openapi3.Operation{Responses: websocketResponses, Extensions: map[string]any{
|
||||
"x-contract-success-exception": map[string]any{"kind": "websocket"},
|
||||
"x-websocket-message-schema": map[string]any{"$ref": "#/components/schemas/Event"},
|
||||
}}
|
||||
// got 是从合法 WebSocket operation 解析出的特殊校验类别。
|
||||
if got := contractSuccessExceptionKind(websocketOperation); got != "websocket" {
|
||||
t.Fatalf("特殊类型=%q", got)
|
||||
}
|
||||
// routes、readErr 分别是收集到的路由集合和读取失败原因。
|
||||
routes, readErr := sourceRoutes(serverDir)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
// violations 保存合法 WebSocket operation 产生的结构违规,预期为空。
|
||||
if violations := validateContractSuccessException(websocketOperation); len(violations) != 0 {
|
||||
t.Fatalf("合法 WebSocket 特殊校验失败: %v", violations)
|
||||
}
|
||||
// expected 是动态订单刷新 POST operation 的稳定键。
|
||||
expected := routeKey{method: "post", path: "/api/v1/orders/refresh"}
|
||||
// exists 表示动态订单刷新 operation 是否已被发现。
|
||||
if _, exists := routes[expected]; !exists {
|
||||
t.Fatalf("动态订单刷新路由未登记: %+v", routes)
|
||||
// missingUpgradeOperation 是缺少 101 响应的 WebSocket 错误夹具。
|
||||
missingUpgradeOperation := &openapi3.Operation{Responses: openapi3.NewResponses(), Extensions: websocketOperation.Extensions}
|
||||
// violations 保存缺少升级响应时必须出现的结构违规。
|
||||
if violations := validateContractSuccessException(missingUpgradeOperation); len(violations) == 0 {
|
||||
t.Fatal("缺少 101 的 WebSocket 未被拒绝")
|
||||
}
|
||||
// staticRoute 是夹具中的静态 session operation。
|
||||
staticRoute := routeKey{method: "get", path: "/api/v1/session"}
|
||||
// exists 表示静态 session operation 是否已被发现。
|
||||
if _, exists := routes[staticRoute]; !exists {
|
||||
t.Fatalf("静态路由未登记: %+v", routes)
|
||||
// missingSchemaOperation 是缺少消息 schema 扩展的 WebSocket 错误夹具。
|
||||
missingSchemaOperation := &openapi3.Operation{Responses: websocketResponses, Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "websocket"}}}
|
||||
// violations 保存缺少事件 schema 时必须出现的结构违规。
|
||||
if violations := validateContractSuccessException(missingSchemaOperation); len(violations) == 0 {
|
||||
t.Fatal("缺少消息 schema 的 WebSocket 未被拒绝")
|
||||
}
|
||||
// binaryResponses 是包含 binary schema 的 CSV 成功响应集合。
|
||||
binaryResponses := openapi3.NewResponses(openapi3.WithStatus(200, &openapi3.ResponseRef{Value: openapi3.NewResponse().WithContent(openapi3.Content{
|
||||
"text/csv": &openapi3.MediaType{Schema: &openapi3.SchemaRef{Value: &openapi3.Schema{Format: "binary"}}},
|
||||
})}))
|
||||
// binaryOperation 是合法二进制下载 operation。
|
||||
binaryOperation := &openapi3.Operation{Responses: binaryResponses, Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "binary"}}}
|
||||
if !hasBinarySuccessResponse(binaryResponses) || len(validateContractSuccessException(binaryOperation)) != 0 {
|
||||
t.Fatal("合法二进制特殊校验失败")
|
||||
}
|
||||
// invalidBinaryOperation 是缺少 binary format 的二进制错误夹具。
|
||||
invalidBinaryOperation := &openapi3.Operation{Responses: openapi3.NewResponses(openapi3.WithStatus(200, &openapi3.ResponseRef{Value: openapi3.NewResponse()})), Extensions: binaryOperation.Extensions}
|
||||
// violations 保存二进制下载缺少 binary schema 时必须出现的结构违规。
|
||||
if violations := validateContractSuccessException(invalidBinaryOperation); len(violations) == 0 {
|
||||
t.Fatal("缺少 binary schema 的特殊校验未被拒绝")
|
||||
}
|
||||
// disabledOperation 是不声明任何 2xx、只声明 501 的永久关闭 operation。
|
||||
disabledOperation := &openapi3.Operation{Responses: openapi3.NewResponses(openapi3.WithStatus(501, &openapi3.ResponseRef{Value: openapi3.NewResponse()})), Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "permanently_disabled"}}}
|
||||
if len(validateContractSuccessException(disabledOperation)) != 0 {
|
||||
t.Fatal("合法永久关闭特殊校验失败")
|
||||
}
|
||||
// invalidDisabledOperation 是错误保留 200 成功响应的永久关闭 operation。
|
||||
invalidDisabledOperation := &openapi3.Operation{Responses: openapi3.NewResponses(
|
||||
openapi3.WithStatus(200, &openapi3.ResponseRef{Value: openapi3.NewResponse()}),
|
||||
openapi3.WithStatus(501, &openapi3.ResponseRef{Value: openapi3.NewResponse()}),
|
||||
), Extensions: disabledOperation.Extensions}
|
||||
// violations 保存永久关闭 operation 仍声明成功码时必须出现的结构违规。
|
||||
if violations := validateContractSuccessException(invalidDisabledOperation); len(violations) == 0 {
|
||||
t.Fatal("保留 200 的永久关闭 operation 未被拒绝")
|
||||
}
|
||||
// invalidKindOperation 是未登记类别的特殊校验 operation。
|
||||
invalidKindOperation := &openapi3.Operation{Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "other"}}}
|
||||
// violations 保存未知特殊校验类别必须产生的结构违规。
|
||||
if violations := validateContractSuccessException(invalidKindOperation); len(violations) == 0 {
|
||||
t.Fatal("未知特殊校验类别未被拒绝")
|
||||
}
|
||||
// malformedOperation 是扩展值不是对象的错误 operation。
|
||||
malformedOperation := &openapi3.Operation{Extensions: map[string]any{"x-contract-success-exception": "websocket"}}
|
||||
if contractSuccessExceptionKind(malformedOperation) != "" || len(validateContractSuccessException(malformedOperation)) == 0 {
|
||||
t.Fatal("格式错误的特殊校验扩展未被拒绝")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user