阶段六:完成生成契约迁移并永久关闭旁路
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
|
||||
}
|
||||
Reference in new issue
Block a user