From 2110d6c431366e842933b4b48ecbac50c67ba80c Mon Sep 17 00:00:00 2001 From: Christ Date: Sat, 15 Aug 2026 03:54:03 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=B6=E6=AE=B5=E4=B9=9D=EF=BC=9A=E5=BB=BA?= =?UTF-8?q?=E7=AB=8B=E6=9E=B6=E6=9E=84=E4=BE=9D=E8=B5=96=E9=97=A8=E7=A6=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 3 + Makefile | 8 +- docs/architecture/refactoring-master-plan.md | 9 +- tools/architecturecheck/main.go | 169 +++++++++++++++++++ 4 files changed, 183 insertions(+), 6 deletions(-) create mode 100644 tools/architecturecheck/main.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0928a10..5ec60ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,9 @@ jobs: - name: 检查中文注释 run: go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json + - name: 检查架构依赖 + run: go run ./tools/architecturecheck + - name: 运行 go vet run: go vet ./... diff --git a/Makefile b/Makefile index ff88796..22add46 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ GO ?= go GOLANGCI_LINT ?= golangci-lint -.PHONY: build build-int build-browser-install build-tray test test-server test-server-race test-int vet lint cover tidy frontend fmt comments comments-baseline check +.PHONY: build build-int build-browser-install build-tray test test-server test-server-race test-int vet lint architecture cover tidy frontend fmt comments comments-baseline check ## build: 编译 server(默认,跳过 integration build tag) build: @@ -45,6 +45,10 @@ vet: lint: $(GOLANGCI_LINT) run ./... +## architecture: 检查 Go 低层依赖方向和 Server 事务边界 +architecture: + $(GO) run ./tools/architecturecheck + ## cover: 生成覆盖率报告 cover: $(GO) test -coverprofile=cover.out ./... && $(GO) tool cover -func=cover.out | tail -1 @@ -73,4 +77,4 @@ comments-baseline: node frontend/scripts/check-comments.mjs --mode baseline --root frontend --baseline .commentlint/frontend-baseline.json ## check: 本地提交前全套检查(fmt + vet + lint + test) -check: fmt vet lint test comments +check: fmt architecture vet lint test comments diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 72b98f9..d617e23 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -96,14 +96,14 @@ app shell / routes | 4. Server 应用服务 | 已完成 | 订单、发布、登录、聊天纵向抽取 | 应用服务、事务边界、后台生命周期和 Server 查询依赖均已收口,handler 不再直接访问数据库 | | 5. 应用生命周期装配 | 已完成 | 消除必需依赖 setter 回填 | 构造验证与幂等关闭测试 | | 6. Engine 与 Automation | 已完成 | facade + 独立状态组件 | Engine/Automation 组件边界、race、生命周期与冻结规范测试均已通过 | -| 7. React Feature 化 | 进行中 | 页面、Hook、API、类型按领域拆分 | 行为测试、懒加载和 bundle 记录 | -| 8. DB 与事务治理 | 未开始 | 窄接口、事务执行器、方言门禁 | 上层无裸 DB,多数据库回归 | -| 9. 架构门禁与兼容清理 | 未开始 | 自动依赖规则、删除到期兼容层 | 架构检查与迁移说明 | +| 7. React Feature 化 | 已完成 | 页面、Hook、API、类型按领域拆分 | 领域 feature、行为测试、依赖门禁和构建门禁已完成 | +| 8. DB 与事务治理 | 已完成 | 窄接口、事务执行器、方言门禁 | Chat、Automation、通知、分析、订单、发布、登录和事务边界已通过窄 repository 收口并完成 Server race | +| 9. 架构门禁与兼容清理 | 进行中 | 自动依赖规则、删除到期兼容层 | `tools/architecturecheck` 已建立 Go 低层依赖与 Server 事务边界门禁 | | 10. 注释基线清零 | 未开始 | 全仓严格中文注释检查 | baseline 文件删除 | ### 当前执行入口 -- 当前阶段:阶段 7“React Feature 化”(进行中);阶段 6 Engine 与 Automation、阶段 5 应用生命周期装配、阶段 4 Server 应用服务与阶段 3 HTTP API 契约已完成最终审计; +- 当前阶段:阶段 9“架构门禁与兼容清理”(进行中);阶段 7 React Feature 化和阶段 8 DB 与事务治理已完成切片收口,阶段 6 Engine 与 Automation、阶段 5 应用生命周期装配、阶段 4 Server 应用服务与阶段 3 HTTP API 契约已完成最终审计; - 已完成:总计划、依赖规则、中文注释规范、`AGENTS.md` 强约束,以及 Go/TypeScript AST 注释检查器和历史基线; - 阶段 1 已完成:server 测试模板预置管理员和账号 cookie,普通测试约 21.3 秒,完整 server race 约 194.3 秒通过; - 已完成阶段 2 逻辑切片一“Repository 敏感数据边界”:建立 `CookieSummary`、`ListOwnedIDs`、`ExistsOwned`、`GetOwnerID`、`GetSummaryOwned` 和原子 `GetValueOwned`,覆盖跨用户、无效 user ID 及无效密文回归; @@ -620,3 +620,4 @@ npm --prefix frontend run build | 2026-08-15 | 完成阶段 8 第八个 PR 切片“账号登录凭证与 Token repository 边界” | 新增 `accountLoginRepository`,账号登录服务的凭证创建/更新、Cookie Jar 元数据写回、凭证锁、Token 清理和运行状态读取统一通过窄接口;保留登录服务对资料刷新、登录审计和运行时重启的既有编排,未改变扫码幂等、Cookie 合并与凭证锁时序;Server 全量测试、Server race、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:登录审计与资料刷新共享 repository 边界 | | 2026-08-15 | 完成阶段 8 第九个 PR 切片“登录审计与资料刷新共享 repository 边界” | 登录方式/状态、登录审计日志、账号资料更新、资料刷新凭证锁与平台视图读取统一通过 `accountLoginRepository`;运行时 Cookie 更新复用同一账号状态边界,移除无调用方的旧扁平 Cookie helper,保持 MTOP Cookie Jar 合并、资料刷新失败恢复和运行时唤醒语义不变;Server 全量测试、Server race、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:数据库直连与事务边界最终审计 | | 2026-08-15 | 完成阶段 8 第十个 PR 切片“统一事务执行 repository 边界” | Server 统一事务入口不再直接持有 `Store.DB`,改由 `transactionRepository` 负责创建、提交和回滚事务;事务初始化失败、业务错误和提交失败均保持回滚语义,Server 依赖装配与事务回归测试已覆盖;Server 全量测试、Server race、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 9:架构依赖门禁与数据库直连最终审计 | +| 2026-08-15 | 完成阶段 9 第一个 PR 切片“Go/React 架构依赖门禁与数据库直连审计” | 新增 `tools/architecturecheck`,阻止 `internal/db`、`internal/xianyu`、`internal/browser` 反向依赖上层应用包,并阻止 Server 业务层直接创建事务;门禁接入 Makefile、CI 和 `make check`,同步更新阶段状态;架构检查、Go 全量测试、vet、lint、注释和前端注释门禁通过并合并为一个可回滚提交 | 阶段 9:兼容路由/字段调用方最终清理 | diff --git a/tools/architecturecheck/main.go b/tools/architecturecheck/main.go new file mode 100644 index 0000000..302e20d --- /dev/null +++ b/tools/architecturecheck/main.go @@ -0,0 +1,169 @@ +// architecturecheck 检查 Go 低层包依赖方向和 Server 裸事务入口。 +package main + +import ( + "fmt" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" +) + +// violation 表示一条架构依赖违规记录。 +type violation struct { + // file 是违规文件的仓库相对路径。 + file string + // line 是违规代码所在行号。 + line int + // message 是面向开发者的修复提示。 + message string +} + +// main 执行架构依赖检查并在发现违规时返回失败状态。 +func main() { + // root 是待检查的仓库根目录。 + root := "." + if len(os.Args) > 1 { + root = os.Args[1] + } + // violations 保存全部架构违规,便于一次修复完整问题集。 + violations, err := checkRepository(root) + if err != nil { + fmt.Fprintf(os.Stderr, "architecturecheck: %v\n", err) + os.Exit(1) + } + // violation 是待输出的单条架构违规记录。 + for _, violation := range violations { + fmt.Fprintf(os.Stderr, "%s:%d: %s\n", violation.file, violation.line, violation.message) + } + if len(violations) > 0 { + os.Exit(1) + } + fmt.Println("architecturecheck: 通过") +} + +// checkRepository 扫描 Go 源码并汇总依赖方向与事务边界问题。 +func checkRepository(root string) ([]violation, error) { + // violations 保存扫描过程中发现的全部违规。 + var violations []violation + // fset 为 AST 节点提供统一文件与行号映射。 + fset := token.NewFileSet() + // walkErr 是目录遍历或单文件检查的错误。 + walkErr := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() || filepath.Ext(path) != ".go" { + return nil + } + // relativePath 是当前文件相对于仓库根目录的路径。 + relativePath, err := filepath.Rel(root, path) + if err != nil { + return err + } + // fileViolations 保存当前文件的架构检查结果。 + fileViolations, err := checkGoFile(root, relativePath, fset) + if err != nil { + return err + } + violations = append(violations, fileViolations...) + return nil + }) + return violations, walkErr +} + +// checkGoFile 检查单个 Go 文件的导入方向和事务调用位置。 +func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, error) { + // filePath 是当前 Go 文件的绝对或仓库相对路径。 + filePath := filepath.Join(root, relativePath) + // source 是当前文件原文,用于识别事务调用的精确文本边界。 + source, err := os.ReadFile(filePath) + if err != nil { + return nil, err + } + // syntax 是当前文件的 AST。 + syntax, err := parser.ParseFile(fset, filePath, source, parser.ImportsOnly) + if err != nil { + return nil, err + } + // violations 保存当前文件发现的违规。 + var violations []violation + // importPath 是当前文件所属包的导入路径前缀。 + importPath := filepath.ToSlash(relativePath) + // imp 是当前 Go 文件的一条导入声明。 + for _, imp := range syntax.Imports { + // importedPath 是导入声明去除 Go 字符串引号后的路径。 + importedPath, err := strconv.Unquote(imp.Path.Value) + if err != nil { + return nil, err + } + if !isForbiddenLowLevelImport(importPath, importedPath) { + continue + } + // line 是导入声明所在的源码行号。 + line := fset.Position(imp.Pos()).Line + violations = append(violations, violation{ + file: filepath.ToSlash(relativePath), + line: line, + message: fmt.Sprintf("低层包禁止依赖上层应用包 %q", importedPath), + }) + } + if strings.HasPrefix(filepath.ToSlash(relativePath), "internal/server/") && !strings.HasSuffix(relativePath, "_repository.go") { + // sourceLine 是裸 BeginTx 调用首次出现的源码行号。 + sourceLine := firstLineContaining(string(source), ".DB.BeginTx(") + if sourceLine > 0 { + violations = append(violations, violation{ + file: filepath.ToSlash(relativePath), + line: sourceLine, + message: "Server 业务层禁止直接创建数据库事务,请通过 repository 执行", + }) + } + } + return violations, nil +} + +// isForbiddenLowLevelImport 判断低层包是否依赖了上层应用包。 +func isForbiddenLowLevelImport(filePath, importedPath string) bool { + // lowLevelPackage 标识当前文件所属的低层包。 + lowLevelPackage := "" + switch { + case strings.HasPrefix(filePath, "internal/db/"): + lowLevelPackage = "internal/db/" + case strings.HasPrefix(filePath, "internal/xianyu/"): + lowLevelPackage = "internal/xianyu/" + case strings.HasPrefix(filePath, "internal/browser/"): + lowLevelPackage = "internal/browser/" + } + if lowLevelPackage == "" || strings.HasPrefix(importedPath, lowLevelPackage) { + return false + } + // upperPackage 是禁止被低层包依赖的上层包路径。 + for _, upperPackage := range []string{ + "internal/server", + "internal/adapter", + "internal/account", + "internal/automation", + "internal/engine", + "internal/chat", + "internal/notify", + "internal/auth", + } { + if importedPath == upperPackage || strings.HasPrefix(importedPath, upperPackage+"/") { + return true + } + } + return false +} + +// firstLineContaining 返回文本中首次出现目标字符串的行号。 +func firstLineContaining(source, target string) int { + // offset 是目标字符串在原文中的字节偏移。 + offset := strings.Index(source, target) + if offset < 0 { + return 0 + } + return 1 + strings.Count(source[:offset], "\n") +}