阶段六:完成生成契约迁移并永久关闭旁路
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("格式错误的特殊校验扩展未被拒绝")
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
// TestHTTPResponseContractBoundary 验证 HTTP 契约扫描会拒绝动态 map 和直接 map 响应。
|
||||
func TestHTTPResponseContractBoundary(t *testing.T) {
|
||||
// fset 是模拟 Server 源码的文件位置集合。
|
||||
|
||||
@@ -100,6 +100,68 @@ func checkActivatedRepositoryGates(root string, activeStage int) []violation {
|
||||
}
|
||||
if architectureStageEnabled(activeStage, architectureStageClosure) {
|
||||
violations = append(violations, checkQualityArchitecture(root)...)
|
||||
violations = append(violations, checkOpenAPIContractClosure(root)...)
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkOpenAPIContractClosure 永久禁止手写 transport 汇总、生成类型越过契约层和旧 HTTP 请求旁路回流。
|
||||
func checkOpenAPIContractClosure(root string) []violation {
|
||||
// violations 保存 OpenAPI 契约闭环的物理文件和依赖方向违规。
|
||||
var violations []violation
|
||||
// frontendRoot 是前端源码根目录,用于定位只读生成类型和 feature adapter。
|
||||
frontendRoot := filepath.Join(root, "frontend")
|
||||
// legacyTransportPath 是阶段六必须永久删除的手写 DTO 汇总文件。
|
||||
legacyTransportPath := filepath.Join(frontendRoot, "shared", "api-contract", "transport.ts")
|
||||
// statErr 表示旧手写 DTO 汇总文件是否仍然存在。
|
||||
if _, statErr := os.Stat(legacyTransportPath); statErr == nil {
|
||||
violations = append(violations, violation{file: "frontend/shared/api-contract/transport.ts", line: 1, message: "阶段六禁止重新引入手写 transport DTO 汇总;必须使用生成类型或所属 feature UI 模型"})
|
||||
}
|
||||
// importPattern 提取静态 import 和 export-from 的模块路径,避免通过 re-export 隐藏旁路。
|
||||
importPattern := regexp.MustCompile(`(?m)(?:from\s+)["']([^"']+)["']`)
|
||||
// walkErr 是扫描前端生产源码时的文件系统错误。
|
||||
walkErr := filepath.WalkDir(frontendRoot, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if entry.IsDir() {
|
||||
if entry.Name() == "node_modules" || entry.Name() == "coverage" || entry.Name() == "dist" {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !isFrontendProductionPath(path) {
|
||||
return nil
|
||||
}
|
||||
// relativePath 是当前源码相对于 frontend 的稳定路径。
|
||||
relativePath, relativeErr := filepath.Rel(frontendRoot, path)
|
||||
if relativeErr != nil {
|
||||
return relativeErr
|
||||
}
|
||||
relativePath = filepath.ToSlash(relativePath)
|
||||
// source、readErr 分别保存源码文本及读取失败原因。
|
||||
source, readErr := os.ReadFile(path)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
// sourceText 是当前文件的字符串视图,供稳定依赖检查使用。
|
||||
sourceText := string(source)
|
||||
// match 是当前静态导入或再导出的完整正则匹配结果。
|
||||
for _, match := range importPattern.FindAllStringSubmatch(sourceText, -1) {
|
||||
// specifier 是当前静态导入或再导出的模块路径。
|
||||
specifier := match[1]
|
||||
if strings.HasSuffix(specifier, "/transport") || strings.HasSuffix(specifier, "/transport.ts") {
|
||||
violations = append(violations, violation{file: "frontend/" + relativePath, line: sourceLineAt(source, strings.Index(sourceText, match[0])), message: "阶段六禁止引用手写 transport DTO;请改用生成契约或 feature UI 模型"})
|
||||
}
|
||||
// shared/api-contract 是生成类型的唯一宿主;feature 只能经自己的 api adapter 使用类型。
|
||||
if strings.Contains(specifier, "generated/schema") && !strings.HasPrefix(relativePath, "shared/api-contract/") {
|
||||
violations = append(violations, violation{file: "frontend/" + relativePath, line: sourceLineAt(source, strings.Index(sourceText, match[0])), message: "生成 OpenAPI 类型不得越过 shared 契约层直接进入 feature、组件或 Hook"})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if walkErr != nil {
|
||||
violations = append(violations, violation{file: "frontend", line: 1, message: fmt.Sprintf("扫描 OpenAPI 契约闭环失败: %v", walkErr)})
|
||||
}
|
||||
return violations
|
||||
}
|
||||
@@ -243,6 +305,8 @@ func checkReactArchitecture(root string) []violation {
|
||||
}
|
||||
// modulePattern 提取静态 import、re-export 和动态 import 的模块路径。
|
||||
modulePattern := regexp.MustCompile(`(?m)(?:from\s+|import\s*\()\s*["']([^"']+)["']`)
|
||||
// legacyHTTPImportPattern 仅匹配旧 HTTP client 的具名导入,用于永久禁止 feature 恢复未类型化请求旁路。
|
||||
legacyHTTPImportPattern := regexp.MustCompile(`(?s)import\s*\{([^}]*)\}\s*from\s*["'][^"']*shared/http/client["']`)
|
||||
// walkErr 是遍历前端生产源码时的文件系统错误。
|
||||
walkErr := filepath.WalkDir(frontendRoot, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
@@ -270,6 +334,19 @@ func checkReactArchitecture(root string) []violation {
|
||||
}
|
||||
// sourceText 是用于模块和网络边界匹配的源码文本。
|
||||
sourceText := string(source)
|
||||
// legacyMatch 是当前 feature 对旧 HTTP client 的具名导入;只允许错误类型和请求控制类型继续复用。
|
||||
for _, legacyMatch := range legacyHTTPImportPattern.FindAllStringSubmatch(sourceText, -1) {
|
||||
// importedNames 保存去除 type 与别名后的本地导入名称。
|
||||
importedNames := strings.Split(legacyMatch[1], ",")
|
||||
// importedName 是当前待核验的旧 client 导入名称。
|
||||
for _, importedName := range importedNames {
|
||||
// normalizedName 是去除 TypeScript type 前缀与别名后的源导出名称。
|
||||
normalizedName := strings.TrimSpace(strings.Split(strings.TrimPrefix(strings.TrimSpace(importedName), "type "), " as ")[0])
|
||||
if normalizedName == "get" || normalizedName == "post" || normalizedName == "put" || normalizedName == "del" || normalizedName == "postForm" {
|
||||
violations = append(violations, violation{file: "frontend/" + relativePath, line: sourceLineAt(source, strings.Index(sourceText, legacyMatch[0])), message: "feature 禁止导入旧 HTTP get/post/put/del/postForm;必须使用生成契约客户端"})
|
||||
}
|
||||
}
|
||||
}
|
||||
if relativePath != "shared/http/client.ts" && relativePath != "shared/api-contract/client.ts" && (strings.Contains(sourceText, "fetch(") || regexp.MustCompile(`\baxios\b`).MatchString(sourceText)) {
|
||||
violations = append(violations, violation{file: "frontend/" + relativePath, line: 1, message: "前端生产代码不得绕过共享 HTTP 契约客户端直接请求网络"})
|
||||
}
|
||||
|
||||
@@ -213,3 +213,34 @@ func TestQualityArchitectureGate(t *testing.T) {
|
||||
t.Fatalf("violations=%+v", violations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAPIContractClosureGate 验证阶段六拒绝手写 DTO 汇总和 feature 直接读取生成 schema。
|
||||
func TestOpenAPIContractClosureGate(t *testing.T) {
|
||||
// root 是承载阶段六违规样例的独立临时仓库。
|
||||
root := t.TempDir()
|
||||
// transportPath 是模拟被错误恢复的旧手写 DTO 汇总文件。
|
||||
transportPath := filepath.Join(root, "frontend", "shared", "api-contract", "transport.ts")
|
||||
// mkdirErr 表示创建旧 DTO 样例目录失败的原因。
|
||||
if mkdirErr := os.MkdirAll(filepath.Dir(transportPath), 0o755); mkdirErr != nil {
|
||||
t.Fatal(mkdirErr)
|
||||
}
|
||||
// writeErr 表示写入旧 DTO 样例失败的原因。
|
||||
if writeErr := os.WriteFile(transportPath, []byte("export interface Legacy {}\n"), 0o600); writeErr != nil {
|
||||
t.Fatal(writeErr)
|
||||
}
|
||||
// featurePath 是绕过 adapter 直接导入生成 schema 的 feature UI 样例。
|
||||
featurePath := filepath.Join(root, "frontend", "app", "features", "items", "page.tsx")
|
||||
// mkdirErr 表示创建 feature 样例目录失败的原因。
|
||||
if mkdirErr := os.MkdirAll(filepath.Dir(featurePath), 0o755); mkdirErr != nil {
|
||||
t.Fatal(mkdirErr)
|
||||
}
|
||||
// writeErr 表示写入 feature 旁路样例失败的原因。
|
||||
if writeErr := os.WriteFile(featurePath, []byte("import type { components } from '../../../shared/api-contract/generated/schema';\ntype Row = components['schemas']['ItemListResponse'];\n"), 0o600); writeErr != nil {
|
||||
t.Fatal(writeErr)
|
||||
}
|
||||
// violations 是闭环门禁必须同时报告的两类绕过。
|
||||
violations := checkOpenAPIContractClosure(root)
|
||||
if len(violations) != 2 {
|
||||
t.Fatalf("violations=%+v", violations)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user