阶段七:完成 React Feature 化与前置重构收口
This commit is contained in:
1 parent
375e84d663
commit
1a228dc35c
305 files changed
+14179
-5431
No files matched your search
@@ -0,0 +1,161 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestFrontendProductionRequestsUseVersionedAPI 清点 React 生产源码,确保业务请求不再调用旧路径。
|
||||
func TestFrontendProductionRequestsUseVersionedAPI(t *testing.T) {
|
||||
// root 是当前仓库根目录,测试从任意 Go 包工作目录向上解析它。
|
||||
root := repositoryRootForContractTest(t)
|
||||
// frontendRoot 是需要审计的前端源码目录。
|
||||
frontendRoot := filepath.Join(root, "frontend")
|
||||
// legacyFragments 是旧 HTTP 入口在字符串字面量中的稳定前缀集合。
|
||||
legacyFragments := []string{
|
||||
"'/login", `"/login`, "`/login",
|
||||
"'/verify", `"/verify`, "`/verify",
|
||||
"'/logout", `"/logout`, "`/logout",
|
||||
"'/change-password", `"/change-password`, "`/change-password",
|
||||
"'/account/credentials", `"/account/credentials`, "`/account/credentials",
|
||||
"'/cookies", `"/cookies`, "`/cookies",
|
||||
"'/items", `"/items`, "`/items",
|
||||
"'/automation-rules", `"/automation-rules`, "`/automation-rules",
|
||||
"'/automation-issues", `"/automation-issues`, "`/automation-issues",
|
||||
"'/automation-runs", `"/automation-runs`, "`/automation-runs",
|
||||
"'/automation-pending-tasks", `"/automation-pending-tasks`, "`/automation-pending-tasks",
|
||||
"'/api/orders", `"/api/orders`, "`/api/orders",
|
||||
"'/system-settings", `"/system-settings`, "`/system-settings",
|
||||
"'/user-settings", `"/user-settings`, "`/user-settings",
|
||||
"'/ai-reply-settings", `"/ai-reply-settings`, "`/ai-reply-settings",
|
||||
"'/ai-models", `"/ai-models`, "`/ai-models",
|
||||
"'/cards", `"/cards`, "`/cards",
|
||||
"'/notification-channels", `"/notification-channels`, "`/notification-channels",
|
||||
"'/message-notifications", `"/message-notifications`, "`/message-notifications",
|
||||
"'/api/chat", `"/api/chat`, "`/api/chat",
|
||||
"'/keywords", `"/keywords`, "`/keywords",
|
||||
"'/keywords-with-item-id", `"/keywords-with-item-id`, "`/keywords-with-item-id",
|
||||
"'/keywords-with-type", `"/keywords-with-type`, "`/keywords-with-type",
|
||||
"'/item-reply", `"/item-reply`, "`/item-reply",
|
||||
"'/itemReplays", `"/itemReplays`, "`/itemReplays",
|
||||
"'/default-replies", `"/default-replies`, "`/default-replies",
|
||||
"'/api/default-reply", `"/api/default-reply`, "`/api/default-reply",
|
||||
"'/api/account-tasks", `"/api/account-tasks`, "`/api/account-tasks",
|
||||
"'/admin/", `"/admin/`, "`/admin/",
|
||||
"'/change-admin-password", `"/change-admin-password`, "`/change-admin-password",
|
||||
"'/dashboard/stats", `"/dashboard/stats`, "`/dashboard/stats",
|
||||
"'/analytics/", `"/analytics/`, "`/analytics/",
|
||||
"'/qr-login", `"/qr-login`, "`/qr-login",
|
||||
"'/password-login", `"/password-login`, "`/password-login",
|
||||
}
|
||||
// findings 保存命中的文件、行号和旧路径片段。
|
||||
var findings []string
|
||||
// walkErr 表示遍历前端生产源码时遇到的文件系统错误。
|
||||
walkErr := filepath.WalkDir(frontendRoot, func(path string, entry os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() {
|
||||
if entry.Name() == "node_modules" || entry.Name() == "coverage" || entry.Name() == "dist" {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !isFrontendProductionSource(path) {
|
||||
return nil
|
||||
}
|
||||
// file 是当前待扫描的前端生产源码文件;openErr 表示打开失败原因。
|
||||
file, openErr := os.Open(path)
|
||||
if openErr != nil {
|
||||
return openErr
|
||||
}
|
||||
defer file.Close()
|
||||
// lineNumber 是当前源码行的 1-based 行号。
|
||||
lineNumber := 0
|
||||
// scanner 按行读取当前前端源码,供旧路径静态清点使用。
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
lineNumber++
|
||||
// line 是当前源码文本,用于检查是否包含历史 API 路径。
|
||||
line := scanner.Text()
|
||||
// fragment 是当前待检查的历史 API 路径片段。
|
||||
for _, fragment := range legacyFragments {
|
||||
if strings.Contains(line, fragment) {
|
||||
findings = append(findings, fmt.Sprintf("%s:%d 命中 %s", filepath.ToSlash(path), lineNumber, fragment))
|
||||
}
|
||||
}
|
||||
}
|
||||
return scanner.Err()
|
||||
})
|
||||
if walkErr != nil {
|
||||
t.Fatal(walkErr)
|
||||
}
|
||||
if len(findings) != 0 {
|
||||
t.Fatalf("前端生产源码存在旧 API 调用:\n%s", strings.Join(findings, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestCompatibilityMatrixDocumentsSunsetConditions 验证兼容清单保留调用方证据和删除条件。
|
||||
func TestCompatibilityMatrixDocumentsSunsetConditions(t *testing.T) {
|
||||
// root 是当前仓库根目录,供读取架构契约文档使用。
|
||||
root := repositoryRootForContractTest(t)
|
||||
// matrixPath 是 API 兼容边界清单的绝对路径。
|
||||
matrixPath := filepath.Join(root, "docs", "architecture", "api-compatibility-matrix.md")
|
||||
// raw 是兼容清单原文,测试只检查治理字段是否仍被记录。
|
||||
raw, err := os.ReadFile(matrixPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// requiredPhrases 是阶段三调用方审计必须保留的证据和删除条件短语。
|
||||
requiredPhrases := []string{
|
||||
"阶段 3 调用方审计",
|
||||
"TestFrontendProductionRequestsUseVersionedAPI",
|
||||
"外部调用方",
|
||||
"Sunset",
|
||||
"连续两个发布周期",
|
||||
"回滚",
|
||||
}
|
||||
for _, phrase := range requiredPhrases { // phrase 是当前待核对的治理短语。
|
||||
if !strings.Contains(string(raw), phrase) {
|
||||
t.Errorf("兼容清单缺少治理短语 %q", phrase)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// isFrontendProductionSource 判断文件是否属于需要审计的前端生产源码。
|
||||
func isFrontendProductionSource(path string) bool {
|
||||
// ext 是当前文件扩展名,用于排除非 TypeScript 源码。
|
||||
ext := filepath.Ext(path)
|
||||
if ext != ".ts" && ext != ".tsx" {
|
||||
return false
|
||||
}
|
||||
// base 是当前文件名,用于排除测试与规格文件。
|
||||
base := filepath.Base(path)
|
||||
return !strings.Contains(base, ".test.") && !strings.Contains(base, ".spec.")
|
||||
}
|
||||
|
||||
// repositoryRootForContractTest 从当前测试目录向上寻找包含 go.mod 的仓库根目录。
|
||||
func repositoryRootForContractTest(t *testing.T) string {
|
||||
t.Helper()
|
||||
// current 是当前测试进程的工作目录绝对路径。
|
||||
current, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for {
|
||||
// statErr 表示当前目录是否存在模块声明文件。
|
||||
if _, statErr := os.Stat(filepath.Join(current, "go.mod")); statErr == nil {
|
||||
return current
|
||||
}
|
||||
// parent 是向上搜索仓库根目录时的父目录。
|
||||
parent := filepath.Dir(current)
|
||||
if parent == current {
|
||||
t.Fatal("无法定位仓库根目录")
|
||||
}
|
||||
current = parent
|
||||
}
|
||||
}
|
||||
@@ -132,6 +132,7 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
|
||||
}
|
||||
}
|
||||
violations = append(violations, checkApplicationTypeLeaks(relativePath, syntax, fset)...)
|
||||
violations = append(violations, checkHTTPResponseContracts(relativePath, syntax, fset)...)
|
||||
if strings.HasPrefix(filepath.ToSlash(relativePath), "internal/server/") && !strings.HasSuffix(relativePath, "_repository.go") {
|
||||
// sourceLine 是裸 BeginTx 调用首次出现的源码行号。
|
||||
sourceLine := firstLineContaining(string(source), ".DB.BeginTx(")
|
||||
@@ -146,6 +147,121 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
|
||||
return violations, nil
|
||||
}
|
||||
|
||||
// checkHTTPResponseContracts 检查 Server 对外响应是否使用具名 DTO,并阻止动态 map 绕过契约边界。
|
||||
func checkHTTPResponseContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前 Server 文件发现的 HTTP 契约问题。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// typedNode 是当前遍历到的 AST 节点,用于识别 HTTP 契约声明或调用。
|
||||
switch typedNode := node.(type) {
|
||||
case *ast.TypeSpec:
|
||||
if !isHTTPContractTypeName(typedNode.Name.Name) {
|
||||
return true
|
||||
}
|
||||
if (typedNode.Name.Name == "settingsResponse" || containsDynamicMapType(typedNode.Type)) &&
|
||||
!isControlledDynamicResponseType(typedNode.Name.Name) {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(typedNode.Pos()).Line,
|
||||
message: fmt.Sprintf("HTTP 契约类型 %s 禁止使用动态 map,请定义具名 DTO 字段", typedNode.Name.Name),
|
||||
})
|
||||
}
|
||||
case *ast.CallExpr:
|
||||
if !isWriteJSONCall(typedNode) || len(typedNode.Args) < 3 {
|
||||
return true
|
||||
}
|
||||
// responseArg 是 writeJSON 的响应值参数,必须是具名 DTO 或受控类型。
|
||||
responseArg := typedNode.Args[2]
|
||||
if isDynamicMapLiteral(responseArg) {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(responseArg.Pos()).Line,
|
||||
message: "HTTP 响应禁止直接写入动态 map,请使用具名 DTO",
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// isControlledDynamicResponseType 判断已登记的动态键兼容响应,避免本阶段改变旧客户端 JSON 形状。
|
||||
func isControlledDynamicResponseType(name string) bool {
|
||||
// 这些类型的键来自账号 ID、触发类型或设置名称;只有完成外部调用方审计后才允许在后续阶段删除。
|
||||
switch name {
|
||||
case "settingsResponse", "notificationBindingListResponse", "automationRulePageResponse":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// isHTTPContractTypeName 判断类型名称是否属于 Server 的 HTTP 响应契约。
|
||||
func isHTTPContractTypeName(name string) bool {
|
||||
// lowerName 统一大小写,兼容 Response、DTO、Envelope 和 Result 的命名习惯。
|
||||
lowerName := strings.ToLower(name)
|
||||
return strings.HasSuffix(lowerName, "response") || strings.HasSuffix(lowerName, "dto") ||
|
||||
strings.HasSuffix(lowerName, "envelope") || strings.HasSuffix(lowerName, "result")
|
||||
}
|
||||
|
||||
// containsDynamicMapType 递归识别以 any/interface{} 为值的动态 map,保留已有键值兼容契约。
|
||||
func containsDynamicMapType(expr ast.Expr) bool {
|
||||
// typedExpr 是当前递归检查的 AST 类型表达式。
|
||||
switch typedExpr := expr.(type) {
|
||||
case *ast.MapType:
|
||||
return isAnyType(typedExpr.Value)
|
||||
case *ast.ArrayType:
|
||||
return containsDynamicMapType(typedExpr.Elt)
|
||||
case *ast.StarExpr:
|
||||
return containsDynamicMapType(typedExpr.X)
|
||||
case *ast.StructType:
|
||||
// field 是当前结构体字段,需继续检查其元素类型。
|
||||
for _, field := range typedExpr.Fields.List {
|
||||
if containsDynamicMapType(field.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isAnyType 判断表达式是否为 Go 的 any 或空接口,用于识别无稳定字段边界的响应 map。
|
||||
func isAnyType(expr ast.Expr) bool {
|
||||
// ident 是表达式的标识符形式;ok 表示断言成功。
|
||||
if ident, ok := expr.(*ast.Ident); ok {
|
||||
return ident.Name == "any" || ident.Name == "interface{}"
|
||||
}
|
||||
// interfaceType 是表达式的接口类型形式;ok 表示断言成功。
|
||||
if interfaceType, ok := expr.(*ast.InterfaceType); ok {
|
||||
return interfaceType.Methods != nil && len(interfaceType.Methods.List) == 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isWriteJSONCall 判断调用是否为 Server 的统一 JSON 响应写入函数。
|
||||
func isWriteJSONCall(call *ast.CallExpr) bool {
|
||||
// functionName 是调用目标的简单函数名。
|
||||
functionName, ok := call.Fun.(*ast.Ident)
|
||||
return ok && functionName.Name == "writeJSON"
|
||||
}
|
||||
|
||||
// isDynamicMapLiteral 判断表达式是否直接构造 map 响应,避免匿名契约逃逸静态检查。
|
||||
func isDynamicMapLiteral(expr ast.Expr) bool {
|
||||
// composite 是表达式的复合字面量;ok 表示断言成功。
|
||||
composite, ok := expr.(*ast.CompositeLit)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
// isMap 表示复合字面量是否直接构造动态 map。
|
||||
_, isMap := composite.Type.(*ast.MapType)
|
||||
return isMap
|
||||
}
|
||||
|
||||
// checkApplicationTypeLeaks 检查应用 Port 是否泄露数据库、事务或 Server 类型。
|
||||
func checkApplicationTypeLeaks(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
if !strings.HasPrefix(filepath.ToSlash(relativePath), "internal/application/") {
|
||||
@@ -210,7 +326,7 @@ func isForbiddenServerLowLevelImport(filePath, importedPath string) bool {
|
||||
if !strings.HasPrefix(filePath, "internal/server/") || strings.HasSuffix(filePath, "_test.go") {
|
||||
return false
|
||||
}
|
||||
if importedPath != "internal/db" && !strings.HasPrefix(importedPath, "internal/db/") &&
|
||||
if importedPath != "database/sql" && importedPath != "internal/db" && !strings.HasPrefix(importedPath, "internal/db/") &&
|
||||
importedPath != "internal/xianyu" && !strings.HasPrefix(importedPath, "internal/xianyu/") &&
|
||||
importedPath != "internal/browser" && !strings.HasPrefix(importedPath, "internal/browser/") {
|
||||
return false
|
||||
|
||||
@@ -6,6 +6,81 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestHTTPResponseContractBoundary 验证 HTTP 契约扫描会拒绝动态 map 和直接 map 响应。
|
||||
func TestHTTPResponseContractBoundary(t *testing.T) {
|
||||
// fset 是模拟 Server 源码的文件位置集合。
|
||||
fset := token.NewFileSet()
|
||||
// syntax、err 是同时包含 map 响应类型和直接 map 写入的模拟 Server 文件。
|
||||
syntax, err := parser.ParseFile(fset, "response.go", []byte(`package server
|
||||
type badResponse struct { Rows []map[string]any }
|
||||
func handler(w any) { writeJSON(w, 200, map[string]any{"ok": true}) }
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// violations 是动态响应契约的扫描结果。
|
||||
violations := checkHTTPResponseContracts("internal/server/response.go", syntax, fset)
|
||||
if len(violations) != 2 {
|
||||
t.Fatalf("violations=%+v", violations)
|
||||
}
|
||||
// cleanSyntax 是只使用具名字段的模拟 Server 文件。
|
||||
cleanSyntax, err := parser.ParseFile(fset, "clean.go", []byte(`package server
|
||||
type goodResponse struct { Rows []goodRow }
|
||||
type goodRow struct { ID string }
|
||||
func handler(w any) { writeJSON(w, 200, goodResponse{}) }
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// cleanViolations 是合规响应契约的扫描结果。
|
||||
cleanViolations := checkHTTPResponseContracts("internal/server/clean.go", cleanSyntax, fset)
|
||||
if len(cleanViolations) != 0 {
|
||||
t.Fatalf("clean violations=%+v", cleanViolations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestControlledDynamicResponseTypes 验证已登记的兼容动态键不会被阶段三门禁误判。
|
||||
func TestControlledDynamicResponseTypes(t *testing.T) {
|
||||
// fset 是兼容响应模拟源码的文件位置集合。
|
||||
fset := token.NewFileSet()
|
||||
// syntax、err 是包含既有动态键响应的模拟 Server 文件。
|
||||
syntax, err := parser.ParseFile(fset, "compat.go", []byte(`package server
|
||||
type settingsResponse map[string]string
|
||||
type notificationBindingListResponse map[string][]bindingRow
|
||||
type automationRulePageResponse struct { TriggerCounts map[string]int }
|
||||
type bindingRow struct { ID string }
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// violations 是兼容响应扫描结果;现有键形状必须继续保留。
|
||||
violations := checkHTTPResponseContracts("internal/server/compat.go", syntax, fset)
|
||||
if len(violations) != 0 {
|
||||
t.Fatalf("controlled response violations=%+v", violations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHTTPResponseContractScope 验证架构扫描不会误伤测试代码和非 Server 包。
|
||||
func TestHTTPResponseContractScope(t *testing.T) {
|
||||
// fset 是模拟源代码的文件位置集合。
|
||||
fset := token.NewFileSet()
|
||||
// syntax、err 是包含动态 map 的模拟文件。
|
||||
syntax, err := parser.ParseFile(fset, "response_test.go", []byte(`package server
|
||||
type testResponse map[string]any
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// got 是测试文件被扫描出的架构违规列表。
|
||||
if got := checkHTTPResponseContracts("internal/server/response_test.go", syntax, fset); len(got) != 0 {
|
||||
t.Fatalf("test-file violations=%+v", got)
|
||||
}
|
||||
// got 是非 Server 文件被扫描出的架构违规列表。
|
||||
if got := checkHTTPResponseContracts("internal/application/response.go", syntax, fset); len(got) != 0 {
|
||||
t.Fatalf("non-server violations=%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeImportPath 验证架构检查器能够识别当前模块的内部包路径。
|
||||
func TestNormalizeImportPath(t *testing.T) {
|
||||
if got /* got 是规范化后的导入路径。 */ := normalizeImportPath("xianyu-go/internal/db"); got != "internal/db" {
|
||||
@@ -40,6 +115,9 @@ func TestServerLowLevelBoundary(t *testing.T) {
|
||||
if !isForbiddenServerLowLevelImport("internal/server/new_service.go", "internal/db") {
|
||||
t.Fatal("新增 Server 低层依赖必须被门禁拒绝")
|
||||
}
|
||||
if !isForbiddenServerLowLevelImport("internal/server/unit_of_work.go", "database/sql") {
|
||||
t.Fatal("Server 不得暴露 database/sql 事务类型")
|
||||
}
|
||||
if isForbiddenServerLowLevelImport("internal/server/new_service_test.go", "internal/db") {
|
||||
t.Fatal("测试文件不应被生产依赖门禁阻断")
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user