阶段二:完成 Server 组合根和应用服务迁移

This commit is contained in:
Christ committed 2026-08-18 23:38:28 +08:00
1 parent 649af6499f
commit 3cbe73b560
72 files changed
+4647 -2918

No files matched your search

+20 -20
View File
@@ -108,28 +108,28 @@ agents MUST read all of:
- `docs/architecture/comment-standard.md`
- `docs/slider-captcha-frozen-spec.md` when credentials, login, engine, account, server or browser call paths are involved
The following rules are mandatory:
The authoritative schedule has exactly six formal phases and is defined only by
`docs/architecture/refactoring-master-plan.md`. Before editing, read its state table. Do not infer a phase from
old commits, a document heading, implementation that happened to land early, or a historical completion claim.
1. Identify the current plan stage before editing. A stage is the only delivery and review unit: one complete
phase-level PR/final merge may modify several Go packages, frontend features, tests, architecture gates and
documents together. Agents must not turn a stage into separately delivered vertical slices.
2. A phase worktree may be temporarily non-compiling while its coordinated migration is in progress. The final
phase commit/merge must compile, start, pass every mandatory phase verification and include complete evidence.
Add or strengthen characterization tests before moving high-risk behavior.
3. Do not use a large phase change to hide unfinished branches, error paths or unverified behavior. Unrelated
renames, repository-wide formatting, dependency upgrades, test weakening, coverage deletion, compatibility
whitelist expansion and frozen CAPTCHA changes remain prohibited.
4. Update the master-plan status table, completion evidence, update log and next entry point once when a phase
is completed or its scope materially changes. Completion evidence is bound to the final phase commit and the
complete command output, not to intermediate local commits.
5. Do not weaken, skip or delete tests to make a refactor pass. Existing test failures must be explained and
resolved or reported as blockers.
6. Preserve unrelated working-tree changes. Do not reformat or rename unrelated code as cleanup.
7. Compatibility adapters remain until every known caller is migrated and contract tests prove the old path
can be removed. New compatibility aliases require an explicit removal condition in the plan.
Each phase is one task, one review unit and one final Chinese commit. A phase may change every package, feature,
test, gate and document required by its stated scope. Agents MUST NOT split it into vertical slices, milestones,
separately delivered subtasks, independent PRs, or intermediate commits. The worktree may be temporarily
non-compiling only while the single phase is in progress; its final commit must compile, start, pass every listed
verification and have complete evidence recorded once in `refactoring-progress.md`.
Emergency bug or security fixes may precede the planned sequence, but they must stay narrowly scoped, preserve
the same architectural constraints, and add a note to the plan update log explaining why the sequence changed.
The complete architecture-gate catalog is established before production migration. `tools/architecturecheck`
reads the single current phase from the master plan, activates that phase and every earlier gate, and fails when
the phase state is missing or ambiguous. After phase six is complete, every gate remains permanently active.
Agents must not defer gate design to phase six, enable a future phase
early, or bypass an active gate with a whitelist, baseline, ignored path or warning-only result.
Do not use a large phase change to hide unfinished branches, error paths or unverified behavior. Do not weaken,
skip or delete tests; reformat or rename unrelated code; upgrade unrelated dependencies; delete coverage; expand
a compatibility whitelist; or change frozen CAPTCHA behavior. Preserve unrelated working-tree changes.
Compatibility adapters remain until every known caller has migrated and contract tests prove removal. Emergency
bug or security fixes may precede the plan only when narrowly scoped and recorded in the master plan.
## Mandatory Chinese comments for all functions and variables
+1 -1
View File
@@ -51,7 +51,7 @@ vet:
lint:
$(GOLANGCI_LINT) run ./...
## architecture: 检查 Go 低层依赖方向和 Server 事务边界
## architecture: 按总计划当前阶段启用完整架构规则目录中的对应门禁
architecture:
$(GO) run ./tools/architecturecheck
+40 -171
View File
@@ -21,17 +21,11 @@ import (
"syscall"
"time"
"xianyu-go/internal/adapter"
lifecycleapp "xianyu-go/internal/application/lifecycle"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
compositionruntime "xianyu-go/internal/composition/runtime"
"xianyu-go/internal/db"
"xianyu-go/internal/logging"
"xianyu-go/internal/logsafe"
"xianyu-go/internal/renewal"
"xianyu-go/internal/server"
appversion "xianyu-go/internal/version"
)
@@ -70,6 +64,9 @@ const (
applicationShutdownTimeout = 10 * time.Second
)
// errDataKeyEmpty 表示已打开的数据密钥文件尚未包含有效内容;并发读取者可以有限等待写入者完成。
var errDataKeyEmpty = errors.New("data key 文件为空")
// serverStartupConfig 保存目录、数据库和日志策略准备阶段的派生配置。
type serverStartupConfig struct {
// dataDir 是桌面服务或显式 workdir 使用的应用数据目录,空值表示沿用当前目录布局。
@@ -113,9 +110,9 @@ func (i serverInfrastructure) close() {
// serverRuntime 保存 HTTP 服务及应用生命周期协调器,二者必须由同一 Context 启动和关闭。
type serverRuntime struct {
// httpServer 是已完成依赖注入、尚未启动监听的 HTTP 服务。
httpServer *server.Server
httpServer httpRuntime
// lifecycleCoordinator 按登记顺序启动组件并按逆序关闭后台 worker。
lifecycleCoordinator *lifecycleapp.Coordinator
lifecycleCoordinator applicationRuntimeCoordinator
}
// httpRuntimeStopper 定义进程关闭阶段需要的最小 HTTP 停止能力。
@@ -125,6 +122,17 @@ type httpRuntimeStopper interface {
Stop(context.Context) error
}
// httpRuntime 定义正常进程启动、等待和关闭 HTTP 服务所需的完整能力。
type httpRuntime interface {
// Bind 在启动后台组件前同步占用 HTTP 监听端口。
Bind() error
// Start 开始接收 HTTP 请求。
Start(context.Context) error
// Wait 等待 HTTP 监听退出。
Wait() error
Stop(context.Context) error
}
// applicationRuntimeCloser 定义进程关闭阶段需要的最小应用组件收束能力。
// Close 必须取消并等待全部已登记应用 worker,返回值保留未完成组件诊断。
type applicationRuntimeCloser interface {
@@ -132,6 +140,12 @@ type applicationRuntimeCloser interface {
Close(context.Context) error
}
// applicationRuntimeCoordinator 定义 cmd 对组合根生命周期对象执行启动和关闭所需的能力。
type applicationRuntimeCoordinator interface {
Start(context.Context) error
Close(context.Context) error
}
// main 封装main业务协调。
func main() {
// opts 是命令行解析出的服务启动选项。
@@ -389,167 +403,14 @@ func openServerInfrastructure(ctx context.Context, startup serverStartupConfig,
// buildServerRuntime 构造浏览器、账号、自动化、通知、应用服务和 HTTP 服务依赖,并登记全部生命周期组件但不启动它们。
func buildServerRuntime(opts serverOptions, infrastructure serverInfrastructure) (serverRuntime, error) {
// bm 是可选浏览器基础设施;禁用浏览器时保持 nil,使账号运行时走无浏览器路径。
var bm *browser.Manager
if !opts.noBrowser {
bm = browser.NewManager(infrastructure.logger)
// runtime、buildErr 分别是组合层返回的完整运行时快照及其装配失败原因。
runtime, buildErr := compositionruntime.BuildRuntime(compositionruntime.RuntimeOptions{
NoBrowser: opts.noBrowser, SecureCookie: opts.secure, WebDir: opts.webDir, Addr: opts.addr,
}, compositionruntime.RuntimeInfrastructure{Store: infrastructure.store, Logger: infrastructure.logger})
if buildErr != nil {
return serverRuntime{}, buildErr
}
// runtimeBundle 一次性闭合账号、自动化、通知和聊天依赖,避免生产路径通过 setter 补装必需依赖。
runtimeBundle, bundleErr := adapter.NewRuntimeBundle(infrastructure.store, bm, infrastructure.logger)
if bundleErr != nil {
return serverRuntime{}, fmt.Errorf("构造账号运行时依赖失败: %w", bundleErr)
}
// ap 是账号引擎事件和协议级订单详情的固定适配器。
ap := runtimeBundle.Adapter
// chatService 是 HTTP 与账号事件共享的聊天领域服务。
chatService := runtimeBundle.Chat
// mgr 是统一拥有已启用账号引擎生命周期的 supervisor。
mgr := runtimeBundle.Manager
// notifier 是账号告警与自动化结果共用的通知出口。
notifier := runtimeBundle.Notifier
// autoCenter 是接收账号事件和计划任务的自动化中心。
autoCenter := runtimeBundle.Automation
// automationScheduler 驱动自动化延迟任务、租约恢复和定时扫描。
automationScheduler := automation.NewScheduler(autoCenter)
// renewalScheduler 负责账号凭证续期调度,并通过固定适配器通知账号运行时。
renewalScheduler := renewal.NewScheduler(infrastructure.store, mgr, ap, infrastructure.logger, notifier)
// lifecycleCoordinator 统一拥有组件启动顺序、取消 Context 和逆序关闭。
lifecycleCoordinator := lifecycleapp.NewCoordinator()
if bm != nil {
// err 表示浏览器生命周期组件登记失败。
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "browser", Component: lifecycleapp.FuncComponent{
StartFunc: func(context.Context) error { return bm.Initialize() },
CloseFunc: bm.CloseContext,
}}); err != nil {
return serverRuntime{}, fmt.Errorf("登记浏览器生命周期组件失败: %w", err)
}
}
// err 表示通知 worker 生命周期组件登记失败。
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "notifier", Component: lifecycleapp.FuncComponent{
StartFunc: func(componentCtx context.Context) error { notifier.Start(componentCtx); return nil },
CloseFunc: notifier.WaitContext,
}}); err != nil {
return serverRuntime{}, fmt.Errorf("登记通知生命周期组件失败: %w", err)
}
// err 表示账号运行时生命周期组件登记失败。
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "account-manager", Component: lifecycleapp.FuncComponent{
StartFunc: mgr.StartAll,
CloseFunc: mgr.StopAllContext,
}}); err != nil {
return serverRuntime{}, fmt.Errorf("登记账号生命周期组件失败: %w", err)
}
// err 表示自动化调度器生命周期组件登记失败。
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "automation-scheduler", Component: lifecycleapp.FuncComponent{
StartFunc: func(componentCtx context.Context) error { go automationScheduler.Run(componentCtx); return nil },
CloseFunc: automationScheduler.WaitContext,
}}); err != nil {
return serverRuntime{}, fmt.Errorf("登记自动化调度生命周期组件失败: %w", err)
}
// err 表示凭证续期调度器生命周期组件登记失败。
if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "renewal-scheduler", Component: lifecycleapp.FuncComponent{
StartFunc: func(componentCtx context.Context) error { go renewalScheduler.Run(componentCtx); return nil },
CloseFunc: renewalScheduler.StopContext,
}}); err != nil {
return serverRuntime{}, fmt.Errorf("登记续期调度生命周期组件失败: %w", err)
}
// orderDependencies、orderErr 分别是订单应用服务依赖及其构造失败。
orderDependencies, orderErr := adapter.NewOrderDependencies(infrastructure.store)
if orderErr != nil {
return serverRuntime{}, fmt.Errorf("构造订单基础设施依赖失败: %w", orderErr)
}
// accountDependencies、accountErr 分别是账号应用服务依赖及其构造失败。
accountDependencies, accountErr := adapter.NewAccountDependencies(infrastructure.store)
if accountErr != nil {
return serverRuntime{}, fmt.Errorf("构造账号基础设施依赖失败: %w", accountErr)
}
// itemDependencies、itemErr 分别是商品应用服务依赖及其构造失败。
itemDependencies, itemErr := adapter.NewItemDependencies(infrastructure.store)
if itemErr != nil {
return serverRuntime{}, fmt.Errorf("构造商品基础设施依赖失败: %w", itemErr)
}
// automationDependencies、automationErr 分别是自动化应用服务依赖及其构造失败。
automationDependencies, automationErr := adapter.NewAutomationDependencies(infrastructure.store)
if automationErr != nil {
return serverRuntime{}, fmt.Errorf("构造自动化基础设施依赖失败: %w", automationErr)
}
// miscDependencies、miscErr 分别是通知、分析和卡券应用服务依赖及其构造失败。
miscDependencies, miscErr := adapter.NewMiscDependencies(infrastructure.store)
if miscErr != nil {
return serverRuntime{}, fmt.Errorf("构造通知分析卡券基础设施依赖失败: %w", miscErr)
}
// adminSettingsDependencies 是管理员与系统设置应用服务的依赖,nil 代表装配失败。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(infrastructure.store)
if adminSettingsDependencies == nil {
return serverRuntime{}, fmt.Errorf("构造管理员设置基础设施依赖失败")
}
// chatDependencies 是聊天应用服务使用的运行时与平台适配器,nil 代表装配失败。
chatDependencies := adapter.NewChatDependencies(infrastructure.store)
if chatDependencies == nil {
return serverRuntime{}, fmt.Errorf("构造聊天基础设施依赖失败")
}
// systemDependencies 是健康检查和订单补偿扫描使用的数据库适配器,nil 代表装配失败。
systemDependencies := adapter.NewSystemDependencies(infrastructure.store)
if systemDependencies == nil {
return serverRuntime{}, fmt.Errorf("构造系统基础设施依赖失败")
}
// orderReconciliationRecovery 是由进程装配层拥有的订单补偿扫描应用服务,Server 仅接收其 transport-facing 端口。
orderReconciliationRecovery, orderReconciliationRecoveryErr := orderapp.NewReconciliationRecoveryCoordinator(systemDependencies.NewReconciliationService(infrastructure.logger))
if orderReconciliationRecoveryErr != nil {
return serverRuntime{}, fmt.Errorf("构造订单补偿恢复协调器失败: %w", orderReconciliationRecoveryErr)
}
// databaseHealth 是进程装配层创建的数据库健康检查端口,HTTP handler 只能通过该窄接口探测连通性。
databaseHealth := systemDependencies.NewDatabaseHealth()
if databaseHealth == nil {
return serverRuntime{}, fmt.Errorf("构造数据库健康检查端口失败")
}
// platformDependencies 提供 HTTP 层使用的 MTOP、长登录和二维码平台能力。
platformDependencies, platformErr := adapter.NewDefaultPlatformDependencies(infrastructure.logger)
if platformErr != nil {
return serverRuntime{}, fmt.Errorf("构造平台基础设施依赖失败: %w", platformErr)
}
// transportApplications 是进程组合根一次性构造的 transport-facing 应用服务集合。
transportApplications, transportApplicationsErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies,
MiscDependencies: miscDependencies,
AdminSettingsDependencies: adminSettingsDependencies,
AdminRuntime: mgr,
AccountTaskRunner: adapter.NewAccountTaskRunner(autoCenter),
ChannelSender: notifier,
ModelClient: adapter.NewAIModelClient(),
})
if transportApplicationsErr != nil {
return serverRuntime{}, fmt.Errorf("构造 transport 应用服务失败: %w", transportApplicationsErr)
}
// authentication 负责 HTTP 会话认证;Secure 策略由启动参数控制。
authentication := &auth.Service{Store: infrastructure.store, Logger: infrastructure.logger, Secure: opts.secure}
// compositionServer 仅在迁移期间复用旧应用服务装配逻辑;它不绑定端口、不启动 worker,也不作为 HTTP Server 运行。
compositionServer, compositionErr := server.NewLegacyComposedServer(authentication, mgr, opts.webDir, opts.addr, infrastructure.logger, autoCenter, notifier, server.WithChatService(chatService), server.WithChatDependencies(chatDependencies), server.WithDatabaseHealth(databaseHealth), server.WithOrderReconciliationRecovery(orderReconciliationRecovery), server.WithOrderDependencies(orderDependencies), server.WithAccountDependencies(accountDependencies), server.WithItemDependencies(itemDependencies), server.WithAutomationDependencies(automationDependencies), server.WithTransportApplicationServices(transportApplications), server.WithPlatformDependencies(platformDependencies), server.WithApplicationLifecycle(lifecycleCoordinator))
if compositionErr != nil {
return serverRuntime{}, fmt.Errorf("构造应用服务集合失败: %w", compositionErr)
}
// applications 是组合期一次性构造的只读应用服务集合,HTTP Server 不得在自身构造期间补建业务服务。
applications := compositionServer.ApplicationServices()
// httpServer 是只接收完整依赖快照的 HTTP transport 实例。
httpServer, serverErr := server.New(server.Dependencies{
Auth: authentication, Manager: mgr, WebDir: opts.webDir, Addr: opts.addr, Logger: infrastructure.logger,
Automation: autoCenter, Notifier: notifier, Chat: chatService, OrderDependencies: orderDependencies,
AccountDependencies: accountDependencies, ItemDependencies: itemDependencies, ChatDependencies: chatDependencies,
AutomationDependencies: automationDependencies, TransportApplications: transportApplications,
PlatformDependencies: platformDependencies, DatabaseHealth: databaseHealth,
OrderReconciliationRecovery: orderReconciliationRecovery, Applications: applications,
ApplicationLifecycle: lifecycleCoordinator,
})
if serverErr != nil {
return serverRuntime{}, fmt.Errorf("构造 HTTP 服务失败: %w", serverErr)
}
// component 表示应用服务集合交给进程组合根登记的 worker 生命周期组件。
for _, component := range applications.LifecycleComponents() {
// err 表示当前 HTTP 应用 worker 生命周期组件登记失败。
if err := lifecycleCoordinator.Add(component); err != nil {
return serverRuntime{}, fmt.Errorf("登记应用 worker 生命周期组件 %q 失败: %w", component.Name, err)
}
}
return serverRuntime{httpServer: httpServer, lifecycleCoordinator: lifecycleCoordinator}, nil
return serverRuntime{httpServer: runtime.HTTPServer, lifecycleCoordinator: runtime.Lifecycle}, nil
}
// runServerLifecycle 启动应用组件和 HTTP 监听,等待退出后执行有限时长的 HTTP 与组件逆序关闭。
@@ -722,6 +583,8 @@ func loadOrCreateDataKey(path string) (string, error) {
// key、readErr 分别是已存在密钥文件的内容及读取错误;已有文件永远优先于本次生成。
if key, readErr := readDataKey(path); readErr == nil {
return key, nil
} else if errors.Is(readErr, errDataKeyEmpty) {
return waitForDataKey(path)
} else if !errors.Is(readErr, os.ErrNotExist) {
return "", readErr
}
@@ -779,13 +642,15 @@ func readDataKey(path string) (string, error) {
// key 是去除文件末尾换行后的数据加密主密钥,禁止记录到日志。
key := strings.TrimSpace(string(raw))
if key == "" {
return "", fmt.Errorf("data key 文件为空: %s", path)
return "", fmt.Errorf("%w: %s", errDataKeyEmpty, path)
}
return key, nil
}
// waitForDataKey 等待并读取由并发启动进程创建的密钥文件,不会生成或覆盖另一把密钥。
func waitForDataKey(path string) (string, error) {
// lastReadErr 保存最后一次未得到可用密钥的读取错误,用于保留遗留空文件诊断。
var lastReadErr error
// attempt 是读取竞争方写入结果的有限尝试次数,避免空文件永久阻塞启动。
for attempt := 0; attempt < 20; attempt++ {
// key、readErr 分别是当前尝试读到的密钥及读取错误。
@@ -793,11 +658,15 @@ func waitForDataKey(path string) (string, error) {
if readErr == nil {
return key, nil
}
if !strings.Contains(readErr.Error(), "文件为空") && !errors.Is(readErr, os.ErrNotExist) {
lastReadErr = readErr
if !errors.Is(readErr, errDataKeyEmpty) && !errors.Is(readErr, os.ErrNotExist) {
return "", readErr
}
time.Sleep(10 * time.Millisecond)
}
if errors.Is(lastReadErr, errDataKeyEmpty) {
return "", lastReadErr
}
return "", fmt.Errorf("等待并发创建 data key 文件超时: %s", path)
}
@@ -9,7 +9,7 @@
- 新增接口必须先进入 `/api/v1/...`,旧路径只有在确认外部调用方为零后才允许删除。
- 删除旧路径前必须在本文件记录调用方审计证据、迁移版本和回滚方式,并同步删除对应契约测试。
## 阶段 3 调用方审计
## API 调用方审计
旧入口的仓库内调用方由 `tools/architecturecheck` 中的
`TestFrontendProductionRequestsUseVersionedAPI` 静态清点,并在每次改动前端请求适配层时运行:
@@ -41,4 +41,5 @@ DTO 或明确标量;架构门禁只允许这类已登记的兼容结构,禁
服务端目前保留 `/api/...`、`/...` 和 `/admin/...` 等历史入口。仓库内生产 React 调用已经全部迁移到 `/api/v1/...`,服务端契约测试仍覆盖新旧路径的等价响应和权限边界。
这些旧入口暂不删除,因为它们可能被已部署的桌面包、脚本或第三方客户端调用。后续发布周期收集到外部调用方为零的证据后,再按“一个资源域一个 PR”逐步删除,并保留版本化入口回归测试。
这些旧入口暂不删除,因为它们可能被已部署的桌面包、脚本或第三方客户端调用。只有外部调用方为零、
Sunset 到期、回滚方案和契约测试齐备后,才能在阶段六的唯一阶段提交中删除,并同步保留版本化入口回归测试。
@@ -1,6 +1,6 @@
# HTTP API 版本化迁移边界
本文记录阶段三当前切片完成后的 API 版本化边界。当前仓库尚未切换现有路径;新版本路由必须先完成前端调用方迁移和契约测试,再删除旧别名。
本文记录 API 版本化边界。它不定义重构阶段编号、当前状态或完成结论;新版本路由必须先完成前端调用方迁移和契约测试,再删除旧别名。
## 当前兼容路径
@@ -32,7 +32,7 @@
4. 删除旧路径前必须记录调用方、发布日期、迁移版本和回滚方案;发布说明要明确旧路径的移除版本。
5. 错误响应始终使用 `code`、`message`、`request_id`,恢复信息只能放入 `details`;版本适配器不得重新引入 `detail`、`msg` 或 HTTP 200 + `success:false`。
## 当前切片证据
## API 版本化证据
- 认证会话校验使用 `sessionVerificationResponse`。
- 账号详情、设置、资料刷新和暂停查询使用 `cookieDetailResponse`、`cookieSettingsResponse`、`cookieProfileResponse` 与 `pauseDurationResponse`。
+9 -8
View File
@@ -3,7 +3,8 @@
## 1. 目的
本文定义重构期间和目标状态下的依赖方向。过渡期允许保留已有直接依赖,
但禁止新增同类耦合;每个重构阶段必须减少而不是扩大例外。
但禁止新增同类耦合;每个正式阶段必须减少而不是扩大例外。阶段编号、状态和交付规则只由
refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态。
## 2. 通用规则
@@ -53,7 +54,7 @@
- 保存业务 worker、锁、cancel map 或平台会话状态;
- 直接实现订单同步、商品发布、凭证续期或自动化动作。
过渡期已有依赖可以在对应纵向切片完成前保留,但不得新增新的直接调用点。
过渡期已有依赖可以在对应正式阶段完成前保留,但不得新增新的直接调用点。
### 3.3 应用服务
@@ -166,9 +167,9 @@
门禁应按目标边界逐步启用:
1. 先禁止新增不允许依赖;
2. 每迁移一个业务切片,删除对应例外;
3. 最终使用 `go list` 或自定义 AST 检查完整依赖;
4. 前端使用 TypeScript/ESLint import 限制;
5. 架构例外必须记录负责人、原因和删除阶段;
6. 禁止为了让门禁通过而把依赖藏进反射、动态 import 或 service locator。
1. 当前正式阶段开始前先启用该阶段的 fail-closed AST、依赖或行为门禁;当前阶段违规必须立即失败。
2. 已完成阶段的门禁永久保留;后续阶段专有门禁只在该阶段成为当前阶段时启用。
3. 阶段目标边界禁止使用白名单、baseline、忽略目录或降级告警豁免;阶段内失败只能通过完成迁移消除。
4. 最终使用 `go list`、AST 与前端依赖规则检查完整依赖图,不能只依赖少量名称匹配。
5. 仅生成物和冻结文件可有精确范围排除;它们不是架构违规的通用例外,也不能覆盖生产源码。
6. 禁止为了让门禁通过而把依赖藏进反射、动态 import、service locator 或无语义中转层。
+7 -7
View File
@@ -1,7 +1,7 @@
# 生命周期与后台任务清单
本文是重构计划阶段 5 收口后的静态审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界,
用于防止后续迭代重新引入游离 goroutine;阶段状态和验收证据只记录在重构进度文档中。
本文是生命周期静态审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界,
用于防止后续迭代重新引入游离 goroutine;它不定义阶段编号、阶段状态或验收结论。
## 组件清单
@@ -12,13 +12,13 @@
| 订单刷新 worker/recovery | `lifecycle.Coordinator` → `orders.RefreshJobService` | 协调器共享应用生命周期 Context;请求只负责创建任务 | 协调器逆序 `Close(ctx)`,runner 通过租约 token 和 Context 收束 | 应用任务状态、租约终态和 runner `Wait/Close` | 订单刷新生命周期、租约、取消和晚到写入测试 | 统一运维查询属于后续观测迭代,不改变生命周期所有权 |
| 商品批量发布 worker/recovery | `lifecycle.Coordinator` → `items.BatchWorkerCoordinator` | 协调器共享应用生命周期 Context;取消后的本地收口使用受控补偿 Context | 协调器逆序 `Close(ctx)`,worker cancel、租约 token 和终态补偿由应用协调器负责 | 批次状态、协调器 `Wait/Close` 与错误回调 | 批量取消 race、应用 BatchRunner 和协调器测试 | 恢复指标属于后续观测迭代,不改变生命周期所有权 |
| 订单 reconciliation worker | `lifecycle.Coordinator` → `orders.ReconciliationRecoveryCoordinator` | 协调器共享应用生命周期 Context | 协调器逆序 `Close(ctx)` 取消当前扫描并等待退出 | 补偿记录状态与协调器 `Wait/Close` | reconciliation 成功/失败重试、取消和协调器测试 | 指数退避属于后续补偿策略迭代 |
| `account.Manager` 账号运行时集合 | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopAllContext`,保留全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing、生命周期和 race 测试 | 运行时内部任务的细分归入阶段 6,不改变进程级 owner |
| `account.Manager` 账号运行时集合 | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopAllContext`,保留全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing、生命周期和 race 测试 | 运行时内部任务的细分由正式总计划决定,不改变进程级 owner |
| `engine.Account` 单账号运行时 | `account.Manager`;连接、出站、凭证和迟到续期分别由 `connectionCoordinator`、`outgoingMessageCoordinator`、`credentialCoordinator`、`pendingRenewalCoordinator` 负责 | `Account.Run(parent)` | `StopContext` 取消运行 Context;连接协调器以受限预算等待自有 worker | `StopContext` 返回错误;共享完成信号支持超时后的再次 Join;运行状态可查询 | Engine lifecycle、连接协调器、出站发送、credential coordinator、刷新取消与迟到续期测试 | recorder 子任务继续沿用账号运行 Context,不允许脱离 facade 生命周期 |
| 浏览器 `Manager` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 每次调用的独立 Context;初始化和关闭受协调器 Context/Close Context 约束 | 协调器逆序调用 `CloseContext`,关闭 fencing 并等待活动调用归零 | `CloseContext` 返回超时并可重试 | Browser lifecycle 与 race 测试 | 底层同步 Playwright Close 无法被 Context 中断,这是实现约束 |
| 续期 `renewal.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopContext`,幂等并阻止 Stop 后 Run | `WaitContext` | 先 Stop、重复 Stop、零值和 race 测试 | 迟到 Cookie 合并语义由续期组件自身 generation/锁测试保护 |
| 自动化 `automation.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context;nil Context 明确拒绝启动 | 协调器逆序取消 Context 并调用 `WaitContext` | `WaitContext` | scheduler、nil 输入与结果收口测试 | 自动化外部动作语义归入阶段 6,不改变调度器 owner |
| 自动化 `automation.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context;nil Context 明确拒绝启动 | 协调器逆序取消 Context 并调用 `WaitContext` | `WaitContext` | scheduler、nil 输入与结果收口测试 | 自动化外部动作语义归属由正式总计划决定,不改变调度器 owner |
| 通知 outbox worker | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `WaitContext`,由共享 Context 停止拉取与发送 | `WaitContext`、uncertain 状态查询 | notify worker、uncertain 状态和三库测试 | 运维重试与人工核对流程属于通知业务迭代 |
| WebSocket/聊天后台发送任务 | `chat.Service` 与请求级连接 owner | 请求 Context 和连接关闭信号;不继承 Server 业务 worker Context | 请求取消或连接关闭时先取消发送/读取任务,再由连接 owner 等待 Join | WebSocket handler 显式等待读取 goroutine,发送结果和连接状态保留可观测字段 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 更细的消息分发状态拆分属于阶段 6,不新增 Server 生命周期入口 |
| WebSocket/聊天后台发送任务 | `chat.Service` 与请求级连接 owner | 请求 Context 和连接关闭信号;不继承 Server 业务 worker Context | 请求取消或连接关闭时先取消发送/读取任务,再由连接 owner 等待 Join | WebSocket handler 显式等待读取 goroutine,发送结果和连接状态保留可观测字段 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 更细的消息分发状态由正式总计划安排,不新增 Server 生命周期入口 |
## 外部调用取消与超时审计
@@ -34,7 +34,7 @@
审计结论:`notify.Notifier.Start(nil)` 和 `automation.Scheduler.Run(nil)` 已明确拒绝启动并有确定性测试;生产组合根始终传入非 nil Context。通知 HTTP helper 仍以 10 秒 client timeout 作为无法直接继承 worker Context 的边界,未形成无限等待。
## 阶段 6 并发与锁边界
## 并发与锁边界
| 锁/协调状态 | 所有者与保护范围 | 明确禁止 | 锁顺序/验证 |
| --- | --- | --- | --- |
@@ -49,4 +49,4 @@
1. 新增 goroutine 必须在本表增加一行,注明启动者、Context 来源、取消责任和等待方式。
2. 新组件必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动继承其业务语义。
3. 删除账号前必须先建立账号级 stopping fence,再在受限 Context 内停止运行时,最后重新校验归属并删除持久化记录。
4. 本表只记录 owner 与边界;阶段 6 以后业务策略、运维观测和实时连接细分风险不得重新转化为 Server 生命周期入口。
4. 本表只记录 owner 与边界;业务策略、运维观测和实时连接细分风险不得重新转化为 Server 生命周期入口。
+148 -486
View File
@@ -1,557 +1,219 @@
# Ydisks 闲鱼助手重构总计划
## 1. 计划目标
## 唯一治理规则
本文是仓库重构的唯一阶段路线图,只记录目标架构、十个正式迭代、阶段验收条件和强制约束。
本文不记录开发日期、提交列表、阶段内进度、完成日志、人员记录或临时工作说明。
本文是唯一的阶段状态、顺序和验收依据。AGENTS.md 只负责要求读取本文;refactoring-progress.md 只
保存最终提交与验收证据;其他架构文档只记录领域约束,不定义阶段状态。
阶段 0 是执行重构前的治理前置条件,不计入正式迭代。阶段 1 至阶段 10 各自对应一个完整
迭代和一个阶段级 PR/最终合并。阶段内部允许同步修改多个包、feature、测试、门禁和文档;
agent 不得将阶段拆成多个独立交付。阶段进行中的本地工作区或临时提交可以暂时不可编译,
但阶段最终提交必须可编译、可启动、可测试并通过本阶段全部强制验证。
本重构只有六个正式阶段。旧的十阶段编号、阶段 0、纵向切片、当前切片、分轮迭代、局部完成声明和
一个改动一个提交的规则全部失效。阶段是唯一任务、评审和交付单位:一个阶段允许同时修改多个 Go
包、多个前端 feature、测试、门禁、文档和嵌入产物;agent 不得拆分子任务、垂直切片、独立 PR 或
中间提交。阶段最终提交必须可编译、可启动、可测试并通过全部强制验证。阶段完成前不得创建提交,
最终只创建一条中文阶段提交。
滑块 CAPTCHA 行为继续由 `docs/slider-captcha-frozen-spec.md` 保护。本文不是修改冻结行为的授权。
禁止无关重命名、全仓格式化、依赖升级、削弱测试或覆盖率、扩大兼容白名单、修改默认 :59188、改变
远程首次初始化行为,以及修改冻结 CAPTCHA 文件、测试、参数、调用顺序或规范。
### 1.1 最终成功标准
## 基础验证层(非正式阶段)
1. `cmd` 只负责配置、依赖构造、信号和进程生命周期。
2. `internal/server` 只负责 HTTP/WebSocket transport、鉴权、中间件、具名 DTO 和 SPA。
3. 应用服务负责完整用例、所有权校验和事务边界,且不依赖 HTTP、数据库或平台实现类型。
4. `internal/db` 独占 SQL、迁移、方言、加密持久化和 repository 实现。
5. 账号摘要、平台凭证、密码登录秘密和运行配置使用不同模型和最小查询。
6. Engine 与 Automation 的并发状态、凭证协调、外部动作和生命周期由明确组件拥有。
7. React 遵守 `app -> features -> shared`,业务请求、状态和 DTO 转换归属对应 feature。
8. SQLite、MySQL、PostgreSQL 的迁移、事务和核心业务行为一致。
9. 旧 API 和兼容字段只在有调用方、遥测和删除条件时保留,最终按明确 Sunset 退场。
10. 架构、注释、race、多数据库、前端类型和构建均成为自动门禁,无历史豁免。
完整架构门禁必须在业务迁移前建立,不属于阶段六的末尾补救工作。`tools/architecturecheck` 预先登记阶段二
至阶段六的全部规则,并从本文状态表读取唯一“当前阶段”:当前阶段及全部前序规则立即 fail-closed,后续
规则保持已定义但暂不阻断。状态表缺失、重复当前阶段或无法解析时,门禁自身失败;阶段六明确完成后
即使不再存在“当前阶段”,全量门禁仍永久开启。
## 2. 目标架构
门禁目录固定覆盖:Server 组合根与平台旁路、worker 生命周期与根 Context、React feature/契约/网络边界、
上层裸数据库与事务泄露、复杂度与超大文件、兼容登记与 Sunset。阶段只负责激活规则并清零真实违规,
不得到阶段执行时才临时设计验收逻辑。
```text
cmd
-> application services / lifecycle
-> consumer-defined ports
<- adapter implementations
-> db / xianyu / browser / notify
## 目标边界
HTTP server
-> application services
cmd 只处理配置、依赖构造、信号和生命周期。internal/server 只处理 HTTP/WebSocket transport、鉴权、
中间件、具名 DTO、错误映射和 SPA。应用服务拥有用例、所有权、事务和补偿,不依赖 HTTP、Server、
DB 或平台实现。internal/db 独占 SQL、方言、迁移、加密和 repository。React 使用 app -> features ->
shared,feature adapter 直接转换领域 DTO 为 feature-owned UI model。
React app shell
-> feature page
-> feature hooks / state / API adapter / UI model
-> shared HTTP client and shared UI
```
## 当前状态
接口由消费者定义并保持最小。禁止全局 service locator、万能 repository、通过 `any`/反射隐藏
依赖、或仅为绕过架构检查增加中转层。详细依赖规则以
`docs/architecture/dependency-rules.md` 为准。
状态只能是 待验收、当前阶段、待执行、阻塞、已完成;已完成必须绑定最终中文提交和完整命令输出。
## 3. 当前代码基线
本节只描述制定后续迭代所需的当前事实,不保存重构历史。
- 当前开发分支从本地 `main` 演进;本地 `main` 落后 `xianyu-go/main`,功能对照必须使用
`xianyu-go/main`,不能只对照本地分支。
- 当前工作树包含大量未提交和未跟踪文件。后续迭代必须原地保护这些修改,禁止 reset、覆盖或
以重建分支代替审计。
- 远端 `main` 的空卡密修复与当前前端 API 文件存在文本合并冲突。当前代码必须持续保证服务端
空列表编码为 `[]`,前端同时接受数组、包裹对象和 `null`;对应回归测试是强制契约。
- 远端 `main` 的文档链接变更不影响运行功能。生成前端资产的文本冲突必须通过当前源码重新构建
解决,禁止手工合并压缩产物。
- 先前关于 Server 组合根、应用生命周期、React Feature 化和 DB 治理的完成声明均撤销为“待重新验收”。
当前 `internal/server` 仍构造应用服务和 worker 并持有基础设施相关依赖;阶段 4 必须先完成组合根迁移。
- 账号敏感摘要与秘密访问已经分离,并已有审计和多数据库覆盖;阶段 2 可视为完成,但后续迭代
不得重新扩大读取、解密、序列化或日志范围。
- HTTP `/api/v1` 版本化、具名 DTO、统一错误、前端兼容归一和调用方审计已完成阶段 3 验收;
受控的设置键、账号绑定键和触发统计键仍按兼容清单保留,删除条件记录在
`docs/architecture/api-compatibility-matrix.md`。
- Engine `Account` 与 Automation `Center` 已有部分组件化实现,但其生命周期、关闭顺序和并发状态仍须在
阶段 5 重新验收。集中前端 API/类型文件和商品发布异步状态属于阶段 6 的后续范围。
- 三方言迁移编号当前对齐,订单已有游标和批量写入能力;跨 repository 事务、查询计划、补偿和
大数据量行为仍需阶段 8 统一验收。
- 注释历史基线文件当前为空,但源码仍存在“保存 X 供当前流程使用”等模板化注释。机械基线清零
不等于注释质量达标,阶段 10 尚未验收。
- 与远端 `main` 相比,受冻结规范保护的 CAPTCHA 文件存在差异。其当前行为必须以仓库内冻结规范
和全部冻结测试为准;没有用户明确授权不得修改、回退或借重构重新合并这些文件。
## 4. 迭代状态与唯一顺序
阶段状态只允许使用 `前置完成`、`已完成`、`当前迭代`、`待执行`、`阻塞`。只有一个阶段可以是
`当前迭代`;后续阶段已有的提前实现代码只作为该阶段未来验收的输入,不代表阶段已启动或完成。
| 阶段 | 状态 | 迭代目标 |
| 阶段 | 状态 | 严格结论 |
| --- | --- | --- |
| 0. 治理与强约束 | 前置完成 | 建立计划、依赖、注释、冻结规范和自动检查 |
| 1. CI 与测试基础 | 已完成 | 建立独立 CI、分层 race 和三数据库门禁 |
| 2. 敏感数据访问边界 | 已完成 | 分离摘要、平台凭证、登录秘密和敏感设置 |
| 3. HTTP API 契约 | 已完成 | 完成版本化、具名 DTO、统一错误和前端契约 |
| 4. Server 应用服务 | 当前迭代 | 把完整业务用例和事务边界移出 transport,并完成启动稳定性修复 |
| 5. 应用装配、生命周期、Engine 与 Automation | 待执行 | 消除隐式装配、业务 worker 和游离后台任务并重新验收状态所有权 |
| 6. React Feature 化与异步状态 | 待执行 | 完成 feature 边界、请求归属、状态和按路由加载 |
| 7. DB 与事务治理 | 待执行 | 完成窄 repository、Unit of Work 和三方言验收 |
| 8. 架构门禁与兼容退场 | 待执行 | 封死依赖旁路并按 Sunset 删除兼容层 |
| 9. 注释与复杂度收口 | 待执行 | 清除模板注释和复杂度债务,形成最终质量门禁 |
| 10. 最终全栈复验 | 待执行 | 以完整 Go、Browser、三方言和前端证据关闭计划 |
| 1. 稳定性、安全和启动生命周期 | 已完成(既有基线) | 已按当前工作树复核原子 data key、同步 Bind、启动回滚、无秘密告警及该阶段命令。六阶段治理建立时这些改动已经存在;禁止为纠正历史提交名重新提交或改写历史。 |
| 2. Server 组合根和应用服务迁移 | 已完成 | `internal/composition` 已成为唯一生产组合根;旧 Server 组合根与生命周期反转已删除。Server 仅接收经校验的消费者 Port,阶段二 AST 门禁和完整验收均已通过。最终提交绑定见 `refactoring-progress.md`。 |
| 3. 生命周期、Engine 和 Automation 重新验收 | 当前阶段 | 阶段二组合根已稳定;现在必须重新验收 worker owner、Context、取消、等待和关闭顺序,已有实现只作为输入。 |
| 4. React Feature 化和异步状态修复 | 待执行 | ApiError、定位和批量状态代码是输入;DTO barrel、根级地图服务和 DTO 直连仍未收口。 |
| 5. DB 与事务治理重新验收 | 待执行 | 不得提前。 |
| 6. 全量架构、兼容退场和注释收口 | 待执行 | 门禁规则已在基础验证层预建;本阶段只激活最终质量规则、清零违规并完成兼容和注释退场。 |
执行顺序固定为 `0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10`。除阻塞性
安全修复、构建修复或用户明确改序外,不得跳过当前阶段推进后续阶段。例外只解决阻塞问题,不能
借机开启另一个重构阶段。
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。阶段二已完成,阶段三是唯一允许继续执行的阶段;阶段四及之后不得提前执行。
### 4.1 阶段级实施矩阵
## 阶段一:稳定性、安全和启动生命周期
| 阶段 | 主要改动位置与实施方式 | 最终验收与禁止项 |
| --- | --- | --- |
| 4. Server 应用服务(当前) | `cmd/server` 先同步 `Bind`,再启动协调器,最后 `Serve`;数据密钥采用 `O_CREATE|O_EXCL` 并处理竞争、空文件和写入失败。由 `cmd/server` 与 `internal/adapter` 组装不可变 `server.Dependencies`/`ApplicationServices`,`internal/server` 仅保留 transport、DTO 和路由;删除 Server worker factory、`ApplicationLifecycleComponents()` 与基础设施生产持有。 | 运行本阶段 Server/application/adapter race、`go vet`、lint、comments、architecturecheck 和 `git diff --check`。保留 `:59188` 与远程网页首次初始化,只输出无秘密高等级警告并在文档说明部署者风险。 |
| 5. 生命周期、Engine 与 Automation | `cmd` 独占 coordinator;为账户、自动化、续期、通知、浏览器、订单刷新、批量发布和 reconciliation 补齐 owner、Context、Cancel、Wait/Join、失败回滚和关闭顺序测试。 | 全量 Go、指定 race 和浏览器集成测试;不编辑任何冻结 CAPTCHA 文件、调用顺序或规范。 |
| 6. React Feature 化与异步状态 | 将 `shared/api-contract/index.ts` 按 session/accounts/items/orders/automation/notifications/settings/chat/cards-admin/common 拆分,feature adapter 直接导入领域契约并转换 UI model;地图服务归入 items feature。统一 `ApiError`,为定位与批量轮询使用独立 AbortController/generation/timeout;清理未使用符号后启用 TypeScript 未使用检查。 | Vitest、typecheck、comments、build、V8 coverage 与嵌入资源重建。不得让组件直接请求网络或以大型 barrel 隐藏跨领域依赖。 |
| 7. DB 与事务治理 | 清除上层 `Store.DB`、`*sql.DB`、`*sql.Tx` 与 row model 泄露;跨 repository 原子操作通过应用层 Unit of Work;补齐 claim、lease、取消、重试、不确定结果和补偿测试。 | SQLite 并发/事务测试、MySQL/PostgreSQL 迁移/CRUD/并发 claim、`cmd/dbverify` 完整证据。 |
| 8. 架构门禁与兼容退场 | 扩展 AST/源码检查以覆盖 Server 低层依赖、应用 Port 泄露、service locator、动态 import、前端依赖方向和根 services 旁路;仅在遥测、Sunset、调用方迁移和契约测试齐备时删除兼容入口。 | 不得新增白名单或扩大 baseline;同步旧路由、Vite 代理、契约测试与嵌入资源。 |
| 9. 注释与复杂度收口 | 清除模板化中文注释,处理超大文件/高复杂度与依赖绕过门禁;不以机械注释或格式化代替责任拆分。 | `make comments`、全量质量门禁和覆盖率;不扩大历史基线。 |
| 10. 最终全栈复验 | 只处理前序阶段验收暴露的阻塞缺陷,并汇总最终提交、完整命令、Go/前端覆盖率和真实外部例外。 | 运行全量 Go/race/lint/comments/architecturecheck/前端门禁,适用时运行浏览器和三方言验证;最终提交可启动。 |
范围:data key 使用 O_CREATE|O_EXCL,覆盖竞争、空文件、写失败和读竞争;Bind 先于 worker 和
Serve;覆盖重复 Start/Stop、已 Bind 未 Serve、启动回滚;修复 SA1012;非 loopback 未初始化只输出
不含秘密的高等级告警并更新部署文档。
## 5. 阶段 0:治理与强约束
~~~text
go test ./cmd/server ./internal/server ./internal/notify -count=1
go test -race ./cmd/server ./internal/server ./internal/notify -count=1
go vet ./...
make lint
git diff --check
~~~
### 目标
既有基线:不追补提交,不改写历史。后续涉及其代码时,必须在所属阶段重新运行相关命令。
建立所有后续迭代共同遵守的边界、冻结行为和检查入口。阶段 0 是前置治理,不占十个正式迭代。
## 阶段二:Server 组合根和应用服务迁移(已完成)
### 范围
组合根必须由独立 composition 包或等价独立组合层负责;cmd/server 只构造基础设施并调用它;
Server 只接受不可变完成依赖。
- 维护本计划、`dependency-rules.md`、`comment-standard.md` 和 `AGENTS.md`。
- 冻结滑块 CAPTCHA 实现、调用链和测试。
- 提供架构检查、Go/TypeScript 注释检查和统一 Make 入口。
必须完成:
- 移出 internal/server/application_services.go 中所有 service、runner、coordinator 和 adapter factory 的生产构造。
- 删除 server.NewApplicationServices 业务组合根、Server.ApplicationServices() 和 LifecycleComponents() 生命周期反转。
- Server 不得持有或调用 MTOP、长登录、QR 登录、Manager、automation、Notifier、DB、Store、session 或具体平台 implementation。
- 订单运行时、聊天发送、批量发布、账号登录、Session 恢复、通知测试发送、聊天已读上报全部通过应用 Port。
- architecturecheck 扫描真实生产源码,禁止 Server 调用 service/runner/coordinator 构造函数和通过 adapter factory 间接构造业务服务。
- 测试覆盖缺失依赖、正常、越权、失败、取消、补偿、启动回滚和独立关闭。
### 完成条件
### 执行形态(对后续 agent 的硬性指导)
- 文档规则互不矛盾,执行单位明确为一个阶段对应一个 PR/迭代。
- 自动检查可在本地和 CI 运行,新增债务不能借历史基线通过。
- 本计划不包含任何历史日志或阶段内完成记录。
1. 新建独立组合层(建议 `internal/composition`);它是唯一允许同时导入 `internal/application`、
`internal/adapter`、`internal/account`、`internal/automation`、`internal/browser`、`internal/notify`
与平台依赖的生产装配位置。`cmd/server/main.go` 只构造基础设施、调用组合层、登记其返回的生命周期
组件并启动 HTTP Server。
2. 将 `internal/server/application_services.go` 的构造函数、`ApplicationServiceDependencies`、生命周期
组件生成和 callback 闭包移到组合层及对应的应用/adapter 包。完成后删除该文件,而不是改名保留;
`internal/server` 不得再出现 `New*Service`、`New*Runner`、`New*Coordinator` 或 adapter factory 调用。
3. `server.Dependencies` 只能包含 HTTP 所需的认证、日志、静态资源、健康检查与由 transport 消费者定义的
最小应用 Port。它不得引用 `adapter` 的平台客户端接口、`account.Manager`、`automation.Center`、
`notify.Notifier`、`chat.Service`、`db.Store`、`sql.DB` 或 `sql.Tx`。`PlatformPort`、`mtopClient`、
`longLoginClient`、`qrLoginService`、`sessionRecoveryCallback` 与测试专用可变平台 Port 一并删除或迁至
应用/adapter 测试。
4. 按用例而非基础设施对象迁移 handler:二维码登录、账号登录与长登录、Cookie/session 恢复、订单运行时、
聊天发送和已读上报、通知测试发送、商品批量发布分别接收消费者定义的应用 Port。handler 只做 DTO
解析、当前用户提取、调用、错误到 HTTP 的映射;不得传递 `Server` callback 给 adapter。
5. 组合层返回不可变的 `server.Dependencies` 和独立 `[]lifecycle.NamedComponent`。`cmd/server` 直接向
`lifecycle.Coordinator` 登记该列表;禁止从 Server 或 Server 持有的服务集合反向读取生命周期组件。
6. 重写 `tools/architecturecheck` 为 fail-closed AST 扫描,并增加真实仓库扫描和正反例测试:扫描全部
非测试 `internal/server/**/*.go` 与 `cmd/server/**/*.go`,拒绝上述类型、字段、构造调用、factory 调用、
Server callback、service locator 及测试专用 setter 的生产使用。现有仅按少量函数名匹配的检查不能作为
阶段完成证据。
7. 所有现有 Server 测试随用例归属迁移:transport 测试只替换应用 Port fake;业务、平台、恢复和 worker
测试进入 application/adapter。为组合层补齐缺失依赖、构造失败、启动回滚和关闭顺序测试。不得因为迁移
删除现有错误路径、越权、取消、租约或晚到结果断言。
8. 阶段二门禁在迁移开始时即启用,且没有临时白名单:`tools/architecturecheck` 必须拒绝
`application_services.go`、Server/cmd 中的 adapter 或业务运行时依赖、Server 平台 Port、组合根 API、
生命周期反转、应用/adapter 构造链,以及缺失或未被 `cmd/server` 调用的 `internal/composition`。阶段内
门禁失败表示未完成迁移,不得降级为告警;最终提交前必须归零。
### 强制验证
```bash
go run ./tools/architecturecheck
go run ./tools/commentlint -mode check -root .
npm --prefix frontend run comments:check
```
## 6. 阶段 1:CI 与测试基础
### 目标
让每个后续迭代都能在独立、稳定、耗时可控的门禁上验收。
### 范围
- PR CI:Go test/vet/lint、架构、注释、前端 test/typecheck/build。
- 普通测试与生命周期/凭证并发 race 分层。
- SQLite 快速回归和 Docker MySQL/PostgreSQL 严格回归。
- 测试数据库模板、确定性 fixture 和覆盖率产物隔离。
### 完成条件
- CI 不依附发布 workflow,失败会阻止合并。
- race 子集覆盖高风险并发路径,完整 race 可在需要时执行。
- `make test-multidb` 缺少任一外部数据库 URL 时明确失败,而不是静默跳过。
### 强制验证
```bash
make check
make test-server-race
TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb
npm test --prefix frontend
npm run build --prefix frontend
```
## 7. 阶段 2:敏感数据访问边界
### 目标
让每个用例只读取完成任务所需的最小数据,阻止秘密进入摘要、所有权查询、HTTP DTO 和前端状态。
### 范围
- 分离 `AccountSummary`、`AccountCredential`、`AccountLoginSecret` 和运行配置。
- 所有权查询只返回存在性、所有者 ID 或非敏感身份。
- 敏感读取使用目的明确的方法,管理/一次性读取有审计且失败时 fail closed。
- 日志、通知、错误和测试输出集中脱敏。
- SQLite、MySQL、PostgreSQL 验证加密、损坏密文、跨用户和迁移行为。
### 完成条件
- 账号列表、详情、状态、商品、订单、聊天和规则校验不读取 Cookie、Token 或密码。
- 敏感持久化模型不被 HTTP 序列化,前端类型不包含可回填的明文秘密。
- 高频运行时不会为普通摘要读取反复解密或写审计。
- 三数据库的敏感字段 CRUD、迁移和失败语义一致。
### 强制验证
```bash
go test ./internal/db ./internal/account ./internal/server -count=1
go test -race ./internal/account ./internal/server -count=1
TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb
make comments
```
## 8. 阶段 3:HTTP API 契约
### 目标
在不破坏当前客户端的前提下完成统一 `/api/v1` 契约、具名 DTO、统一错误和可验证的前端类型边界。
### 范围
- 为全部业务入口提供 `/api/v1` 路径;旧路径只作为调用同一 handler 的兼容适配器。
- 请求、成功响应、分页结果、批量行结果和错误详情全部使用具名 DTO。
- 清除 QR、订单导入/批量结果、聊天和设置 transport 中作为响应契约的动态 map。
- 统一错误 envelope、错误码和 HTTP 状态;禁止新增 `HTTP 200 + success:false`。
- 建立单一契约来源和只读生成类型;feature adapter 将 transport DTO 转换为 UI model。
- 固定空集合为 `[]`,并兼容当前发布链路可能返回的 `null` 或历史包裹对象。
- 契约测试同时覆盖版本化路径和仍被支持的旧路径。
### 完成条件
- 生产 handler 不直接返回数据库模型、领域模型、匿名 struct 或动态 map 契约。
- 前端业务 API 不再依靠 `any` 猜测响应形状;兼容归一只发生在 feature/transport 边界。
- 所有新增失败使用统一错误结构和正确状态码。
- 当前前端只调用 `/api/v1`;旧路径保留范围和删除条件可由测试清点。
- 空卡密、空订单、空商品等集合不会因 `null` 阻断页面其他并行请求。
### 强制验证
```bash
go test ./internal/server -count=1
npm test --prefix frontend
npm run typecheck --prefix frontend
npm run build --prefix frontend
go run ./tools/architecturecheck
make comments
```
## 9. 阶段 4:Server 应用服务
### 目标
使 Server 成为纯 transport,把订单、商品、账号、登录、聊天、通知、自动化和管理员用例交给应用服务。
### 范围
- handler 只做鉴权上下文、参数解析、DTO 转换和应用错误到 HTTP 的映射。
- 应用服务负责所有权、业务校验、跨步骤编排、事务选择和补偿决策。
- Port 由应用消费者定义,不暴露 `db.*`、`*sql.Tx`、HTTP、Server、MTOP 或 browser 类型。
- 删除 Server 中遗留的 `*sql.Tx` 执行器、无调用兼容服务和低层 helper。
- 审查集中式 `adapter.Dependencies`;改为显式、类型化构造,不得成为隐藏 Store 的 service locator。
- 把仍在 Server 内的账号登录持久化、平台会话和业务 worker 操作迁到应用边界。
### 完成条件
- Server 生产代码不导入 `database/sql`、`internal/db`、`internal/xianyu` 或 `internal/browser`。
- Server 不持有 repository 聚合入口,不创建事务,不执行平台业务动作。
- 应用包不依赖 HTTP、chi、DB、Server 或平台实现。
- 每个完整用例的正常、越权、缺失、失败、取消和补偿分支有应用层测试。
- 构造器缺失必需依赖时立即返回错误,不在请求期 panic 或延迟发现。
### 强制验证
```bash
~~~text
go test ./internal/application/... ./internal/adapter ./internal/server -count=1
go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
go run ./tools/architecturecheck
go vet ./...
go run ./tools/architecturecheck
make lint
make comments
```
git diff --check
~~~
## 10. 阶段 5:应用装配与生命周期
最终提交:阶段二:完成 Server 组合根和应用服务迁移。
### 目标
完成结论:生产装配已迁入 `internal/composition` 与其 `runtime` 子层,`cmd/server` 只构造基础设施并调用
组合层;`internal/server` 不再构造业务服务、runner、coordinator 或平台实现,也不再反向返还生命周期组件。
Server 的应用依赖由消费者定义的不可变 Port 容器承载,构造期缺失任一必需 Port 即失败。完整原始验收输出、
冻结 CAPTCHA 差异检查和最终提交绑定只记录在 `refactoring-progress.md`。
明确所有组件、goroutine、连接、timer、channel 和 worker 的所有者、Context、停止与等待边界。
## 阶段三:生命周期、Engine 和 Automation 重新验收(当前阶段)
### 范围
明确每个 worker 的 owner、Context、Cancel、Wait/Join;cmd 独占协调器;Server Stop 只收束 HTTP;
覆盖启动失败、取消、超时、重复关闭、晚到结果和关闭顺序;可在本阶段修复 Engine/Automation 状态问题,
但不得改动冻结 CAPTCHA。
- `cmd` 显式构造全部必需依赖并负责启动顺序和反向关闭顺序。
- 消除必需依赖 setter、请求期懒装配和部分构造可见状态。
- 把订单刷新、批量发布、恢复、reconciliation 和实时连接等业务 worker 移出 Server transport。
- 每个后台任务提供 owner、Context 来源、Cancel、Wait/Join、超时和观测状态。
- 所有通知、平台、续期、二维码、WebSocket 和浏览器外部调用都必须响应所属 Context;无法中断的同步调用必须有明确硬超时并在清单中记录。
- 账号删除先 fencing,受限等待运行时退出,再复核归属并删除。
- Stop/Close 在契约允许时幂等;晚到写入由 generation、lease 或 token 拒绝。
- 清空 `lifecycle-inventory.md` 中的剩余风险后,将其保留为静态组件清单而非进度日志。
### 完成条件
- Server 不保存业务 worker 的锁、cancel map、任务状态或平台会话状态。
- 所有 goroutine 都能由拥有者取消并等待,不使用超时后遗留的等待 goroutine。
- 重复 Start/Stop、先 Stop、启动失败回滚、超时和晚到写入有确定性测试。
- 关闭顺序不持锁等待网络、浏览器或用户操作。
- 生命周期审计清单记录每个外部调用的取消路径、硬超时、无法取消的实现约束和可重试 Join 入口。
### 强制验证
```bash
go test ./internal/server ./internal/account ./internal/engine ./internal/automation ./internal/renewal -count=1
go test -race ./internal/server ./internal/account ./internal/engine ./internal/automation ./internal/renewal -count=1
~~~text
go test ./... -count=1
go run ./tools/architecturecheck
```
## 11. 阶段 6:Engine 与 Automation
### 目标
将大型 facade 拆成状态所有权明确、可独立测试的组件,同时保持平台协议和冻结 CAPTCHA 行为不变。
### 范围
- Engine 分离连接会话、消息分发、去重、防抖、凭证协调、重试和运行状态。
- Automation 分离规则解析、调度、运行协调、动作执行、库存分配、通知和补偿。
- 建立统一账号凭证协调器:快照、版本校验、锁外外部 I/O、条件提交和冲突观测。
- 外部动作使用幂等键和 `succeeded/failed/uncertain` 三态;不确定结果进入人工核对或补偿。
- 明确凭证锁、自动化库存锁和 worker 锁的顺序。
- `Account` 与 `Center` 只保留稳定 facade,不继续拥有全部内部可变状态。
### 完成条件
- facade 的体积和字段职责显著收敛,每个并发组件有独立生命周期和 race 测试。
- 未在任何互斥锁或数据库事务内执行不可控平台、浏览器或用户等待 I/O。
- 凭证冲突、取消、超时、旧响应、重复事件和重连均有确定性测试。
- 发货、评价、求评价、卡密和通知的幂等及不确定态不发生自动重复动作。
- 所有冻结 CAPTCHA 测试通过,受保护文件没有未经授权的行为变化。
### 强制验证
```bash
go test ./internal/engine ./internal/automation ./internal/browser -count=1
go test -race ./internal/engine ./internal/automation -count=1
go test -race ./internal/server ./internal/engine ./internal/automation ./internal/renewal
RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
go run ./tools/architecturecheck
make comments
```
go run ./tools/architecturecheck
~~~
## 12. 阶段 7:React Feature 化
最终提交:阶段三:完成生命周期、Engine 和 Automation 重新验收。
### 目标
## 阶段四:React Feature 化和异步状态修复
完成 `app -> features -> shared` 的真实所有权拆分,而不是只移动页面文件或增加 barrel export。
这是一个完整前端阶段,不拆 HTTP 错误、契约、地图、轮询或构建交付:
- ApiError 保留 status、code、message、request_id、details、payload;JSON/FormData 共用错误解析。
- shared/api-contract/index.ts 拆为 session、accounts、items、orders、automation、notifications、settings、chat、cards、admin、common 直接模块;feature adapter 直接导入领域契约并输出 UI model。
- 地图物理迁入 items;locateForPublish 等待定位和搜索;每次请求 AbortController + generation + timeout,旧响应不得写回。
- pending、running、canceling 统一视为进行中;每个轮询 effect 独立取消;覆盖重启、关闭重开、晚到响应、取消和卸载。
- 清理未使用符号并开启 noUnusedLocals/noUnusedParameters;Vite 重建 internal/webui/static。
### 范围
- `app` 只保留 Provider、认证壳、路由和错误边界。
- 每个 feature 拥有 page、components、hooks/state、API adapter、UI model 和行为测试。
- 拆除集中式 `frontend/services/api.ts` 和 `frontend/types.ts` 的业务职责。
- shared HTTP client 只处理超时、取消、认证和统一错误,不包含领域归一。
- 服务端数据、表单状态和短暂 UI 状态分离;派生值不重复存入 state。
- 异步 effect 使用取消或 generation,独立请求并行启动,旧响应不得覆盖新状态。
- 页面和重型可选依赖按路由/feature 懒加载,并设置初始包体预算。
### 完成条件
- feature 不导入其他 feature 内部文件,shared 不反向导入 feature。
- React 组件不直接 `fetch`/`axios`,业务 DTO 转换只在本 feature API adapter。
- 不再存在承担多个领域的集中 API/类型文件或超大 Hook。
- 关键流程具有成功、失败、取消、切换、乱序响应和卸载测试。
- 构建产物由当前源码生成并更新嵌入目录,初始包体满足预算。
### 强制验证
```bash
~~~text
npm test --prefix frontend
npm run typecheck --prefix frontend
npm run comments:check --prefix frontend
npm run build --prefix frontend
make cover-frontend
git diff --check
```
~~~
## 13. 阶段 8:DB 与事务治理
最终提交:阶段四:完成 React Feature 化和异步状态修复。
### 目标
## 阶段五:DB 与事务治理重新验收
完成窄 repository、应用层 Unit of Work、批量查询写入、补偿持久化和三方言一致性。
清除上层 Store.DB、sql.DB、sql.Tx 和 row model 泄露;跨 repository 原子操作使用 Unit of Work;验证
claim、lease、取消、重试、不确定远程结果和本地补偿;补齐 SQLite 并发和事务测试,并运行 MySQL、
PostgreSQL、cmd/dbverify。任何发现的 repository、迁移或补偿缺陷必须在本阶段同一提交中完成。
### 范围
- SQL、方言、row model 和加密只留在 `internal/db` 与基础设施 adapter。
- 跨 repository 原子操作通过消费者定义的 Unit of Work 执行。
- 清除上层 `*sql.DB`、`*sql.Tx`、DB row 和完整 `Store` 暴露。
- 商品/订单同步使用游标、批量读取、批量 UPSERT 和明确缓存失效,消除 N+1。
- 不可逆外部动作的补偿记录、lease、幂等键和人工核对状态跨重启持久化。
- 所有迁移在 SQLite、MySQL、PostgreSQL 使用相同编号和最终 schema。
- 对高频查询提供三方言查询计划和大数据量回归。
### 完成条件
- handler、React 和领域组件不控制数据库事务。
- 跨 repository 失败原子回滚;外部成功后的本地失败进入可恢复或不确定状态。
- 三方言迁移、CRUD、事务、并发 claim、软删除、批量写入和补偿行为一致。
- 大数据量测试证明没有逐账号、逐订单或逐商品的无界查询放大。
### 强制验证
```bash
~~~text
go test ./internal/db ./internal/application/... ./internal/adapter -count=1
go test -race ./internal/db ./internal/application/... ./internal/adapter -count=1
TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb
go run ./cmd/dbverify "$TEST_MYSQL_URL"
go run ./cmd/dbverify "$TEST_POSTGRES_URL"
```
git diff --check
~~~
## 14. 阶段 9:架构门禁与兼容退场
最终提交:阶段五:完成数据库与事务治理重新验收。
### 目标
## 阶段六:全量架构、兼容退场和注释收口
把目标依赖图和兼容删除条件变为 fail-closed 门禁,删除所有临时例外和已到期兼容路径。
门禁框架和全部阶段规则已经前置建立,本阶段不得重新发明或补写基础规则。本阶段激活最终质量门禁,
处理此前各阶段持续开启的全部边界,并清零 service locator、动态 import、前端依赖方向、根级 services
旁路、模板注释、复杂度和超大文件违规。兼容入口只在遥测、Sunset、调用方迁移和契约测试齐备后删除;
不得扩大 baseline、增加白名单或跳过测试。
### 范围
- 检查 Server 的 `database/sql`、低层 import、业务 worker、裸 Store 和事务暴露。
- 检查应用 Port 是否泄露 DB/HTTP/Server/平台实现类型。
- 检查 service locator、运行时必需 setter、反射/动态 import 隐藏依赖。
- 检查前端 app/features/shared 依赖方向、组件直接请求和集中式 barrel。
- 为旧路径和兼容字段建立调用遥测、Deprecation、Sunset 版本和删除测试。
- 删除调用方已迁移的旧路由、别名、适配器、白名单和死代码。
### 完成条件
- 架构检查覆盖完整目标图且无临时白名单。
- 所有保留兼容入口都有已知调用方、遥测和明确删除版本。
- 到期旧路径删除后,前端、契约测试、Vite 代理和嵌入资产同步更新。
- `go list`、AST、TypeScript/ESLint 规则无法通过简单中转层绕过。
### 强制验证
```bash
go run ./tools/architecturecheck
~~~text
go test ./... -count=1
go test -race ./internal/server ./internal/engine ./internal/automation -count=1
go vet ./...
make lint
make comments
go run ./tools/architecturecheck
go test -race ./internal/server ./internal/engine ./internal/automation
npm test --prefix frontend
npm run typecheck --prefix frontend
npm run comments:check --prefix frontend
npm run build --prefix frontend
```
## 15. 阶段 10:注释与复杂度收口
### 目标
让中文注释准确描述业务、敏感性和并发约束,并把过长函数和高复杂度热点降到可维护范围。
### 范围
- 删除“保存 X”“负责 X”“表示错误”等模板化或复述语法的注释。
- 为函数、参数、返回值、变量、字段、闭包和 React 状态补充准确中文语义。
- 并发代码说明 owner、锁保护字段、锁顺序、Context、Cancel 和 Wait。
- 敏感值说明明文作用域、日志/序列化禁令和清理责任。
- 增加模板短语、复杂度和超大文件门禁;冻结文件只使用精确例外。
- 删除全部注释历史基线机制和已无必要的例外。
### 完成条件
- Go、TypeScript、TSX 无历史注释豁免,无模板化占位注释。
- 自动检查和人工抽查同时通过,注释与当前行为一致。
- 高复杂度函数被按业务责任拆分,未用注释掩盖结构问题。
- 全量测试、race、覆盖率、架构、lint、前端构建和三数据库门禁全部通过。
### 强制验证
```bash
make comments
make check
make cover
make cover-browser
make cover-frontend
TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb
npm run build --prefix frontend
```
git diff --check
~~~
## 16. 迭代强制约束
适用时还运行浏览器集成、MySQL/PostgreSQL 和两个 cmd/dbverify 命令。最终提交:阶段六:完成全量架构、
兼容退场和注释收口。
### 16.1 执行单位与提交
## 执行纪律
1. 阶段 1 至阶段 10 各是一个完整迭代、一个阶段级 PR 和一个最终交付提交。
2. 阶段可同时修改多个 Go 包、多个前端 feature、测试、架构门禁和文档;不得把阶段内工作再拆成独立交付、独立验收或独立 PR。
3. 本地可以使用临时提交或工作区操作,阶段内部允许暂时不可编译;最终阶段提交必须可编译、可启动、可测试并通过全部适用门禁。
4. 阶段未满足全部完成条件时不得标记为“已完成”,也不得以大提交掩盖未完成分支、错误路径或覆盖率缺口。
5. 不改写已有 Git 历史,不覆盖无关工作树修改,不以重建分支代替合并和冲突审计。
6. 仍禁止无关重命名、全仓格式化、削弱/删除测试与覆盖率、扩大兼容白名单和修改冻结 CAPTCHA。
7. 阶段完成证据必须绑定最终阶段提交和完整命令输出;中间提交、局部命令或先前声明不能单独关闭阶段。
1. 开始一个阶段前,只允许读取总计划状态表并审查当前工作树;不得根据旧阶段编号或已落地代码跳阶段。
2. 阶段进行期间不创建提交、不更新阶段状态、不写局部完成记录,也不向后续阶段交付任何实现。
3. 阶段最终验收失败时,状态仍是当前阶段;修复全部失败项后重新执行完整命令,不得只重跑失败命令。
4. 仅在全部命令成功后,按一次操作更新状态表、验收记录、完成证据和下一阶段入口,再创建唯一中文提交。
5. 已存在的正确实现只能作为后续阶段的输入;不能单独改变正式阶段状态,也不得被回滚、清理或拆分重做。
### 16.2 行为与兼容
## 门禁激活规则
1. 重构默认不改变业务行为、HTTP 状态、JSON 字段、重试、超时、幂等或错误优先级。
2. 与 `main` 比较必须使用最新远端目标;先分析文本冲突,再用契约测试判断功能冲突。
3. 空集合统一输出 `[]`,前端兼容当前仍可能存在的 `null` 和历史包裹对象。
4. 新 API 使用 `/api/v1` 和具名 DTO;禁止新增动态 map 响应或 `HTTP 200 + success:false`。
5. 兼容适配器必须记录调用方、删除条件和 Sunset 版本;条件满足前不得删除。
6. 前端源码变化后必须重新构建 `internal/webui/static`,禁止手改哈希资产。
### 16.3 敏感数据
1. 摘要和所有权检查不得读取或解密 Cookie、Token、密码或加密 metadata。
2. 平台凭证和登录秘密使用不同模型及目的明确的 repository 方法。
3. 敏感持久化模型不得进入 HTTP、前端状态、日志、通知、错误或测试失败输出。
4. 管理/一次性敏感读取必须审计且 fail closed,高频运行时使用窄读取。
5. 不得持凭证锁执行未受规范保护的慢速网络、浏览器或用户等待 I/O。
### 16.4 数据库与事务
1. 上层不得新增裸 `*sql.DB`、`*sql.Tx` 或完整 Store;跨 repository 原子操作使用应用 Unit of Work。
2. SQL row、持久化模型、应用模型和 HTTP DTO 不得合并为同一便利类型。
3. 数据库变化必须同时维护 SQLite、MySQL、PostgreSQL 编号和最终 schema。
4. 迁移、方言 SQL、claim、锁、批量写入或补偿变化必须执行 Docker 三数据库回归。
5. 禁止通过逐行查询、无界并发或扩大事务范围掩盖 repository 设计问题。
### 16.5 生命周期与并发
1. goroutine、timer、channel、WebSocket、browser 和 worker 必须有 owner、Context、Cancel、Wait/Join。
2. 必需依赖由构造器输入并在 Start 前验证;禁止生产路径使用 setter 补齐必需依赖。
3. Stop/Close 按契约幂等,超时不得制造新的游离等待 goroutine。
4. channel 由约定发送方关闭;晚到响应由 generation、lease、版本或 token fencing 拒绝。
5. 锁保护字段和锁顺序必须注释并测试;禁止持锁等待不可控外部 I/O。
6. 外部动作必须有幂等键、成功/失败/不确定三态、补偿、重试和人工核对边界。
### 16.6 React
1. 依赖方向固定为 `app -> features -> shared`;feature 不导入其他 feature 内部文件。
2. 组件不直接请求网络,shared HTTP client 不包含领域归一逻辑。
3. 服务端数据、表单状态和短暂 UI 状态分离;可派生值不重复存 state。
4. 异步 effect/request 必须可取消或有 latest-generation 保护;独立请求并行启动。
5. 不因习惯增加 memo;重型页面和可选依赖按路由/feature 懒加载。
6. 新或重大流程必须覆盖成功、失败、取消、切换、乱序和卸载,不用源码字符串测试替代行为测试。
### 16.7 冻结 CAPTCHA
1. 未经用户在当前任务明确授权,不得编辑、移动、格式化、回退或间接改变受保护文件和调用链。
2. 不得改变选择器、258px 标准距离、轨迹、时序、fresh `x5sec`、重试、profile、Cookie 合并、
Playwright/CDP 顺序、启动参数或结果标签。
3. 发现与基线差异时只做只读审计;任何行为调整必须同时更新实现、全部测试和冻结规范。
4. 涉及 browser、登录、凭证、engine、account 或 server 调用路径时必须运行冻结规范要求的验证。
### 16.8 注释、测试与覆盖率
1. 所有新增或修改的 Go/TypeScript/TSX 函数和变量必须有准确中文注释。
2. 禁止“err 表示错误”“变量 X 保存 X”等模板化注释,自动检查通过不能替代语义审查。
3. 每个确定性函数、分支和错误路径必须有聚焦测试;禁止删除、跳过或放宽测试来通过重构。
4. 测试可跳过的范围仅限真实账号、私有平台状态或不可用外部服务;本地浏览器和数据库不得假跳过。
5. 覆盖率声明必须写明命令、浏览器开关、Go/前端百分比和真实外部例外,但不得写入本计划。
## 17. 阶段统一验收矩阵
| 变化范围 | 最低验证 |
| --- | --- |
| 任意 Go | 聚焦测试、`go test ./... -count=1`、`go vet ./...`、架构、Go 注释、`git diff --check` |
| HTTP/应用服务 | Server 与应用契约测试、错误/越权/取消测试、Server race |
| Engine/Automation/生命周期 | 聚焦 race、Stop/Close/超时/晚到写入、全量 Go test |
| 数据库/事务/迁移 | SQLite 聚焦、Docker MySQL/PostgreSQL、`cmd/dbverify`、并发 claim/回滚 |
| React/前端 API | Vitest、typecheck、前端注释、V8 coverage、生产构建、嵌入资产校验 |
| Browser/登录/凭证 | 冻结测试、浏览器集成、凭证 race、日志脱敏检查 |
| 阶段完成 | 该阶段全部强制验证 + `make check` + 适用覆盖率,不允许只凭单项门禁关闭 |
## 18. 计划维护规则
1. 本文只允许修改目标、阶段范围、状态、验收条件、固定顺序和强制约束。
2. 禁止在本文新增阶段内部的临时提交、逐文件进度或人员记录;阶段级完成证据维护在 `refactoring-progress.md`。
3. 阶段内临时发现写入 PR 描述或 issue,不写入总计划;只有改变阶段范围或验收条件时才更新本文。
4. 阶段完成时只更新一次状态表,并在验收记录中一次性写入最终提交、完整命令输出、覆盖率和下一阶段入口。
5. 若阶段被阻塞,只将状态改为 `阻塞`;阻塞原因和尝试过程留在任务报告,不写入本文。
1. 全部阶段规则在基础验证层预先写入自动门禁并具备正反例测试;每个阶段开始时只激活对应规则,之后才允许迁移生产代码。
2. 当前阶段门禁必须 fail-closed。阶段内出现违规是未完成工作的可见清单,不得通过白名单、baseline、忽略目录、字符串规避、反射、动态 import 或降低严重级别使其通过。
3. 前序阶段已完成的门禁继续保持启用。后续阶段专有门禁只能在其成为当前阶段时启用,避免以尚未执行的设计阻断当前阶段;但任何全局安全、冻结 CAPTCHA、依赖方向、测试和注释规则始终生效。
4. 阶段最终验收只接受“当前阶段及全部既有门禁均为零违规”的完整输出。门禁失败时不得更新阶段状态、完成证据或创建提交。
+66 -183
View File
@@ -1,201 +1,84 @@
# 重构阶段验收记录
本文件只记录阶段整体的验收证据、更新日志和阶段边界。阶段是唯一交付和评审单位;同一阶段可以
同时修改多个 Go 包、前端 feature、测试、架构门禁和文档。阶段中的本地工作区可暂时不可编译,只有
最终阶段提交必须可编译、可启动、可测试,并附上完整命令输出和覆盖率证据。
本文件只记录已经完成阶段的最终提交与验收证据。唯一阶段状态和顺序由
`refactoring-master-plan.md` 定义;阶段内工作、临时提交、切片和局部成功一律不记录。
当前复核结论:阶段 0–3 保持完成,阶段 4 是当前迭代,阶段 5–10 均待执行。此前关于 Server
组合根迁移、生命周期迁移、React Feature 化和 DB 治理的“已完成”证据已撤销为重新验收输入,不能
关闭任何阶段。后续 agent 不得把阶段拆成多个独立交付任务;可使用临时本地提交,但最终只合并阶段级提交。
## 阶段二:Server 组合根和应用服务迁移
## 阶段 4:治理与计划修正
- 最终提交绑定:本文件随最终提交 `阶段二:完成 Server 组合根和应用服务迁移` 一并进入 `HEAD`。
- 交付范围:删除 `internal/server/application_services.go` 和 Server 生命周期反转;引入
`internal/composition` 生产组合根及其 runtime 投影层;Server 以校验后的消费者 Port 承接全部 HTTP
用例;真实源码 AST 门禁拒绝 Server/cmd 重新装配业务服务、平台实现或 worker。
- 迁移回归修复:订单 repository 在 adapter 边界归一化不存在错误;测试平台 QR Port 保持动态替身代理,
不改变生产 Server 依赖的不可变性。
状态:当前迭代,尚未产生最终阶段提交。
目标与执行指导:在同一阶段完成数据密钥原子创建、HTTP 同步 Bind/启动回滚、非 loopback 未初始化
高等级无秘密告警、`notifier_test.go` 的 SA1012 修复、远程首次初始化风险文档,以及 Server 组合根迁移。
组合根必须在 `cmd/server` 和 `internal/adapter` 构造全部应用服务、runner、coordinator 与生命周期组件;
`internal/server` 只接收不可变的 `ApplicationServices` 和 `Dependencies`,保留 DTO/路由/错误映射,删除
业务服务和 worker 工厂、`ApplicationLifecycleComponents()`、manager/notifier/automation/platform/DB 生产持有。
完成证据:仅接受最终阶段提交绑定的完整命令输出;当前阶段仍在执行,以下命令是最终门禁:
### 强制验收原始输出
```text
go test ./cmd/server ./internal/server ./internal/notify -count=1
go test -race ./cmd/server ./internal/server ./internal/notify -count=1
go test ./internal/application/... ./internal/adapter ./internal/server -count=1
go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
go vet ./...
make lint
make comments
go run ./tools/architecturecheck
git diff --check
```
$ go test ./internal/application/... ./internal/adapter ./internal/server -count=1
ok xianyu-go/internal/application/account
ok xianyu-go/internal/application/admin
ok xianyu-go/internal/application/analytics
ok xianyu-go/internal/application/automation
ok xianyu-go/internal/application/cards
ok xianyu-go/internal/application/chat
ok xianyu-go/internal/application/defaultreply
ok xianyu-go/internal/application/items
ok xianyu-go/internal/application/keywords
ok xianyu-go/internal/application/lifecycle
ok xianyu-go/internal/application/notifications
ok xianyu-go/internal/application/orders
ok xianyu-go/internal/application/settings
ok xianyu-go/internal/adapter
ok xianyu-go/internal/server
## 阶段 3:HTTP API 契约
$ go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
ok xianyu-go/internal/application/account
ok xianyu-go/internal/application/admin
ok xianyu-go/internal/application/analytics
ok xianyu-go/internal/application/automation
ok xianyu-go/internal/application/cards
ok xianyu-go/internal/application/chat
ok xianyu-go/internal/application/defaultreply
ok xianyu-go/internal/application/items
ok xianyu-go/internal/application/keywords
ok xianyu-go/internal/application/lifecycle
ok xianyu-go/internal/application/notifications
ok xianyu-go/internal/application/orders
ok xianyu-go/internal/application/settings
ok xianyu-go/internal/adapter 204.415s
ok xianyu-go/internal/server 242.734s
状态:已完成。
$ go run ./tools/architecturecheck
architecturecheck: 通过
主要证据:业务入口使用 `/api/v1` 版本化路径、具名 DTO、统一错误 envelope 和前端兼容归一;空集合兼容、契约测试、前端构建和嵌入资源均已验证。
$ go vet ./...
(无输出,退出码 0)
## 阶段 4:Server 应用服务
$ make lint
golangci-lint run ./...
0 issues.
状态:已撤销,内容仅作为当前阶段的历史输入,不构成完成证据。
完成证据:
- Server 生产代码不再导入 `database/sql`、`internal/db`、`internal/xianyu` 或 `internal/browser`,不创建事务,也不持有通用 `adapter.Dependencies`。
- 订单刷新、订单补偿扫描、批量发布、二维码会话、账号登录、Cookie 写入、资料刷新、聊天刷新/订阅、商品发布和管理员删除均通过应用服务与消费者定义的最小 Port 编排。
- Session 失效恢复统一由 `adapter.SessionRecoveryHandler` 分类和记录脱敏诊断,再调用账号运行时应用端口;生产适配器不再把 `Server.recoverExpiredMTOPSession` 作为回调传入。
- 订单运行时使用 `adapter.OrderAutomation`、`adapter.OrderNotifier` 等 typed port;Server 不再编排 Manager、Automation 和 Notifier 闭包。订单补偿扫描由 `orders.ReconciliationRecoveryCoordinator` 拥有启动、取消、等待和关闭生命周期。
- 账号凭证恢复使用 `account.CredentialRefreshCoordinator` 按账号并发登记;慢速协议续期不在协调锁内执行,自动化唤醒经过 `CredentialWakePort`/`CredentialWakeService`。
- 所有必需领域依赖由显式类型化依赖组构造并在 `Server.New` 阶段校验;缺失依赖、越权、失败、取消、重复启动/关闭、租约 fencing、补偿和晚到结果均有聚焦测试。
- `MTop`、`CookieRenew`、`QRLogin` 以及少量 Adapter setter 仅作为测试/兼容入口保留。删除条件为已知生产与测试调用清零、契约测试证明新构造路径覆盖全部调用,并完成外部调用方审计;这些兼容入口不作为新增业务依赖。
- 冻结滑块 CAPTCHA 实现及其测试未修改。
统一验证证据:
```text
go test ./internal/application/... ./internal/adapter ./internal/server -count=1
go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
go vet ./...
go run ./tools/architecturecheck
go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json
git diff --check
```
以上命令均通过;race 运行实际覆盖应用层、适配器和 Server 生命周期/凭证并发路径。
## 更新日志
- 2026-08-17:完成阶段 4 整体 Server 应用服务改造,统一完成应用 Port、显式装配、凭证边界、Session 恢复、订单补偿生命周期和并发协调,并通过阶段 4 全部门禁。
## 阶段 5:应用装配与生命周期
状态:待执行;原完成声明撤销,内容仅作为重新验收输入。
当前切片证据(不代表阶段完成):
- 新增 `internal/application/lifecycle.Coordinator`,统一拥有共享 Context、登记顺序、启动失败逆序回滚、关闭逆序、并发 Close 等待、超时和错误聚合;组件回调始终在锁外执行。
- `cmd/server` 统一登记浏览器、Notifier、账号 Manager、Automation Scheduler、Renewal Scheduler 以及订单刷新、批量发布、订单 reconciliation 三类应用 worker;HTTP Server 只负责 HTTP 启停,退出时先停 HTTP,再由协调器逆序关闭应用组件。
- Server 删除业务 worker 的启动/关闭入口和应用 worker 等待逻辑;Server 仅通过只读生命周期 Context 为请求创建的应用 worker 提供父 Context,生命周期 owner 保持在协调器与应用服务。
- 启动失败回滚、重复 Start/Close、并发 Close、启动与关闭竞争、批次/订单 worker 取消、租约 fencing、账号 stopping fence、浏览器关闭超时重试和实时连接 Join 已有聚焦测试;本轮新增 HTTP 与应用 worker 独立关闭预算、错误聚合、未完成组件诊断和 HTTP 启动失败回滚错误保留测试;冻结 CAPTCHA 文件未修改。
- 订单补偿恢复协调器已从 `internal/server` 构造路径迁至 `cmd/server` 组合根,并以 `WithOrderReconciliationRecovery` 显式注入;Server 构造阶段拒绝缺失实例,architecturecheck 禁止该构造函数回流到 Server 生产代码。
- 数据库健康检查端口已从 `Server.New` 迁至 `cmd/server` 组合根,以 `WithDatabaseHealth` 注入;Server 不再保存系统依赖组,缺失端口会在构造期失败,architecturecheck 同步禁止其构造逻辑回流。
- 12 个不依赖 Server callback 的 transport-facing 应用服务已迁至 `internal/adapter` 的 `TransportApplicationServices` 装配集合,由 `cmd/server` 在启动期构造并以 `WithTransportApplicationServices` 注入;Server 不再在请求期或构造期创建这些服务,缺失集合和不完整集合均在 `New` 阶段失败。
- `docs/architecture/lifecycle-inventory.md` 已转为静态 owner/Context/Stop/Wait 清单,并补充通知、SMTP、MTOP、QR 登录、续期、WebSocket 和浏览器外部调用的取消/超时审计;后续 Engine/Automation 内部状态拆分和运维观测风险归入阶段 6 及后续迭代,不得重新引入 Server 生命周期入口。
- `lifecycle.Coordinator.Close` 按组件保留成功关闭进度;超时或组件错误时保持未完成状态、返回组件名称诊断并允许更长 Context 重试,`WaitContext` 在全部组件成功收束前不会伪造完成。并发 `Close` 等待本次尝试的固定结果,重复重试不会覆盖此前调用方的错误语义。
- `Notifier.Start(nil)` 与 `automation.Scheduler.Run(nil)` 明确拒绝启动,避免错误调用创建无法取消的后台 worker;对应行为有确定性测试。
本轮切片验证证据:
```text
go test ./cmd/server ./internal/server ./internal/adapter -count=1
go test ./... -count=1
go test -race ./internal/account ./internal/automation ./internal/engine ./internal/server ./internal/renewal -count=1
go test -race ./internal/application/lifecycle ./internal/notify ./internal/automation -run 'TestCoordinatorClose(ContextBoundsConcurrentClose|RetainsIncompleteComponentsForRetry)|TestNotifierStartRejectsNilContext|TestAutomationSchedulerRunRejectsNilContext' -count=1
go vet ./...
go run ./tools/architecturecheck
$ make comments
go run ./tools/commentlint -mode check -root .
git diff --check
commentlint: 通过(无缺少中文注释或模板化注释)
node frontend/scripts/check-comments.mjs --mode check --root frontend
commentlint: 通过(无缺少中文注释或模板化注释)
$ git diff --check
(无输出,退出码 0)
```
以上命令均通过。transport 应用服务集合的完整构造、缺失依赖、Server 构造失败、独立关闭预算、外部调用边界、未完成组件诊断和可重试 Join 均有测试证据;阶段 5 验收完成。
### 验收边界
此前切片验证证据:
- 覆盖率:本阶段强制命令不包含覆盖率命令,未声明 Go 或前端覆盖率百分比。
- 浏览器:未运行 `RUN_BROWSER_INTEGRATION=1`;阶段二不修改 browser 或冻结 CAPTCHA 调用链。
- 外部服务:阶段二验收不需要 MySQL、PostgreSQL、真实账号或外部平台。
- 冻结 CAPTCHA:受保护的七个实现与测试文件在最终差异中均未出现,冻结规范未修改。
- 生成物:`frontend/coverage/` 是未跟踪的测试产物,不纳入提交。
```text
go test ./cmd/server ./internal/application/lifecycle ./internal/server -count=1
go run ./tools/commentlint -mode check -root .
git diff --check
```
## 下一阶段入口
以上命令均通过。此前证据保留用于生命周期切片追溯,不能替代当前切片和完整阶段验收。
覆盖率证据:`make cover` 运行且 Go statements 为 66.0%;`make cover-frontend` 运行且 Frontend V8 statements 为 79.44%;`make cover-browser` 已以 `RUN_BROWSER_INTEGRATION=1` 运行,本地 Chromium Browser statements 为 63.5%。未使用真实账号或外部平台;覆盖率中的未覆盖 UI 页面和外部平台路径仍按既有分类保留,不以豁免替代业务 Hook、状态转换、取消或生命周期测试。
下一安全入口:阶段 4 的组合根迁移完成并取得最终阶段级证据后,才进入阶段 5 生命周期、Engine 与 Automation 重新验收。
## 更新日志
- 2026-08-17:阶段 5 原整体完成声明因组合根和关闭预算复核不完整而撤回,保留为当前迭代。
- 2026-08-18:完成独立 HTTP/应用关闭预算和错误诊断切片;HTTP 启动失败回滚现在保留应用 worker 错误,阶段 5 继续等待组合根迁移与完整验收。
- 2026-08-18:将订单补偿恢复协调器迁至进程组合根并以显式依赖注入 Server;补充构造失败与架构回流门禁测试。
- 2026-08-18:将数据库健康检查端口迁至进程组合根,删除 Server 对系统依赖组的构造职责,并补充缺失端口与架构回流测试。
- 2026-08-18:将设置、管理员、账号任务、通知、分析、自动化规则/异常、卡券、发布后规则、默认回复和关键词服务迁至显式 transport 应用服务集合,补充组合根构造与缺失依赖测试;阶段 5 仍保持当前迭代。
- 2026-08-18:完成通知、SMTP、MTOP、QR 登录、续期、WebSocket 和浏览器外部调用取消/超时审计;记录浏览器同步 Playwright 停止的不可中断约束、通知/自动化 nil Context 防御缺口和最终 Join 验收入口,阶段 5 仍保持当前迭代。
- 2026-08-18:完成最终 Join 收口;协调器关闭超时后保留未完成组件并支持更长 Context 重试,并发关闭返回本轮固定错误;通知与自动化 nil Context 拒绝启动。该记录仅作为重新验收输入。
- 2026-08-18:按阶段级交付规则重置状态:阶段 4 设为当前迭代,阶段 5–10 设为待执行;历史局部证据不再代替最终阶段提交和完整命令输出。
### 阶段 5 的 Engine 与 Automation 历史输入
状态:待执行;原完成声明撤销,内容仅作为重新验收输入。
完成证据:
- `automationActionExecutor.sendDataCard` 的卡券锁仅覆盖库存预留与确定未发送时的恢复,外部 WebSocket 发送已移到锁外,并有并发阻塞测试证明第二个库存操作不会等待第一个外部发送。
- `confirmShipmentAttempt` 在凭证锁内只读取最小运行时快照,MTOP 调用在锁外执行;响应写回重新获取凭证锁并进行指纹条件校验,冲突时跳过旧响应并记录人工核对所需错误。
- 新增凭证锁锁外外部 I/O、并发新凭证不被旧响应覆盖的确定性测试;冻结 CAPTCHA 实现及测试未修改。
- `automation.NewWithDependencies` 固定 MTOP、账号任务、订单详情、通知和 Cookie 读取依赖;所有 `Center` setter、运行时依赖覆盖和其锁已删除,延迟恢复通过同一构造依赖重建 Center。
- `engine.Account` 已将连接、出站消息、凭证、消息分发、运行状态、生命周期和迟到续期收束到独立组件;凭证实现已物理迁入 `credentialCoordinator`,facade 仅保留稳定入口和必要兼容委托。
- `refreshGate` 支持 Context 取消;凭证锁只覆盖快照和条件提交,MTOP、WebSocket、浏览器、通知及 Handler 回调均在锁外执行。`pendingRenewalCoordinator` 与连接协调器以共享完成信号和有限预算 Join,不创建超时后无法回收的等待 goroutine。
- 自动化外部动作在运行检查点后执行,保留成功、失败和 `needs_review` 三态。结果通知以 `runID + status` 作为持久化 outbox 幂等键,重复恢复不会重复入队;外部投递成功但本地确认失败的 `uncertain` 记录不会自动重放。SQLite、MySQL、PostgreSQL 的 `00034` 通知幂等迁移已对齐。
- 冻结 CAPTCHA 受保护文件未改动;浏览器集成和全部冻结行为测试通过。
下一安全入口:阶段 5 完整重新验收后,再进入阶段 6 React Feature 化和异步状态修复。
当前统一验证证据:
```text
make check # 通过
go test ./internal/engine ./internal/automation ./internal/browser -count=1 # 通过
go test -race ./internal/engine ./internal/automation -count=1 # 通过
RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1 # 通过
go run ./tools/architecturecheck # 通过
make comments # 通过
git diff --check # 通过
make cover # Go statements 66.5%
make cover-browser # Browser statements 60.9%(RUN_BROWSER_INTEGRATION=1)
make cover-frontend # Frontend statements 93.01%
```
覆盖率例外:未跳过本地确定性 Engine、Automation 或浏览器行为;仅保留项目既有的真实账号/外部平台不可用场景分类。
更新日志:
- 2026-08-17:完成阶段 6 整体 Engine 与 Automation 改造,统一收束 facade、凭证和 worker 生命周期、锁外外部 I/O、运行检查点及通知幂等/不确定态,并通过阶段 6 全部门禁。
## 阶段 6:React Feature 化与异步状态
状态:待执行;原完成声明撤销,内容仅作为重新验收输入。
完成证据:
- 根 `App` 仅装配错误边界、会话 Provider 和路由;认证表单归属 session feature,认证后导航、权限回退、侧边栏偏好和一次性跨页面载荷由 app 路由壳管理。
- 九个业务页面与其直属组件、Hook、状态、API adapter 和测试均归入各自 feature;账号自动任务归入 accounts,删除跨 feature 的 accountAutomation 目录。
- 已删除集中式 `frontend/services/api.ts`、`frontend/types.ts`、`frontend/request.ts` 和 `frontend/services/contract.ts`;feature API adapter 直接依赖 `shared/http`,只读传输契约位于 `shared/api-contract`,DTO 归一保留在所属 feature 边界。
- `shared` 只保留 HTTP transport、兼容 JSON contract、通用异步 gate、浏览器偏好和纯展示 UI;架构测试禁止 feature 相互导入、shared 反向依赖 feature、组件直连网络和根 components 回流。
- 所有业务页面由 `React.lazy` 按路由加载;构建验证九个独立页面分片、首屏不预加载 charts 分片且每页原始大小满足既有预算。仪表盘乱序、卡密/订单卸载取消、聊天切换与旧分页响应均有确定性行为测试。
- 冻结 CAPTCHA 实现、测试及调用语义均未修改。
当前统一验证证据:
```text
npm test --prefix frontend # 63 files, 383 tests 通过
npm run typecheck --prefix frontend # 通过
npm run comments:check --prefix frontend # 通过
npm run build --prefix frontend # 通过,已更新 internal/webui/static
make cover-frontend # Frontend statements 79.84%,RUN_BROWSER_INTEGRATION 未使用
git diff --check # 通过
go run ./tools/architecturecheck # 通过
make comments # 通过
make check # 通过
```
覆盖率例外:纯 React 页面、展示组件与错误边界在本阶段的 V8 报告中存在未覆盖行;所有新改动的业务 API、Hook、状态、取消、切换和乱序行为均由确定性 Vitest 覆盖。无真实账号或外部平台调用。
下一安全入口:阶段 6 完成后进入阶段 7 DB 与事务治理;阶段 7 完成后依次进入阶段 8 架构门禁与兼容退场、阶段 9 注释与复杂度收口和阶段 10 最终全栈复验。
更新日志:
- 2026-08-17:完成阶段 7 React Feature 化整体改造,统一落地 app -> features -> shared、feature API adapter、路由懒加载、异步请求生命周期与前端架构门禁,并通过阶段全部验证。
当前阶段为阶段三:生命周期、Engine 和 Automation 重新验收。先以 `lifecycle-inventory.md` 对照每个后台
worker 的 owner、Context、Cancel、Wait/Join 和锁顺序;阶段三门禁已经随状态切换启用。不得提前进入 React、
数据库或最终收口阶段,也不得修改冻结 CAPTCHA。
+7 -7
View File
@@ -1,7 +1,7 @@
# 登录续期与风控能力实施记录
> 本文最初是实施计划。当前列出的五个阶段均已落地;后续协议变化应以实际代码、测试和
> 本文的实施记录为准,不应把“目标流程”误读为尚未实现的功能。
> 本文最初是实施计划。当前列出的五个功能记录均已落地;后续协议变化应以实际代码、测试和
> 本文的实施记录为准,不应把“目标流程”误读为尚未实现的功能。它不是重构总计划,不定义正式阶段。
## 目标
@@ -14,7 +14,7 @@
- 不在第一版引入跨服务架构;续期和验证能力仍在当前 Go 进程内闭环。
- 不默认把已禁用账号自动启用,避免用户明确停用的账号被后台恢复上线。
## 阶段 1:扫码人脸验证 API 链路
## 功能记录 1:扫码人脸验证 API 链路
修改 `internal/xianyu/qrlogin`:
@@ -38,7 +38,7 @@
- 提取 `htoken`、`verify_modes`、人脸二维码内容的纯函数测试。
- `photoVerify/check.do` 成功后 session 转为 `success` 的 HTTP mock 测试。
## 阶段 2:Cookie 接口续期服务
## 功能记录 2:Cookie 接口续期服务
新增 `internal/xianyu/renew`:
@@ -54,7 +54,7 @@
- 接口续期成功、失败、部分 Cookie 更新。
- `setLoginSettings.do` 未返回 Cookie 时不误判成功。
## 阶段 3:登录态检查与 MTOP 风控分类
## 功能记录 3:登录态检查与 MTOP 风控分类
新增或扩展 `internal/xianyu/mtop`:
@@ -69,7 +69,7 @@
- 风控 URL 提取。
- 登录态接口返回 Cookie 时正确合并。
## 阶段 4:运行时恢复顺序接入
## 功能记录 4:运行时恢复顺序接入
修改 `internal/engine/account.go`:
@@ -90,7 +90,7 @@
- 密码登录作为最后自动恢复手段。
- 风控类错误进入 `verification_required`,降频重试并发通知。
## 阶段 5:重连退避和多账号保护
## 功能记录 5:重连退避和多账号保护
- 网络错误和认证错误使用不同退避。
- 增加 0-30% 随机抖动,降低多账号同时重连冲击。
+36 -3
View File
@@ -20,11 +20,13 @@ type chatOutgoingRepository struct {
// NewChatSendingApplication 装配聊天历史、实时发送、图片上传和身份补全端口。
func NewChatSendingApplication(domainService *domainchat.Service, store *db.Store, manager *account.Manager, clientProvider func() mtop.Client) *chatapp.Service {
// readReporter 保存从账号运行时适配出的平台已读上报能力,未运行账号保持可选语义。
readReporter := NewChatReadReporter(manager)
if domainService == nil {
// service 保留历史查询应用对象,但不伪造未装配的发送、订阅和刷新端口。
return chatapp.NewWithSendingSubscriptionAndRefresh(NewChatRepository(store), nil, nil, nil, nil, nil, NewChatIdentityResolver(store, clientProvider))
return chatapp.WithPlatformReadReporter(chatapp.NewWithSendingSubscriptionAndRefresh(NewChatRepository(store), nil, nil, nil, nil, nil, NewChatIdentityResolver(store, clientProvider)), readReporter)
}
return chatapp.NewWithSendingSubscriptionAndRefresh(
return chatapp.WithPlatformReadReporter(chatapp.NewWithSendingSubscriptionAndRefresh(
NewChatRepository(store),
NewChatOutgoingRepository(domainService),
NewChatSenderProvider(manager),
@@ -32,7 +34,38 @@ func NewChatSendingApplication(domainService *domainchat.Service, store *db.Stor
NewChatSubscriptionProvider(domainService),
NewChatRefreshProvider(domainService, manager),
NewChatIdentityResolver(store, clientProvider),
)
), readReporter)
}
// chatReadReporter 将账号运行时的可选已读上报能力适配为聊天应用端口。
type chatReadReporter struct {
// manager 保存当前进程的账号运行时查询入口。
manager *account.Manager
}
// NewChatReadReporter 创建聊天已读上报端口;nil Manager 表示当前进程不提供运行时上报能力。
func NewChatReadReporter(manager *account.Manager) chatapp.PlatformReadReporter {
return chatReadReporter{manager: manager}
}
// ReportRead 向在线账号实例尽力上报平台已读状态;不支持该能力时保持无副作用。
func (reporter chatReadReporter) ReportRead(ctx context.Context, accountID, chatID string, messageIDs []map[string]any) error {
if reporter.manager == nil {
return nil
}
// sender、ok 保存账号运行实例与其在线状态。
sender, ok := reporter.manager.GetInstance(accountID)
if !ok || sender == nil {
return nil
}
// reader、ok 保存运行时是否支持平台已读上报。
reader, ok := sender.(interface {
MarkChatRead(context.Context, string, []map[string]any) error
})
if !ok {
return nil
}
return reader.MarkChatRead(ctx, chatID, messageIDs)
}
// NewChatOutgoingRepository 创建聊天外发消息的领域适配器。
@@ -0,0 +1,37 @@
package adapter
import (
"context"
"errors"
itemapp "xianyu-go/internal/application/items"
)
// BatchManagementRuntime 将由组合根拥有的 worker 协调器适配为批次管理应用 Port。
type BatchManagementRuntime struct {
// lifecycleContext 返回进程协调器拥有的 worker 父 Context,批次管理不保存 HTTP Server。
lifecycleContext func() context.Context
// coordinator 持有批量 worker 的启动、取消、恢复和等待语义。
coordinator *itemapp.BatchWorkerCoordinator
}
// NewBatchManagementRuntime 构造批次管理运行时 Port;依赖缺失在应用服务创建时转换为可诊断错误。
func NewBatchManagementRuntime(lifecycleContext func() context.Context, coordinator *itemapp.BatchWorkerCoordinator) itemapp.BatchManagementRuntime {
return BatchManagementRuntime{lifecycleContext: lifecycleContext, coordinator: coordinator}
}
// StartBatch 在组合根提供的生命周期 Context 下启动已获租约的批量 worker。
func (runtime BatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) error {
if runtime.lifecycleContext == nil || runtime.coordinator == nil {
return errors.New("批量 worker 协调器未装配")
}
return runtime.coordinator.Start(runtime.lifecycleContext(), userID, batchID, workerToken)
}
// CancelBatch 取消指定租约对应的 worker;协调器缺失时保持幂等无副作用。
func (runtime BatchManagementRuntime) CancelBatch(batchID, workerToken string) {
if runtime.coordinator == nil {
return
}
_ = runtime.coordinator.Cancel(batchID, workerToken)
}
+63
View File
@@ -0,0 +1,63 @@
package adapter
import (
"context"
"errors"
"time"
itemapp "xianyu-go/internal/application/items"
)
// itemBatchPublisher 将平台远端发布和本地成功收口组合为应用层 BatchPublisher,不依赖 HTTP Server。
type itemBatchPublisher struct {
// remotePort 负责平台发布与会话变化收集,不读取 HTTP 请求或响应对象。
remotePort itemapp.BatchPublishPort
// localService 负责远端成功后的本地商品、规则与检查点事务收口。
localService itemapp.BatchLocalPublisher
}
// NewItemBatchPublisher 构造批量发布的应用端口适配器,并拒绝缺失的远端或本地依赖。
func NewItemBatchPublisher(remotePort itemapp.BatchPublishPort, localService itemapp.BatchLocalPublisher) (itemapp.BatchPublisher, error) {
if remotePort == nil || localService == nil {
return nil, errors.New("批量发布 publisher 依赖不完整")
}
return itemBatchPublisher{remotePort: remotePort, localService: localService}, nil
}
// PublishRow 执行单行远端发布并同步本地完成状态;远端结果不确定时保留人工核对语义。
func (publisher itemBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string, beforePublish func(context.Context) error) error {
// outcome、publishErr 分别保存远端发布结果及其错误,远端调用失败时不得写入本地成功状态。
outcome, publishErr := publisher.remotePort.PublishRemoteRow(ctx, userID, row, workerToken, beforePublish)
if publishErr != nil {
// uncertainErr 表示远端请求已经发出但无法确认最终商品状态,调用方必须禁止自动重试。
var uncertainErr *itemapp.UncertainRemotePublishError
if errors.As(publishErr, &uncertainErr) {
return publishErr
}
return publishErr
}
if outcome.Result == nil {
return errors.New("发布商品接口未返回结果")
}
if outcome.ResponseCookieErr != nil {
return &itemapp.PostPublishError{Err: outcome.ResponseCookieErr}
}
if ctx.Err() != nil {
return &itemapp.PostPublishError{Err: ctx.Err()}
}
return publisher.localService.Complete(ctx, userID, row, workerToken, outcome.Result)
}
// NewItemBatchRunnerApplication 构造批量发布 worker;调用方必须在组合期提供窄仓储、发布端口和失败分类规则。
func NewItemBatchRunnerApplication(repository itemapp.BatchRepository, publisher itemapp.BatchPublisher, leaseDuration time.Duration, classifyFailure func(error, string) (string, string)) (*itemapp.BatchRunner, error) {
if repository == nil || publisher == nil || leaseDuration <= 0 || classifyFailure == nil {
return nil, errors.New("批量发布运行器依赖不完整")
}
// options 保存 worker 的租约、平台会话判断与失败状态归类,运行期不再回读 Server。
options := itemapp.BatchRunOptions{
LeaseDuration: leaseDuration,
IsSessionExpired: IsSessionExpiredError,
ClassifyFailure: classifyFailure,
}
return itemapp.NewBatchRunner(repository, publisher, options)
}
@@ -0,0 +1,43 @@
package adapter
import (
"testing"
"time"
)
// TestNewItemBatchRunnerApplicationRejectsIncompleteDependencies 验证组合期拒绝缺失的批量 worker 依赖,避免请求期才发现半初始化实例。
func TestNewItemBatchRunnerApplicationRejectsIncompleteDependencies(t *testing.T) {
// runner、buildErr 分别保存构造结果及缺失依赖产生的错误。
runner, buildErr := NewItemBatchRunnerApplication(nil, nil, time.Minute, nil)
if buildErr == nil {
t.Fatal("缺失依赖时应返回构造错误")
}
if runner != nil {
t.Fatal("构造失败时不得返回可运行 worker")
}
}
// TestNewItemBatchPublisherRejectsIncompleteDependencies 验证 publisher 在组合期拒绝缺失端口,避免 worker 启动后才暴露配置错误。
func TestNewItemBatchPublisherRejectsIncompleteDependencies(t *testing.T) {
// publisher、buildErr 分别保存构造结果及缺失发布端口产生的错误。
publisher, buildErr := NewItemBatchPublisher(nil, nil)
if buildErr == nil {
t.Fatal("缺失发布端口时应返回构造错误")
}
if publisher != nil {
t.Fatal("构造失败时不得返回可执行 publisher")
}
}
// TestBatchManagementRuntimeRejectsMissingCoordinator 验证缺失 worker 协调器时不会启动半初始化后台任务。
func TestBatchManagementRuntimeRejectsMissingCoordinator(t *testing.T) {
// runtime 是缺失协调器的批次管理 Port,用于覆盖启动期失败分支。
runtime := NewBatchManagementRuntime(nil, nil)
// startErr 保存启动半初始化 worker 时的组合错误。
startErr := runtime.StartBatch(1, "batch-1", "worker-1")
if startErr == nil {
t.Fatal("缺失协调器时应拒绝启动批次 worker")
}
// CancelBatch 在缺失协调器时必须保持幂等且不 panic。
runtime.CancelBatch("batch-1", "worker-1")
}
+1 -1
View File
@@ -100,7 +100,7 @@ func (r OrderRepository) GetOrder(ctx context.Context, orderID string) (*orderap
// order 和 err 保存数据库订单查询结果及其错误。
order, err := r.store.Orders.Get(ctx, orderID)
if err != nil {
return nil, err
return nil, NormalizeOrderError(err)
}
return orderFromDB(order), nil
}
+165
View File
@@ -0,0 +1,165 @@
package adapter
import (
"context"
"errors"
"log/slog"
"xianyu-go/internal/account"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/automation"
"xianyu-go/internal/notify"
)
// OrderRuntimeAdapter 将账号、自动化、通知和平台调用组合为订单应用 Port,不依赖 HTTP Server。
type OrderRuntimeAdapter struct {
// runtime 保存已完成基础设施装配的订单运行时;nil 仅用于隔离测试的缺失依赖分支。
runtime *OrderRuntime
}
// OrderRuntimeFactory 定义订单运行时装配所需的最小基础设施工厂,由组合根提供具体实现。
type OrderRuntimeFactory interface {
// NewOrderRuntime 使用已装配 hooks 与补偿记录端口创建订单运行时。
NewOrderRuntime(OrderRuntimeHooks, orderapp.ReconciliationRecorder, *slog.Logger) *OrderRuntime
}
// NewOrderRuntimeAdapter 构造订单应用运行时 Port;所有外部能力仅通过组合期回调和窄接口进入。
func NewOrderRuntimeAdapter(dependencies OrderRuntimeFactory, manager *account.Manager, autoCenter *automation.Center, notifier *notify.Notifier, mtopClient func() MTOPClient, updateRunningCookie func(context.Context, string, string), sessionRecovery SessionRecoveryHandler, logger *slog.Logger, reconciliation orderapp.ReconciliationRecorder) OrderRuntimeAdapter {
// automationPort 保持 nil 接口语义,避免 nil 指针伪装成已装配自动化能力。
var automationPort OrderAutomation
if autoCenter != nil {
automationPort = autoCenter
}
// notifierPort 保持 nil 接口语义,避免 nil 指针伪装成已装配通知能力。
var notifierPort OrderNotifier
if notifier != nil {
notifierPort = notifier
}
// hooks 收口账号、自动化、通知、平台和凭证恢复能力,订单应用不接触 HTTP transport。
hooks := NewOrderRuntimeHooks(mtopClient, manager, automationPort, notifierPort, updateRunningCookie, sessionRecovery)
// runtime 保存由 adapter 创建的订单运行时;无数据库依赖时仅支持确定性错误分支。
var runtime *OrderRuntime
if dependencies == nil {
runtime = NewOrderRuntime(nil, hooks, reconciliation, logger)
} else {
runtime = dependencies.NewOrderRuntime(hooks, reconciliation, logger)
}
return OrderRuntimeAdapter{runtime: runtime}
}
// AccountRunning 判断指定账号是否在线运行。
func (adapter OrderRuntimeAdapter) AccountRunning(cookieID string) bool {
return adapter.runtime != nil && adapter.runtime.AccountRunning(cookieID)
}
// AutomationReady 判断完整发货自动化依赖是否已装配。
func (adapter OrderRuntimeAdapter) AutomationReady() bool {
return adapter.runtime != nil && adapter.runtime.AutomationReady()
}
// ManualFullDelivery 执行完整自动化发货。
func (adapter OrderRuntimeAdapter) ManualFullDelivery(ctx context.Context, order *orderapp.Order) (int, error) {
if adapter.runtime == nil {
return 0, errors.New("订单运行时未初始化")
}
return adapter.runtime.ManualFullDelivery(ctx, order)
}
// MTopAvailable 判断平台客户端是否已注入。
func (adapter OrderRuntimeAdapter) MTopAvailable() bool {
return adapter.runtime != nil && adapter.runtime.MTopAvailable()
}
// ConfirmShipment 执行平台确认发货并返回应用层结果。
func (adapter OrderRuntimeAdapter) ConfirmShipment(ctx context.Context, cookieID, orderID string, userID int64) orderapp.ConsignResult {
if adapter.runtime == nil {
return orderapp.ConsignResult{Err: errors.New("订单运行时未初始化")}
}
return adapter.runtime.ConfirmShipment(ctx, cookieID, orderID, userID)
}
// UpdateRunningCookie 同步运行时账号 Cookie。
func (adapter OrderRuntimeAdapter) UpdateRunningCookie(ctx context.Context, cookieID, value string) {
if adapter.runtime != nil {
adapter.runtime.UpdateRunningCookie(ctx, cookieID, value)
}
}
// NotifyDelivery 发送发货结果通知。
func (adapter OrderRuntimeAdapter) NotifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
if adapter.runtime != nil {
adapter.runtime.NotifyDelivery(cookieID, buyerID, itemID, chatID, message)
}
}
// RecordOrderReconciliation 写入外部动作成功后的本地异常补偿记录。
func (adapter OrderRuntimeAdapter) RecordOrderReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
if adapter.runtime == nil {
return "", errors.New("订单运行时未初始化")
}
return adapter.runtime.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message)
}
// RecordReconciliation 满足手动发货应用 Port 的补偿记录接口。
func (adapter OrderRuntimeAdapter) RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
return adapter.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message)
}
// ReportPersistenceFailure 记录手动发货本地状态持久化失败。
func (adapter OrderRuntimeAdapter) ReportPersistenceFailure(orderID string, err error) {
if adapter.runtime != nil {
adapter.runtime.ReportPersistenceFailure(orderID, err)
}
}
// RecoverExpiredSession 将订单刷新发现的会话失效交给组合期恢复回调。
func (adapter OrderRuntimeAdapter) RecoverExpiredSession(ctx context.Context, cookieID string, err error) bool {
return adapter.runtime != nil && adapter.runtime.RecoverExpiredSession(ctx, cookieID, err)
}
// DetailAvailable 判断订单详情接口是否可用。
func (adapter OrderRuntimeAdapter) DetailAvailable() bool {
return adapter.runtime != nil && adapter.runtime.DetailAvailable()
}
// SoldAvailable 判断已售订单列表接口是否可用。
func (adapter OrderRuntimeAdapter) SoldAvailable() bool {
return adapter.runtime != nil && adapter.runtime.SoldAvailable()
}
// CredentialAvailable 判断平台请求视图是否包含可用 Cookie。
func (adapter OrderRuntimeAdapter) CredentialAvailable(detail *orderapp.PlatformRuntimeData) bool {
return adapter.runtime != nil && adapter.runtime.CredentialAvailable(detail)
}
// FetchOrderDetail 调用平台详情接口并收集 Cookie 会话变化。
func (adapter OrderRuntimeAdapter) FetchOrderDetail(ctx context.Context, detail *orderapp.PlatformRuntimeData, orderID string) (orderapp.RefreshDetailFetchResult, error) {
if adapter.runtime == nil {
return orderapp.RefreshDetailFetchResult{}, errors.New("订单运行时未初始化")
}
return adapter.runtime.FetchOrderDetail(ctx, detail, orderID)
}
// FetchSoldOrders 调用平台已售订单接口并收集 Cookie 会话变化。
func (adapter OrderRuntimeAdapter) FetchSoldOrders(ctx context.Context, detail *orderapp.PlatformRuntimeData) (orderapp.RefreshSoldFetchResult, error) {
if adapter.runtime == nil {
return orderapp.RefreshSoldFetchResult{}, errors.New("订单运行时未初始化")
}
return adapter.runtime.FetchSoldOrders(ctx, detail)
}
// PersistCookieSession 在凭证锁内保存应用层 Cookie 更新。
func (adapter OrderRuntimeAdapter) PersistCookieSession(ctx context.Context, detail *orderapp.PlatformRuntimeData, update orderapp.RefreshCookieUpdate) (string, bool, bool, error) {
if adapter.runtime == nil {
if detail == nil {
return update.Value, false, update.Handled, errors.New("订单运行时未初始化")
}
return update.Value, update.Value != detail.Value, update.Handled, errors.New("订单运行时未初始化")
}
return adapter.runtime.PersistCookieSession(ctx, detail, update)
}
// IsSessionExpired 判断平台错误是否为会话过期。
func (adapter OrderRuntimeAdapter) IsSessionExpired(err error) bool {
return adapter.runtime != nil && adapter.runtime.IsSessionExpired(err)
}
+25
View File
@@ -140,6 +140,13 @@ type RefreshProvider interface {
RefreshHistory(context.Context, string, string, int64, int, Session) (HistoryPage, error)
}
// PlatformReadReporter 定义将本地已读动作尽力同步到平台运行时的最小能力。
// 该端口不读取凭证,未装配时调用保持无副作用。
type PlatformReadReporter interface {
// ReportRead 上报指定会话的已读消息标识;调用方可将失败记录为诊断但不得回滚本地状态。
ReportRead(context.Context, string, string, []map[string]any) error
}
// Page 是聊天历史查询的分页结果。
type Page struct {
// Messages 是按时间正序排列的当前页消息。
@@ -194,6 +201,8 @@ type Service struct {
subscription SubscriptionProvider
// refresh 保存平台聊天刷新端口;原始响应只在适配器内部解析和持久化。
refresh RefreshProvider
// readReporter 保存可选的平台已读上报端口,本地已读持久化不依赖该外部动作。
readReporter PlatformReadReporter
}
// New 创建聊天历史应用服务;空端口会导致构造结果不可用。
@@ -425,6 +434,22 @@ func (s *Service) MarkRead(ctx context.Context, userID int64, accountID, chatID
return repository.MarkRead(ctx, userID, accountID, chatID)
}
// WithPlatformReadReporter 为已构造的聊天应用服务注入可选的平台已读上报端口。
func WithPlatformReadReporter(service *Service, reporter PlatformReadReporter) *Service {
if service != nil {
service.readReporter = reporter
}
return service
}
// ReportPlatformRead 尽力上报平台已读状态;未装配运行时或空消息集合时保持无副作用。
func (s *Service) ReportPlatformRead(ctx context.Context, accountID, chatID string, messageIDs []map[string]any) error {
if s == nil || s.readReporter == nil || len(messageIDs) == 0 {
return nil
}
return s.readReporter.ReportRead(ctx, strings.TrimSpace(accountID), strings.TrimSpace(chatID), messageIDs)
}
// ResolveSessionIdentity 补全单个会话展示身份并尽力保存到本地。
// 平台查询错误会原样返回,但已获得的会话摘要仍会返回给调用方。
func (s *Service) ResolveSessionIdentity(ctx context.Context, session Session) (Session, error) {
+49
View File
@@ -156,6 +156,27 @@ type fakeRepository struct {
markReadCalls int
}
// fakePlatformReadReporter 记录平台已读上报调用并返回预设失败。
type fakePlatformReadReporter struct {
// err 是平台已读上报需要返回的稳定错误。
err error
// calls 记录实际转发次数,确保空消息不会触发外部动作。
calls int
// accountID、chatID 和 messageIDs 保存最近一次上报输入,用于断言透传语义。
accountID string
chatID string
messageIDs []map[string]any
}
// ReportRead 记录已读上报请求并返回预设错误。
func (reporter *fakePlatformReadReporter) ReportRead(_ context.Context, accountID, chatID string, messageIDs []map[string]any) error {
reporter.calls++
reporter.accountID = accountID
reporter.chatID = chatID
reporter.messageIDs = messageIDs
return reporter.err
}
// ListMessages 返回测试消息,并记录用户归属参数。
func (r *fakeRepository) ListMessages(_ context.Context, userID int64, _ string, _ string, _ int64, _ int) ([]Message, error) {
r.userID = userID
@@ -402,3 +423,31 @@ func TestMarkReadValidatesAndPropagatesPortErrors(t *testing.T) {
t.Fatalf("unavailable MarkRead() error=%v", unavailableErr)
}
}
// TestReportPlatformReadIsOptionalAndPreservesReporterError 验证平台已读上报不影响本地写入且透传运行时失败。
func TestReportPlatformReadIsOptionalAndPreservesReporterError(t *testing.T) {
// messageIDs 是需要上报的平台消息标识,内容保持测试数据且不含凭证。
messageIDs := []map[string]any{{"messageId": "message-1"}}
// idleService 是没有运行时上报端口的聊天应用服务,调用必须无副作用成功。
idleService := New(&fakeRepository{})
// idleErr 表示未装配平台上报端口时的调用结果,必须保持 nil。
if idleErr := idleService.ReportPlatformRead(context.Background(), "account-1", "chat-1", messageIDs); idleErr != nil {
t.Fatalf("未装配上报端口时不应失败: %v", idleErr)
}
// wantErr 是平台运行时返回的失败,本地已读持久化调用方只会记录该诊断。
wantErr := errors.New("platform read failed")
// reporter 是记录参数并返回预设失败的平台已读端口替身。
reporter := &fakePlatformReadReporter{err: wantErr}
// service 是注入上报端口后的聊天应用服务。
service := WithPlatformReadReporter(New(&fakeRepository{}), reporter)
// reportErr 保存应用服务原样返回的平台上报失败。
reportErr := service.ReportPlatformRead(context.Background(), " account-1 ", " chat-1 ", messageIDs)
if !errors.Is(reportErr, wantErr) || reporter.calls != 1 || reporter.accountID != "account-1" || reporter.chatID != "chat-1" || len(reporter.messageIDs) != 1 {
t.Fatalf("ReportPlatformRead() error=%v calls=%d account=%q chat=%q messages=%d", reportErr, reporter.calls, reporter.accountID, reporter.chatID, len(reporter.messageIDs))
}
// emptyErr 保存空消息集合的调用结果,不能再触发运行时端口。
emptyErr := service.ReportPlatformRead(context.Background(), "account-1", "chat-1", nil)
if emptyErr != nil || reporter.calls != 1 {
t.Fatalf("空消息不应触发上报: error=%v calls=%d", emptyErr, reporter.calls)
}
}
@@ -46,6 +46,12 @@ type BatchPublishedItemRepository interface {
UpsertPublishedItem(context.Context, BatchPublishedItem) error
}
// BatchLocalPublisher 定义远端商品发布成功后的本地收口能力。
// adapter 只依赖该 Port,不应持有具体应用服务实现。
type BatchLocalPublisher interface {
Complete(context.Context, int64, BatchRow, string, *BatchPublishResult) error
}
// BatchLocalPublishService 编排远端成功后的本地商品、自动化规则和批次成功收口。
type BatchLocalPublishService struct {
// completionRepository 负责复核批次租约并保存明细成功检查点。
@@ -0,0 +1,137 @@
package composition
import (
"context"
"errors"
"strings"
"time"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
)
// accountLoginService 组合手动 Cookie 与二维码登录的应用用例;它只在组合层持有适配器细节。
type accountLoginService struct {
// cookieWriterFactory 为单次请求创建明文 Cookie 写入端口,明文不会进入 HTTP Server 状态。
cookieWriterFactory func(string) accountapp.CookieWriter
// cookieUpdaterFactory 为单次更新请求创建明文 Cookie 写入端口。
cookieUpdaterFactory func(string) accountapp.CookieUpdater
// sessionPort 保存平台响应 Cookie 会话所需的窄凭证能力。
sessionPort accountapp.CredentialSessionPort
// createApplication 执行手动 Cookie 登录用例。
createApplication *accountapp.LoginService
// qrApplication 执行扫码成功后的凭证持久化用例。
qrApplication *accountapp.QRLoginService
// qrSessions 管理二维码会话的所有权、过期与幂等写入。
qrSessions *accountapp.QRLoginSessionRegistry
}
// CookieLoginResult 是扫码登录持久化后允许返回给 transport 的非敏感结果。
type CookieLoginResult struct {
// AccountID 是已经创建或更新的账号标识。
AccountID string
// IsNew 指示本次是否创建账号。
IsNew bool
// UserID 是二维码会话绑定的用户标识。
UserID int64
// CreatedAt 是本次幂等结果创建时间。
CreatedAt time.Time
}
// CreateCookie 创建账号凭证并触发登录后的应用编排。
func (service *accountLoginService) CreateCookie(ctx context.Context, accountID, cookies string, userID int64, loginMethod string) error {
if service == nil || service.createApplication == nil || service.cookieWriterFactory == nil {
return errors.New("账号 Cookie 登录服务未初始化")
}
return service.createApplication.CreateCookie(ctx, accountapp.CreateCookieInput{AccountID: accountID, UserID: userID, LoginMethod: loginMethod}, service.cookieWriterFactory(cookies))
}
// UpdateCookie 更新账号凭证并触发登录后的应用编排。
func (service *accountLoginService) UpdateCookie(ctx context.Context, accountID, cookies string, userID int64, loginMethod string, expectedRevision int64) error {
if service == nil || service.createApplication == nil || service.cookieUpdaterFactory == nil {
return errors.New("账号 Cookie 更新服务未初始化")
}
return service.createApplication.UpdateCookie(ctx, accountapp.UpdateCookieInput{AccountID: accountID, UserID: userID, LoginMethod: loginMethod, ExpectedRevision: expectedRevision}, service.cookieUpdaterFactory(cookies))
}
// PersistQRLoginSuccess 将平台结果转换为应用命令,并在会话注册表下执行一次性持久化。
func (service *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (CookieLoginResult, error) {
if service == nil || service.qrApplication == nil || service.qrSessions == nil {
return CookieLoginResult{}, errors.New("扫码登录应用服务未初始化")
}
// persisted、persistErr 分别是会话幂等结果及其持久化错误。
persisted, persistErr := service.qrSessions.PersistOnce(sessionID, userID, func() (accountapp.QRLoginSessionPersistence, error) {
// cookies 保存平台返回的明文凭证,仅在当前用例调用期间传递,不进入 Server 状态。
cookies := resultString(result, "cookies")
// cookieSnapshot、snapshotComplete 分别是结构化 Cookie 快照及其是否完整的标记。
cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result)
// scannedAccountID 是平台扫描出的账号标识,缺失时从 Cookie 非敏感字段推断。
scannedAccountID := strings.TrimSpace(firstNonEmpty(resultString(result, "unb"), adapter.AccountIDFromCookie(cookies)))
// input 是扫码登录应用服务使用的凭证持久化命令。
input := accountapp.QRLoginInput{UserID: userID, ScannedAccountID: scannedAccountID, TargetAccountID: targetAccountID, Cookies: cookies}
if snapshotComplete {
input.Snapshot = cookieSnapshot
}
// resultValue、writeErr 分别是扫码成功持久化结果及其错误。
resultValue, writeErr := service.qrApplication.PersistSuccess(ctx, input)
if writeErr != nil {
return accountapp.QRLoginSessionPersistence{}, writeErr
}
return accountapp.QRLoginSessionPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, CreatedAt: time.Now().UTC()}, nil
})
if persistErr != nil {
return CookieLoginResult{}, persistErr
}
return CookieLoginResult{AccountID: persisted.AccountID, IsNew: persisted.IsNew, UserID: persisted.UserID, CreatedAt: persisted.CreatedAt}, nil
}
// RegisterQRSession 记录二维码会话的用户所有权。
func (service *accountLoginService) RegisterQRSession(sessionID string, userID int64, createdAt time.Time) {
if service != nil && service.qrSessions != nil {
service.qrSessions.Register(sessionID, userID, createdAt)
}
}
// AuthorizeQRSession 验证二维码会话属于当前用户。
func (service *accountLoginService) AuthorizeQRSession(sessionID string, userID int64) error {
if service == nil || service.qrSessions == nil {
return errors.New("扫码登录应用服务未初始化")
}
return service.qrSessions.Authorize(sessionID, userID)
}
// CleanupQRSessions 清理过期二维码会话并返回需要删除的平台会话标识。
func (service *accountLoginService) CleanupQRSessions(now time.Time) []string {
if service == nil || service.qrSessions == nil {
return nil
}
return service.qrSessions.Cleanup(now)
}
// CredentialSessionPort 返回平台 Cookie 会话写入所需的最小凭证端口。
func (service *accountLoginService) CredentialSessionPort() accountapp.CredentialSessionPort {
if service == nil {
return nil
}
return service.sessionPort
}
// resultString 读取平台结果中的字符串字段;非字符串或不存在时返回空值。
func resultString(result map[string]any, key string) string {
// value、ok 分别是平台字段的字符串值及其类型判断结果。
if value, ok := result[key].(string); ok {
return value
}
return ""
}
// firstNonEmpty 返回第一个非空字符串,用于优先使用平台明确字段。
func firstNonEmpty(values ...string) string {
// value 是当前待判断的候选字符串;首个非空值具有优先级。
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
@@ -0,0 +1,687 @@
// Package composition 是进程唯一的跨层装配根。
package composition
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
adminapp "xianyu-go/internal/application/admin"
analyticsapp "xianyu-go/internal/application/analytics"
automationapp "xianyu-go/internal/application/automation"
cardsapp "xianyu-go/internal/application/cards"
chatapp "xianyu-go/internal/application/chat"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
itemapp "xianyu-go/internal/application/items"
keywordsapp "xianyu-go/internal/application/keywords"
lifecycleapp "xianyu-go/internal/application/lifecycle"
notificationsapp "xianyu-go/internal/application/notifications"
orderapp "xianyu-go/internal/application/orders"
settingsapp "xianyu-go/internal/application/settings"
"xianyu-go/internal/automation"
"xianyu-go/internal/chat"
"xianyu-go/internal/netguard"
"xianyu-go/internal/notify"
)
const (
// refreshOrderChunkSize 限制单次订单刷新在应用层处理的账号数量。
refreshOrderChunkSize = 100
// publishBatchLease 是发布 worker 对单批次持有租约的最长时间。
publishBatchLease = 5 * time.Minute
)
// Services 聚合组合根已完成构造的应用服务与后台组件。
// 它只由 composition 创建,随后通过 server.Dependencies 的最小 Port 交给 HTTP transport。
type Services struct {
// qrLogin 是二维码平台协议的组合层私有实例,只通过 HTTP 用例 Port 暴露。
qrLogin adapter.QRLoginService
// platformCredentials 负责按需读取平台凭证窄视图并执行归属复核。
platformCredentials *accountapp.PlatformCredentialService
// orders 是订单 HTTP 适配器;业务服务集合由应用层统一构造。
orders *orderapp.ServiceSet
// orderRefreshJobs 是订单刷新任务创建、取消、恢复和 worker 生命周期应用服务。
orderRefreshJobs *orderapp.RefreshJobService
// orderReconciliationRecovery 是订单补偿扫描器的应用层生命周期协调器。
orderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
// itemSinglePublish 是仅负责单商品发布用例的纯应用服务。
itemSinglePublish *itemapp.Service
// itemBatchCoordinator 是商品批量发布 worker、恢复扫描和关闭等待的生命周期拥有者。
itemBatchCoordinator *itemapp.BatchWorkerCoordinator
// itemBatchPreview 是商品批量发布表格预检应用服务。
itemBatchPreview *itemapp.BatchPreviewService
// itemBatchManagement 是商品批次查询、取消和重试应用服务。
itemBatchManagement *itemapp.BatchManagementService
// itemCategoryRecommendation 是商品类目推荐应用服务。
itemCategoryRecommendation *itemapp.CategoryRecommendationService
// itemBatchPreviewPersistence 是预检结果持久化应用服务。
itemBatchPreviewPersistence *itemapp.BatchPreviewPersistenceService
// itemBatchLocalPublish 是远端发布成功后的本地商品与规则收口服务。
itemBatchLocalPublish *itemapp.BatchLocalPublishService
// itemSync 是商品全量和分页同步应用服务。
itemSync *itemapp.SyncService
// itemCatalog 是商品列表和详情读取应用服务。
itemCatalog *itemapp.CatalogService
// itemCatalogMutation 是商品创建、更新、删除和交付开关应用服务。
itemCatalogMutation *itemapp.CatalogMutationService
// accountLogin 是账号登录应用服务。
accountLogin *accountLoginService
// authentication 是用户会话、密码校验和登录凭据应用服务。
authentication *accountapp.AuthenticationService
// loginAudit 是登录成功审计应用服务,负责方式归一化和账号启用编排。
loginAudit *accountapp.LoginAuditService
// passwordLogin 是密码登录策略应用服务;当前只返回关闭策略,不保存登录秘密或会话。
passwordLogin *accountapp.PasswordLoginService
// accountDelete 是账号删除应用服务,负责停止 fencing 和归属复核后的持久化删除。
accountDelete *accountapp.DeleteService
// accountProfile 是账号资料刷新应用服务。
accountProfile *accountapp.ProfileService
// accountLongLogin 是账号长登录设置应用服务。
accountLongLogin *accountapp.LongLoginService
// accountSettings 是账号设置、登录信息、启停和暂停应用服务。
accountSettings *accountapp.SettingsService
// accountRuntime 是账号凭证写回后的运行时同步与状态快照应用服务。
accountRuntime *accountapp.RuntimeService
// accountSummaries 是账号摘要、所有权和管理员账号列表应用服务。
accountSummaries *accountapp.SummaryService
// accountTasks 是账号任务设置、历史和手动执行应用服务。
accountTasks *automationapp.Service
// credentialWake 是凭证恢复后唤醒自动化任务的应用服务。
credentialWake *automationapp.CredentialWakeService
// chat 是聊天历史查询应用服务,负责用户归属和分页编排。
chat *chatapp.Service
// uncertainNotifications 是通知不确定状态运维查询应用服务。
uncertainNotifications *notificationsapp.Service
// notificationChannels 是通知渠道 CRUD 与账号绑定应用服务。
notificationChannels *notificationsapp.ChannelService
// analytics 是订单分析应用服务。
analytics *analyticsapp.Service
// automationIssues 是自动化异常查询与人工处理应用服务。
automationIssues *automationapp.IssueService
// automationRules 是自动化规则校验、分页和持久化应用服务。
automationRules *automationapp.RuleService
// cards 是卡券 CRUD、输入校验和所有权编排应用服务。
cards *cardsapp.Service
// publishAutomationRules 是批量发布成功后幂等准备自动化规则的应用服务。
publishAutomationRules *automationapp.PublishRuleService
// defaultReplies 是默认回复配置与投递记录应用服务。
defaultReplies *defaultreplyapp.Service
// keywords 是关键词规则与指定商品回复应用服务。
keywords *keywordsapp.Service
// settings 是系统、用户和账号 AI 设置应用服务。
settings *settingsapp.Service
// admin 是管理员用户管理与全局统计应用服务。
admin *adminapp.Service
}
// Dependencies 是进程组合根构造应用服务所需的不可变依赖集合。
// 它不包含 HTTP Server;服务只能使用窄仓储工厂、运行时端口和受控回调。
type Dependencies struct {
// OrderDependencies 创建订单用例的持久化与运行时适配器。
OrderDependencies *adapter.OrderDependencies
// AccountDependencies 创建账号、认证和登录审计用例的持久化适配器。
AccountDependencies *adapter.AccountDependencies
// ItemDependencies 创建商品同步、发布和批量 worker 用例的适配器。
ItemDependencies *adapter.ItemDependencies
// ChatDependencies 创建聊天发送应用服务。
ChatDependencies *adapter.ChatDependencies
// AutomationDependencies 创建自动化唤醒和发布后规则用例。
AutomationDependencies *adapter.AutomationDependencies
// TransportApplications 保存已由组合根装配的其余应用服务。
TransportApplications *adapter.TransportApplicationServices
// OrderReconciliationRecovery 保存订单补偿扫描生命周期服务。
OrderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
// Manager 提供账号运行时应用端口。
Manager *account.Manager
// Automation 提供订单手动发货应用端口。
Automation *automation.Center
// Notifier 提供订单通知应用端口。
Notifier *notify.Notifier
// Chat 提供聊天领域事件服务。
Chat *chat.Service
// Logger 记录不含秘密的后台任务诊断。
Logger *slog.Logger
// MTopClient 返回当前平台 MTOP 客户端。
MTopClient func() adapter.MTOPClient
// LongLoginClient 返回当前平台长登录客户端。
LongLoginClient func() adapter.LongLoginClient
// QRLogin 提供二维码生成、轮询和风控完成的底层平台能力。
QRLogin adapter.QRLoginService
// UpdateRunningCookie 同步平台响应 Cookie 到账号运行时。
UpdateRunningCookie func(context.Context, string, string)
// SessionRecovery 处理平台会话失效后的账号恢复。
SessionRecovery adapter.SessionRecoveryHandler
// LifecycleContext 返回进程协调器拥有的应用生命周期 Context。
LifecycleContext func() context.Context
}
// LifecycleComponents 返回由组合根登记的应用 worker 生命周期组件。
// 组件只暴露 Start/Close 端口,启动顺序与进程取消责任由 cmd 的协调器拥有。
func (services *Services) LifecycleComponents() []lifecycleapp.NamedComponent {
if services == nil {
return nil
}
// components 保存按应用依赖登记的 worker 生命周期组件。
components := make([]lifecycleapp.NamedComponent, 0, 3)
if services.orderRefreshJobs != nil {
// service 保存订单刷新恢复与 worker 生命周期应用服务。
service := services.orderRefreshJobs
components = append(components, lifecycleapp.NamedComponent{
Name: "order-refresh-recovery",
Component: lifecycleapp.FuncComponent{
StartFunc: service.StartRecovery,
CloseFunc: service.Close,
},
})
}
if services.itemBatchCoordinator != nil {
// coordinator 保存批量发布 worker 与恢复扫描生命周期协调器。
coordinator := services.itemBatchCoordinator
components = append(components, lifecycleapp.NamedComponent{
Name: "publish-batch-workers",
Component: lifecycleapp.FuncComponent{
StartFunc: coordinator.StartRecovery,
CloseFunc: coordinator.Close,
},
})
}
if services.orderReconciliationRecovery != nil {
// coordinator 保存订单补偿扫描生命周期协调器。
coordinator := services.orderReconciliationRecovery
components = append(components, lifecycleapp.NamedComponent{
Name: "order-reconciliation-recovery",
Component: lifecycleapp.FuncComponent{
StartFunc: coordinator.Start,
CloseFunc: coordinator.Close,
},
})
}
return components
}
// UpdateRunningCookie 将平台响应中的 Cookie 变化同步到账号运行时并唤醒受影响任务。
func (services *Services) UpdateRunningCookie(ctx context.Context, accountID, value string) error {
if services == nil || services.accountRuntime == nil {
return nil
}
return services.accountRuntime.UpdateCookie(ctx, accountID, value)
}
// RecoverExpiredCredential 将已确认的会话失效转交给账号运行时恢复。
func (services *Services) RecoverExpiredCredential(ctx context.Context, accountID string) bool {
return services != nil && services.accountRuntime != nil && services.accountRuntime.RecoverExpiredCredential(ctx, accountID)
}
// AccountLogin 是 transport 消费 Cookie 与二维码登录用例所需的最小组合层 Port。
type AccountLogin interface {
CreateCookie(context.Context, string, string, int64, string) error
UpdateCookie(context.Context, string, string, int64, string, int64) error
PersistQRLoginSuccess(context.Context, int64, string, map[string]any, string) (CookieLoginResult, error)
RegisterQRSession(string, int64, time.Time)
AuthorizeQRSession(string, int64) error
CleanupQRSessions(time.Time) []string
}
// TransportPorts 是组合层向 transport 投影层交付的只读应用服务快照。
type TransportPorts struct {
Orders *orderapp.ServiceSet
OrderRefreshJobs *orderapp.RefreshJobService
ItemSinglePublish *itemapp.Service
ItemBatchPreview *itemapp.BatchPreviewService
ItemBatchManagement *itemapp.BatchManagementService
ItemCategoryRecommendation *itemapp.CategoryRecommendationService
ItemBatchPreviewPersistence *itemapp.BatchPreviewPersistenceService
ItemBatchLocalPublish *itemapp.BatchLocalPublishService
ItemSync *itemapp.SyncService
ItemCatalog *itemapp.CatalogService
ItemCatalogMutation *itemapp.CatalogMutationService
AccountLogin AccountLogin
QRLogin adapter.QRLoginService
PlatformCredentials *accountapp.PlatformCredentialService
Authentication *accountapp.AuthenticationService
LoginAudit *accountapp.LoginAuditService
PasswordLogin *accountapp.PasswordLoginService
AccountDelete *accountapp.DeleteService
AccountProfile *accountapp.ProfileService
AccountLongLogin *accountapp.LongLoginService
AccountSettings *accountapp.SettingsService
AccountRuntime *accountapp.RuntimeService
AccountSummaries *accountapp.SummaryService
AccountTasks *automationapp.Service
Chat *chatapp.Service
UncertainNotifications *notificationsapp.Service
NotificationChannels *notificationsapp.ChannelService
Analytics *analyticsapp.Service
AutomationIssues *automationapp.IssueService
AutomationRules *automationapp.RuleService
Cards *cardsapp.Service
PublishAutomationRules *automationapp.PublishRuleService
DefaultReplies *defaultreplyapp.Service
Keywords *keywordsapp.Service
Settings *settingsapp.Service
Admin *adminapp.Service
}
// TransportPorts 返回已完成构造的只读服务引用;调用方不得在运行期替换任何字段。
func (services *Services) TransportPorts() TransportPorts {
if services == nil {
return TransportPorts{}
}
return TransportPorts{
Orders: services.orders, OrderRefreshJobs: services.orderRefreshJobs, ItemSinglePublish: services.itemSinglePublish,
ItemBatchPreview: services.itemBatchPreview, ItemBatchManagement: services.itemBatchManagement,
ItemCategoryRecommendation: services.itemCategoryRecommendation, ItemBatchPreviewPersistence: services.itemBatchPreviewPersistence,
ItemBatchLocalPublish: services.itemBatchLocalPublish, ItemSync: services.itemSync, ItemCatalog: services.itemCatalog,
ItemCatalogMutation: services.itemCatalogMutation, AccountLogin: services.accountLogin, QRLogin: services.qrLogin,
PlatformCredentials: services.platformCredentials, Authentication: services.authentication, LoginAudit: services.loginAudit,
PasswordLogin: services.passwordLogin, AccountDelete: services.accountDelete, AccountProfile: services.accountProfile,
AccountLongLogin: services.accountLongLogin, AccountSettings: services.accountSettings, AccountRuntime: services.accountRuntime,
AccountSummaries: services.accountSummaries, AccountTasks: services.accountTasks, Chat: services.chat,
UncertainNotifications: services.uncertainNotifications, NotificationChannels: services.notificationChannels,
Analytics: services.analytics, AutomationIssues: services.automationIssues, AutomationRules: services.automationRules,
Cards: services.cards, PublishAutomationRules: services.publishAutomationRules, DefaultReplies: services.defaultReplies,
Keywords: services.keywords, Settings: services.settings, Admin: services.admin,
}
}
// New 由进程组合根装配全部应用服务,并在启动前拒绝半初始化依赖。
func New(dependencies Dependencies) (*Services, error) {
if dependencies.OrderDependencies == nil || dependencies.AccountDependencies == nil || dependencies.ItemDependencies == nil || dependencies.ChatDependencies == nil || dependencies.AutomationDependencies == nil || dependencies.TransportApplications == nil || dependencies.OrderReconciliationRecovery == nil || dependencies.Manager == nil || dependencies.MTopClient == nil || dependencies.LongLoginClient == nil || dependencies.QRLogin == nil || dependencies.UpdateRunningCookie == nil || dependencies.LifecycleContext == nil {
return nil, fmt.Errorf("应用服务组合依赖不完整")
}
// transportValidationErr 表示组合根预构造的 transport-facing 服务集合是否存在半初始化字段。
if transportValidationErr := dependencies.TransportApplications.Validate(); transportValidationErr != nil {
return nil, fmt.Errorf("transport 应用服务无效: %w", transportValidationErr)
}
// orderServices、orderRefreshJobs、orderBuildErr 分别是订单用例集合、刷新任务门面及其构造错误。
orderServices, orderRefreshJobs, orderBuildErr := buildOrderServices(dependencies)
if orderBuildErr != nil {
return nil, orderBuildErr
}
// accountProfile 保存账号资料刷新用例的构造结果。
// accountRepository 提供账号登录、资料摘要和删除共用的数据库适配器。
accountRepository := dependencies.AccountDependencies.NewAccountLoginRepository()
// platformCredentials 将账号凭证读取限制在消费者定义的只读应用端口。
platformCredentials, platformCredentialsErr := accountapp.NewPlatformCredentialService(accountRepository)
if platformCredentialsErr != nil {
return nil, fmt.Errorf("构造平台凭证服务失败: %w", platformCredentialsErr)
}
// cookieWriterFactory 将明文 Cookie 封装在 adapter 的请求范围实例中,Server 不持有凭证仓储。
cookieWriterFactory := func(cookies string) accountapp.CookieWriter {
return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, dependencies.Logger)
}
// cookieUpdaterFactory 将既有账号的明文 Cookie 封装在 adapter 的请求范围实例中。
cookieUpdaterFactory := func(cookies string) accountapp.CookieUpdater {
return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, dependencies.Logger)
}
// sessionRecovery 统一适配平台 Session 失效分类、诊断日志和账号运行时恢复。
sessionRecovery := dependencies.SessionRecovery
// accountProfile 由应用层服务编排平台资料刷新与非敏感摘要持久化。
accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, dependencies.MTopClient, dependencies.UpdateRunningCookie, sessionRecovery, dependencies.Logger))
if profileErr != nil {
return nil, fmt.Errorf("构造账号资料服务失败: %w", profileErr)
}
// accountLongLogin 由适配器承载平台调用、Cookie 快照合并和凭证写回。
accountLongLogin, longLoginErr := accountapp.NewLongLoginService(
accountRepository,
adapter.NewLongLoginAdapter(accountRepository, dependencies.LongLoginClient, dependencies.UpdateRunningCookie, dependencies.Logger),
)
if longLoginErr != nil {
return nil, fmt.Errorf("构造账号长登录服务失败: %w", longLoginErr)
}
// accountSettings 由独立适配器承载账号设置写入与敏感登录信息更新。
var settingsRuntime accountapp.SettingsRuntime
if dependencies.Manager != nil {
settingsRuntime = dependencies.Manager
}
// accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。
accountSettings, accountSettingsErr := accountapp.NewSettingsService(dependencies.AccountDependencies.NewAccountSettingsRepository(), settingsRuntime)
if accountSettingsErr != nil {
return nil, fmt.Errorf("构造账号设置服务失败: %w", accountSettingsErr)
}
// accountSummaryRepository 保存普通用户与管理员共用的摘要查询适配器。
accountSummaryRepository := dependencies.AccountDependencies.NewAccountSummaryRepository()
// accountSummaries、accountSummariesErr 保存账号摘要应用服务及其装配错误。
accountSummaries, accountSummariesErr := accountapp.NewSummaryService(accountSummaryRepository, accountSummaryRepository)
if accountSummariesErr != nil {
return nil, fmt.Errorf("构造账号摘要服务失败: %w", accountSummariesErr)
}
// credentialWake 负责将凭证恢复后的任务唤醒写入收口到适配器。
// automationDependencies 提供自动化、默认回复和关键词用例的显式适配器工厂。
automationDependencies := dependencies.AutomationDependencies
if automationDependencies == nil {
return nil, fmt.Errorf("自动化专用依赖未装配")
}
// credentialWake、credentialWakeErr 保存凭证恢复后的自动化唤醒应用服务及装配错误。
credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(automationDependencies.NewAutomationCredentialWakeRepository())
if credentialWakeErr != nil {
return nil, fmt.Errorf("构造凭证恢复唤醒服务失败: %w", credentialWakeErr)
}
// accountRuntime 将 Manager 与凭证恢复后的自动化唤醒收口到账号应用端口。
accountRuntime := accountapp.NewRuntimeService(adapter.NewAccountRuntimePort(dependencies.Manager), credentialWake)
// loginSuccess 负责登录成功后的资料刷新和启用账号运行时重启,避免 Server 持有业务编排。
loginSuccess := accountapp.NewLoginSuccessService(accountRepository, accountProfile, accountRepository, accountRuntime, func(message string, err error) {
if dependencies.Logger != nil {
dependencies.Logger.Warn(message, "err", err)
}
})
// loginAudit 负责登录方式、账号启用和审计日志写入,生命周期适配器只组合应用端口。
loginAudit := accountapp.NewLoginAuditService(dependencies.AccountDependencies.NewAccountLoginAuditRepository())
// loginLifecycle 将手动登录与扫码登录的成功后续动作收口到 adapter,不再反向持有 Server。
loginLifecycle := adapter.NewAccountLoginLifecycle(loginAudit, loginSuccess, dependencies.Logger)
// deleteRuntime 是可选的账号运行时端口;显式保持 nil,避免把 nil *Manager 装入非空接口后触发 panic。
var deleteRuntime accountapp.DeleteRuntime
if dependencies.Manager != nil {
deleteRuntime = dependencies.Manager
}
// accountDelete 是账号删除用例的构造结果,运行时端口可为空以兼容无 Manager 的测试 Server。
accountDelete, deleteErr := accountapp.NewDeleteService(accountRepository, deleteRuntime)
if deleteErr != nil {
return nil, fmt.Errorf("构造账号删除服务失败: %w", deleteErr)
}
// itemBatchPublish 是批量远端发布适配器,图片安全回调由 Server 装配时注入。
itemBatchPublish := dependencies.ItemDependencies.NewItemBatchPublishPort(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) {
if sessionRecovery != nil {
sessionRecovery(ctx, cookieID, err)
}
}, readBatchImageFile, downloadImageURL)
// itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。
itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService(
dependencies.ItemDependencies.NewItemBatchRepository(),
dependencies.ItemDependencies.NewItemCatalogRepository(),
automationDependencies.NewAutomationRepository(),
)
if itemBatchLocalPublishErr != nil {
return nil, fmt.Errorf("构造批量发布本地收口服务失败: %w", itemBatchLocalPublishErr)
}
// itemBatchPublisher、itemBatchPublisherErr 分别保存批量发布端口适配器及其组合期错误。
itemBatchPublisher, itemBatchPublisherErr := adapter.NewItemBatchPublisher(itemBatchPublish, itemBatchLocalPublish)
if itemBatchPublisherErr != nil {
return nil, fmt.Errorf("构造批量发布 publisher 失败: %w", itemBatchPublisherErr)
}
// itemBatchRunner、batchRunnerErr 分别保存批量发布 worker 及其必需端口装配错误。
itemBatchRunner, batchRunnerErr := adapter.NewItemBatchRunnerApplication(dependencies.ItemDependencies.NewItemBatchRepository(), itemBatchPublisher, publishBatchLease, publishBatchFailure)
if batchRunnerErr != nil {
return nil, fmt.Errorf("构造批量发布运行器失败: %w", batchRunnerErr)
}
// itemBatchRecovery 负责恢复扫描的批次状态编排;worker 生命周期由协调器拥有。
itemBatchRecovery, batchRecoveryErr := itemapp.NewBatchRecoveryService(
dependencies.ItemDependencies.NewItemBatchRepository(),
itemapp.BatchRecoveryOptions{LeaseDuration: publishBatchLease},
)
if batchRecoveryErr != nil {
return nil, fmt.Errorf("构造批量发布恢复服务失败: %w", batchRecoveryErr)
}
// itemBatchCoordinator 负责批次 worker 的超时、恢复扫描和停止等待。
itemBatchCoordinator, batchCoordinatorErr := itemapp.NewBatchWorkerCoordinator(itemBatchRunner, itemBatchRecovery, itemapp.BatchWorkerCoordinatorOptions{
OnWorkerError: func(batchID string, err error) {
if dependencies.Logger != nil {
dependencies.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", err)
}
},
OnRecoveryError: func(err error) {
if dependencies.Logger != nil {
dependencies.Logger.Warn("扫描可恢复批量发布任务失败", "err", err)
}
},
})
if batchCoordinatorErr != nil {
return nil, fmt.Errorf("构造批量发布协调器失败: %w", batchCoordinatorErr)
}
// itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。
itemBatchPreviewPort := dependencies.ItemDependencies.NewItemBatchPreviewPort()
// itemBatchPreview 是批量发布预检应用服务的构造结果。
itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort)
if itemBatchPreviewErr != nil {
return nil, fmt.Errorf("构造批量发布预检服务失败: %w", itemBatchPreviewErr)
}
// itemBatchManagement 是批次管理应用服务的构造结果。
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(dependencies.ItemDependencies.NewItemBatchRepository(), adapter.NewBatchManagementRuntime(dependencies.LifecycleContext, itemBatchCoordinator))
if itemBatchManagementErr != nil {
return nil, fmt.Errorf("构造批量发布管理服务失败: %w", itemBatchManagementErr)
}
// accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。
accountLoginCreate, accountLoginCreateErr := accountapp.NewLoginService(loginLifecycle)
if accountLoginCreateErr != nil {
return nil, fmt.Errorf("构造账号登录创建服务失败: %w", accountLoginCreateErr)
}
// accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。
var accountQRLogin *accountapp.QRLoginService
if dependencies.AccountDependencies != nil {
// accountQRLoginErr 保存扫码应用服务装配失败原因。
var accountQRLoginErr error
accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(dependencies.AccountDependencies.NewQRLoginRepository(), loginLifecycle)
if accountQRLoginErr != nil {
return nil, fmt.Errorf("构造扫码登录服务失败: %w", accountQRLoginErr)
}
}
// qrSessionRegistry 将扫码会话所有权、过期回收和幂等结果放在应用边界内。
qrSessionRegistry := accountapp.NewQRLoginSessionRegistry()
// itemCatalogRepository 是商品读写用例共用的数据库适配器。
itemCatalogRepository := dependencies.ItemDependencies.NewItemCatalogRepository()
// itemCatalog 是商品列表和详情读取用例的应用服务。
itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository)
if itemCatalogErr != nil {
return nil, fmt.Errorf("构造商品目录服务失败: %w", itemCatalogErr)
}
// itemCatalogMutation 是商品写入用例的应用服务。
itemCatalogMutation, itemCatalogMutationErr := itemapp.NewCatalogMutationService(itemCatalogRepository)
if itemCatalogMutationErr != nil {
return nil, fmt.Errorf("构造商品目录写入服务失败: %w", itemCatalogMutationErr)
}
// itemPublishPort 是单商品与批量发布共享的平台凭证适配器。
itemPublishPort := dependencies.ItemDependencies.NewItemPublishPort(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) bool {
return sessionRecovery != nil && sessionRecovery(ctx, cookieID, err)
})
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
if itemCategoryRecommendationErr != nil {
return nil, fmt.Errorf("构造商品类目推荐服务失败: %w", itemCategoryRecommendationErr)
}
// itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(dependencies.ItemDependencies.NewItemBatchRepository())
if itemBatchPreviewPersistenceErr != nil {
return nil, fmt.Errorf("构造批量预检持久化服务失败: %w", itemBatchPreviewPersistenceErr)
}
// itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。
itemSinglePublish, itemSinglePublishErr := itemapp.NewService(
itemPublishPort,
dependencies.ItemDependencies.NewItemPublishRepository(),
)
if itemSinglePublishErr != nil {
return nil, fmt.Errorf("构造单商品发布服务失败: %w", itemSinglePublishErr)
}
// services 是完成构造后只读注入 Server 的应用服务集合。
services := &Services{
qrLogin: dependencies.QRLogin,
platformCredentials: platformCredentials,
orders: orderServices,
orderRefreshJobs: orderRefreshJobs,
orderReconciliationRecovery: dependencies.OrderReconciliationRecovery,
itemSinglePublish: itemSinglePublish,
itemBatchCoordinator: itemBatchCoordinator,
itemBatchPreview: itemBatchPreview,
itemBatchManagement: itemBatchManagement,
itemCategoryRecommendation: itemCategoryRecommendation,
itemBatchPreviewPersistence: itemBatchPreviewPersistence,
itemBatchLocalPublish: itemBatchLocalPublish,
itemSync: itemapp.NewSyncService(dependencies.ItemDependencies.NewItemSyncRepository(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) {
if sessionRecovery != nil {
sessionRecovery(ctx, cookieID, err)
}
})),
itemCatalog: itemCatalog,
itemCatalogMutation: itemCatalogMutation,
accountLogin: &accountLoginService{cookieWriterFactory: cookieWriterFactory, cookieUpdaterFactory: cookieUpdaterFactory, sessionPort: accountRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin, qrSessions: qrSessionRegistry},
authentication: nil,
loginAudit: loginAudit,
passwordLogin: accountapp.NewPasswordLoginService(),
accountDelete: accountDelete,
accountProfile: accountProfile,
accountLongLogin: accountLongLogin,
accountSettings: accountSettings,
accountRuntime: accountRuntime,
accountSummaries: accountSummaries,
accountTasks: dependencies.TransportApplications.AccountTasks,
credentialWake: credentialWake,
chat: dependencies.ChatDependencies.NewChatSendingApplication(dependencies.Chat, dependencies.Manager, dependencies.MTopClient),
uncertainNotifications: dependencies.TransportApplications.UncertainNotifications,
notificationChannels: dependencies.TransportApplications.NotificationChannels,
analytics: dependencies.TransportApplications.Analytics,
automationRules: dependencies.TransportApplications.AutomationRules,
cards: dependencies.TransportApplications.Cards,
publishAutomationRules: dependencies.TransportApplications.PublishAutomationRules,
automationIssues: dependencies.TransportApplications.AutomationIssues,
defaultReplies: dependencies.TransportApplications.DefaultReplies,
keywords: dependencies.TransportApplications.Keywords,
settings: dependencies.TransportApplications.Settings,
admin: dependencies.TransportApplications.Admin,
}
// authentication、authenticationErr 分别是认证应用服务及其构造错误。
authentication, authenticationErr := accountapp.NewAuthenticationService(dependencies.AccountDependencies.NewAuthenticationRepository())
if authenticationErr != nil {
return nil, authenticationErr
}
services.authentication = authentication
return services, nil
}
// buildOrderServices 构造订单用例集合及其刷新 worker 门面,并把后台诊断限制在组合根。
func buildOrderServices(dependencies Dependencies) (*orderapp.ServiceSet, *orderapp.RefreshJobService, error) {
// orderRepository 保存订单应用服务共享的基础设施适配器。
orderRepository := dependencies.OrderDependencies.NewOrderRepository()
// orderReconciliation 保存订单补偿写入应用 Port 的数据库适配器。
orderReconciliation := dependencies.OrderDependencies.NewOrderReconciliationRepository()
// orderRuntime 保存订单服务共享的运行时能力适配器。
orderRuntime := adapter.NewOrderRuntimeAdapter(dependencies.OrderDependencies, dependencies.Manager, dependencies.Automation, dependencies.Notifier, dependencies.MTopClient, dependencies.UpdateRunningCookie, dependencies.SessionRecovery, dependencies.Logger, orderReconciliation)
// orderServices 保存应用层统一构造的订单业务服务集合。
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, dependencies.OrderDependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize)
// orderRefreshRunner 是订单刷新后台 worker 与恢复扫描的生命周期拥有者。
orderRefreshRunner, orderRefreshRunnerErr := orderapp.NewRefreshJobRunner(
orderServices.RefreshJobs,
orderServices.Refresh,
orderapp.RefreshJobRunnerOptions{
OnWorkerError: func(jobID string, err error) {
if dependencies.Logger != nil {
dependencies.Logger.Warn("订单刷新后台任务结束", "job_id", jobID, "err", err)
}
},
OnRecoveryError: func(err error) {
if dependencies.Logger != nil {
dependencies.Logger.Warn("扫描订单刷新恢复任务失败", "err", err)
}
},
},
)
if orderRefreshRunnerErr != nil {
return nil, nil, fmt.Errorf("构造订单刷新运行器失败: %w", orderRefreshRunnerErr)
}
// orderRefreshJobs 是订单刷新任务应用 facade,封装归属、租约和 worker 启动编排。
orderRefreshJobs, orderRefreshJobsErr := orderapp.NewRefreshJobService(orderServices.RefreshJobs, orderServices.Refresh, orderRefreshRunner, orderapp.RefreshJobServiceOptions{})
if orderRefreshJobsErr != nil {
return nil, nil, fmt.Errorf("构造订单刷新应用服务失败: %w", orderRefreshJobsErr)
}
return orderServices, orderRefreshJobs, nil
}
// readBatchImageFile 从上传目录读取一张受路径边界保护的发布图片。
func readBatchImageFile(uploadDir, reference string) ([]byte, string, string, error) {
// relativePath 是上传目录内的清理后相对图片路径,绝不允许越界到宿主文件系统。
relativePath := filepath.Clean(strings.TrimSpace(reference))
if relativePath == "." || filepath.IsAbs(relativePath) || relativePath == ".." || strings.HasPrefix(relativePath, ".."+string(filepath.Separator)) {
return nil, "", "", fmt.Errorf("图片路径无效")
}
// root、openErr 分别是受限上传目录句柄及其打开错误。
root, openErr := os.OpenRoot(uploadDir)
if openErr != nil {
return nil, "", "", fmt.Errorf("打开图片目录失败")
}
defer root.Close()
// file、fileErr 分别是受目录边界保护的图片文件及其读取错误。
file, fileErr := root.Open(relativePath)
if fileErr != nil {
return nil, "", "", fmt.Errorf("读取图片失败: %s", reference)
}
defer file.Close()
// data、readErr 分别是受 10 MiB 限制的图片字节及其读取错误。
data, readErr := io.ReadAll(io.LimitReader(file, (10<<20)+1))
if readErr != nil || len(data) == 0 || len(data) > 10<<20 {
return nil, "", "", fmt.Errorf("读取图片失败或文件过大: %s", reference)
}
// contentType 是按实际字节识别的媒体类型,用于拒绝伪装的非图片文件。
contentType := http.DetectContentType(data)
if !strings.HasPrefix(contentType, "image/") {
return nil, "", "", fmt.Errorf("不是有效图片: %s", reference)
}
return data, contentType, filepath.Base(relativePath), nil
}
// downloadImageURL 仅从公网地址下载受大小和媒体类型限制的发布图片。
func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error) {
// request、requestErr 分别是受调用方取消控制的公网图片下载请求及其构造错误。
request, requestErr := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if requestErr != nil || (request.URL.Scheme != "http" && request.URL.Scheme != "https") || request.URL.Hostname() == "" {
return nil, "", fmt.Errorf("图片 URL 无效: %s", rawURL)
}
// client 是限制内网访问的公网 HTTP 客户端;response、responseErr 是下载响应及其网络错误。
client := netguard.PublicHTTPClient(30 * time.Second)
// response、responseErr 分别是远端图片响应及网络失败;正文必须在本函数返回前关闭。
response, responseErr := client.Do(request)
if responseErr != nil {
return nil, "", fmt.Errorf("下载图片失败: %s", rawURL)
}
defer response.Body.Close()
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
return nil, "", fmt.Errorf("下载图片失败: %s HTTP %d", rawURL, response.StatusCode)
}
// data、readErr 分别是受大小限制的远端图片字节及其读取错误。
data, readErr := io.ReadAll(io.LimitReader(response.Body, (10<<20)+1))
if readErr != nil || len(data) > 10<<20 {
return nil, "", fmt.Errorf("读取远程图片失败: %s", rawURL)
}
// contentType 是响应声明或字节探测得到的媒体类型。
contentType := strings.Split(response.Header.Get("Content-Type"), ";")[0]
if contentType == "" || contentType == "application/octet-stream" {
contentType = http.DetectContentType(data)
}
if !strings.HasPrefix(contentType, "image/") {
return nil, "", fmt.Errorf("远程文件不是图片: %s", rawURL)
}
return data, contentType, nil
}
// publishBatchFailure 将应用层的远端不确定和后置持久化错误转换为稳定批次失败分类。
func publishBatchFailure(err error, batchStatus string) (string, string) {
// message、failureKind 分别是可展示失败摘要和持久化的稳定失败分类。
message := err.Error()
// failureKind 是批次记录使用的稳定失败分类,供后续恢复流程避免误重试。
failureKind := "publish"
// uncertainErr、postErr 用于识别远端结果不确定和本地收口失败两种不可自动重试情形。
var uncertainErr *itemapp.UncertainRemotePublishError
// postErr 指向远端发布后本地持久化失败的应用错误,结果必须转人工核对。
var postErr *itemapp.PostPublishError
if errors.As(err, &uncertainErr) {
failureKind = "uncertain_remote"
message += ";远端结果未能可靠落库,禁止自动重试,请人工核对闲鱼商品列表"
} else if errors.As(err, &postErr) {
failureKind = "post_publish"
}
if batchStatus == "canceled" || batchStatus == "canceling" {
if failureKind == "uncertain_remote" {
message = "任务已取消;" + message
} else {
message = "任务已取消"
}
}
return message, failureKind
}
@@ -0,0 +1,22 @@
package composition
import "testing"
// TestNewRejectsIncompleteDependencies 验证组合根会拒绝缺失的必需基础设施,避免半初始化服务进入 transport。
func TestNewRejectsIncompleteDependencies(t *testing.T) {
// services、buildErr 分别是缺失依赖时的构造结果和预期错误。
services, buildErr := New(Dependencies{})
if buildErr == nil || services != nil {
t.Fatalf("缺少组合依赖时应失败: services=%v err=%v", services, buildErr)
}
}
// TestServicesLifecycleComponentsNilSafe 验证空组合服务不会伪造后台组件所有权。
func TestServicesLifecycleComponentsNilSafe(t *testing.T) {
// services 是空组合服务指针;components 是其不应伪造的生命周期组件列表。
var services *Services
// components 是空服务返回的生命周期组件,空组合根不得声明后台组件所有权。
if components := services.LifecycleComponents(); components != nil {
t.Fatalf("空服务不应返回生命周期组件: %v", components)
}
}
+193
View File
@@ -0,0 +1,193 @@
package runtime
import (
"context"
"fmt"
"log/slog"
"xianyu-go/internal/adapter"
"xianyu-go/internal/application/lifecycle"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
composition "xianyu-go/internal/composition"
"xianyu-go/internal/db"
"xianyu-go/internal/renewal"
"xianyu-go/internal/server"
)
// RuntimeOptions 是 cmd 已解析后交给组合根的运行时配置。
type RuntimeOptions struct {
// NoBrowser 表示操作者显式禁用浏览器自动化。
NoBrowser bool
// SecureCookie 控制 HTTP 会话 Cookie 的 Secure 属性。
SecureCookie bool
// WebDir 是前端静态资源路径。
WebDir string
// Addr 是 HTTP 监听地址。
Addr string
}
// RuntimeInfrastructure 是 cmd 打开后交给组合根的基础设施资源。
type RuntimeInfrastructure struct {
// Store 是已迁移并完成敏感字段升级的数据库仓储入口。
Store *db.Store
// Logger 是进程级脱敏结构化日志器。
Logger *slog.Logger
}
// Runtime 是由组合根创建并由 cmd 启动、等待和关闭的完整进程运行时。
type Runtime struct {
// HTTPServer 是只持有 transport Port 的 HTTP 服务。
HTTPServer *server.Server
// Lifecycle 是 cmd 独占启动和关闭的后台组件协调器。
Lifecycle *lifecycle.Coordinator
}
// BuildRuntime 构造全部基础设施适配器、应用服务和生命周期组件,但不启动任何 worker。
func BuildRuntime(options RuntimeOptions, infrastructure RuntimeInfrastructure) (Runtime, error) {
if infrastructure.Store == nil || infrastructure.Logger == nil {
return Runtime{}, fmt.Errorf("组合根基础设施不完整")
}
// browserManager 是可选 Chromium 生命周期拥有者;禁用浏览器时保持 nil。
var browserManager *browser.Manager
if !options.NoBrowser {
browserManager = browser.NewManager(infrastructure.Logger)
}
// runtimeBundle、bundleErr 分别是账号运行时依赖集合及其构造失败原因。
runtimeBundle, bundleErr := adapter.NewRuntimeBundle(infrastructure.Store, browserManager, infrastructure.Logger)
if bundleErr != nil {
return Runtime{}, fmt.Errorf("构造账号运行时依赖失败: %w", bundleErr)
}
// lifecycleCoordinator 由 cmd 最终拥有,用于按顺序启动并逆序关闭后台组件。
lifecycleCoordinator := lifecycle.NewCoordinator()
if browserManager != nil {
// addErr 是浏览器组件登记失败原因,失败时运行时不得继续暴露。
if addErr := lifecycleCoordinator.Add(lifecycle.NamedComponent{Name: "browser", Component: lifecycle.FuncComponent{StartFunc: func(context.Context) error { return browserManager.Initialize() }, CloseFunc: browserManager.CloseContext}}); addErr != nil {
return Runtime{}, fmt.Errorf("登记浏览器生命周期组件失败: %w", addErr)
}
}
// automationScheduler、renewalScheduler 分别负责自动化延迟任务和凭证续期扫描。
automationScheduler := automation.NewScheduler(runtimeBundle.Automation)
// renewalScheduler 负责账号凭证的定期续期,其运行与停止由生命周期协调器统一拥有。
renewalScheduler := renewal.NewScheduler(infrastructure.Store, runtimeBundle.Manager, runtimeBundle.Adapter, infrastructure.Logger, runtimeBundle.Notifier)
// component 是按依赖顺序登记的基础后台组件,协调器负责后续取消和等待。
for _, component := range []lifecycle.NamedComponent{
{Name: "notifier", Component: lifecycle.FuncComponent{StartFunc: func(ctx context.Context) error { runtimeBundle.Notifier.Start(ctx); return nil }, CloseFunc: runtimeBundle.Notifier.WaitContext}},
{Name: "account-manager", Component: lifecycle.FuncComponent{StartFunc: runtimeBundle.Manager.StartAll, CloseFunc: runtimeBundle.Manager.StopAllContext}},
{Name: "automation-scheduler", Component: lifecycle.FuncComponent{StartFunc: func(ctx context.Context) error { go automationScheduler.Run(ctx); return nil }, CloseFunc: automationScheduler.WaitContext}},
{Name: "renewal-scheduler", Component: lifecycle.FuncComponent{StartFunc: func(ctx context.Context) error { go renewalScheduler.Run(ctx); return nil }, CloseFunc: renewalScheduler.StopContext}},
} {
// addErr 是当前后台组件登记失败原因。
if addErr := lifecycleCoordinator.Add(component); addErr != nil {
return Runtime{}, fmt.Errorf("登记生命周期组件 %q 失败: %w", component.Name, addErr)
}
}
// orderDependencies、orderErr 分别是订单应用服务的仓储适配器及其构造错误。
orderDependencies, orderErr := adapter.NewOrderDependencies(infrastructure.Store)
if orderErr != nil {
return Runtime{}, fmt.Errorf("构造订单基础设施依赖失败: %w", orderErr)
}
// accountDependencies、accountErr 分别是账号应用服务的仓储适配器及其构造错误。
accountDependencies, accountErr := adapter.NewAccountDependencies(infrastructure.Store)
if accountErr != nil {
return Runtime{}, fmt.Errorf("构造账号基础设施依赖失败: %w", accountErr)
}
// itemDependencies、itemErr 分别是商品应用服务的仓储适配器及其构造错误。
itemDependencies, itemErr := adapter.NewItemDependencies(infrastructure.Store)
if itemErr != nil {
return Runtime{}, fmt.Errorf("构造商品基础设施依赖失败: %w", itemErr)
}
// automationDependencies、automationErr 分别是自动化应用服务的仓储适配器及其构造错误。
automationDependencies, automationErr := adapter.NewAutomationDependencies(infrastructure.Store)
if automationErr != nil {
return Runtime{}, fmt.Errorf("构造自动化基础设施依赖失败: %w", automationErr)
}
// miscDependencies、miscErr 分别是通知、分析和卡券服务的仓储适配器及其构造错误。
miscDependencies, miscErr := adapter.NewMiscDependencies(infrastructure.Store)
if miscErr != nil {
return Runtime{}, fmt.Errorf("构造通知分析卡券基础设施依赖失败: %w", miscErr)
}
// adminSettingsDependencies、chatDependencies、systemDependencies 分别提供管理设置、聊天和系统探测适配器。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(infrastructure.Store)
// chatDependencies 提供聊天用例需要的持久化和平台适配能力。
chatDependencies := adapter.NewChatDependencies(infrastructure.Store)
// systemDependencies 提供健康检查和订单补偿等系统级窄适配能力。
systemDependencies := adapter.NewSystemDependencies(infrastructure.Store)
if adminSettingsDependencies == nil || chatDependencies == nil || systemDependencies == nil {
return Runtime{}, fmt.Errorf("构造 transport 基础设施依赖失败")
}
// orderReconciliationRecovery、reconciliationErr 分别是订单补偿协调器及其构造错误。
orderReconciliationRecovery, reconciliationErr := orderapp.NewReconciliationRecoveryCoordinator(systemDependencies.NewReconciliationService(infrastructure.Logger))
if reconciliationErr != nil {
return Runtime{}, fmt.Errorf("构造订单补偿恢复协调器失败: %w", reconciliationErr)
}
// databaseHealth 是 HTTP 健康检查使用的窄数据库探测 Port。
databaseHealth := systemDependencies.NewDatabaseHealth()
if databaseHealth == nil {
return Runtime{}, fmt.Errorf("构造数据库健康检查端口失败")
}
// platformDependencies、platformErr 分别是平台协议适配器集合及其构造错误,仅组合层可持有。
platformDependencies, platformErr := adapter.NewDefaultPlatformDependencies(infrastructure.Logger)
if platformErr != nil {
return Runtime{}, fmt.Errorf("构造平台基础设施依赖失败: %w", platformErr)
}
// transportApplications、transportErr 分别是通知等共享应用服务集合及其构造错误。
transportApplications, transportErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies, MiscDependencies: miscDependencies, AdminSettingsDependencies: adminSettingsDependencies,
AdminRuntime: runtimeBundle.Manager, AccountTaskRunner: adapter.NewAccountTaskRunner(runtimeBundle.Automation), ChannelSender: runtimeBundle.Notifier, ModelClient: adapter.NewAIModelClient(),
})
if transportErr != nil {
return Runtime{}, fmt.Errorf("构造 transport 应用服务失败: %w", transportErr)
}
// services 是完成构造后才供回调使用的应用服务集合,构造期保持 nil 防止半初始化调用。
var services *composition.Services
// updateRunningCookie 将平台返回的新 Cookie 同步到运行时;值不记录到日志。
updateRunningCookie := func(ctx context.Context, accountID, value string) {
if services == nil {
return
}
// updateErr 是 Cookie 写回账号运行时失败原因,不包含 Cookie 明文。
if updateErr := services.UpdateRunningCookie(ctx, accountID, value); updateErr != nil {
infrastructure.Logger.Warn("Cookie 更新后同步账号运行时失败", "cookie_id", accountID, "err", updateErr)
}
}
// sessionRecovery 仅把确认的会话失效交给已构造的账号应用服务恢复。
sessionRecovery := adapter.NewSessionRecoveryHandler(infrastructure.Logger, func(ctx context.Context, accountID string) bool {
return services != nil && services.RecoverExpiredCredential(ctx, accountID)
})
// services、buildErr 分别是完成装配的应用服务集合及其构造错误。
services, buildErr := composition.New(composition.Dependencies{
OrderDependencies: orderDependencies, AccountDependencies: accountDependencies, ItemDependencies: itemDependencies,
ChatDependencies: chatDependencies, AutomationDependencies: automationDependencies, TransportApplications: transportApplications,
OrderReconciliationRecovery: orderReconciliationRecovery, Manager: runtimeBundle.Manager, Automation: runtimeBundle.Automation,
Notifier: runtimeBundle.Notifier, Chat: runtimeBundle.Chat, Logger: infrastructure.Logger,
MTopClient: platformDependencies.MTOPClient, LongLoginClient: platformDependencies.LongLoginClient, QRLogin: platformDependencies.QRLoginService(),
UpdateRunningCookie: updateRunningCookie, SessionRecovery: sessionRecovery, LifecycleContext: lifecycleCoordinator.Context,
})
if buildErr != nil {
return Runtime{}, fmt.Errorf("构造应用服务集合失败: %w", buildErr)
}
// serverDependencies、dependenciesErr 分别是投影给 HTTP transport 的依赖快照及其构造错误。
serverDependencies, dependenciesErr := ServerDependencies(services, HTTPDependencies{
Auth: &auth.Service{Store: infrastructure.Store, Logger: infrastructure.Logger, Secure: options.SecureCookie}, WebDir: options.WebDir, Addr: options.Addr,
Logger: infrastructure.Logger, DatabaseHealth: databaseHealth,
}, sessionRecovery)
if dependenciesErr != nil {
return Runtime{}, dependenciesErr
}
// httpServer、serverErr 分别是纯 HTTP transport 实例及其构造错误。
httpServer, serverErr := server.New(serverDependencies)
if serverErr != nil {
return Runtime{}, fmt.Errorf("构造 HTTP 服务失败: %w", serverErr)
}
// component 是应用服务返回的 worker 生命周期组件,由协调器而非 Server 登记。
for _, component := range services.LifecycleComponents() {
// addErr 是应用 worker 组件登记失败原因。
if addErr := lifecycleCoordinator.Add(component); addErr != nil {
return Runtime{}, fmt.Errorf("登记应用 worker 生命周期组件 %q 失败: %w", component.Name, addErr)
}
}
return Runtime{HTTPServer: httpServer, Lifecycle: lifecycleCoordinator}, nil
}
@@ -0,0 +1,194 @@
package runtime
import (
"context"
"fmt"
"log/slog"
"time"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
composition "xianyu-go/internal/composition"
"xianyu-go/internal/server"
)
// accountLoginTransport 将组合层账号登录服务适配为 HTTP transport 消费的公开 Port。
type accountLoginTransport struct {
// service 是完成构造的账号登录应用服务,运行期不替换。
service composition.AccountLogin
}
// CreateCookie 透传新增 Cookie 登录命令到组合层账号登录服务。
func (transport accountLoginTransport) CreateCookie(ctx context.Context, accountID, cookies string, userID int64, loginMethod string) error {
return transport.service.CreateCookie(ctx, accountID, cookies, userID, loginMethod)
}
// UpdateCookie 透传 Cookie 更新命令到组合层账号登录服务。
func (transport accountLoginTransport) UpdateCookie(ctx context.Context, accountID, cookies string, userID int64, loginMethod string, expectedRevision int64) error {
return transport.service.UpdateCookie(ctx, accountID, cookies, userID, loginMethod, expectedRevision)
}
// PersistQRLoginSuccess 将组合层的持久化结果转换为 Server 可公开的非敏感结果。
func (transport accountLoginTransport) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (server.AccountLoginResult, error) {
// persisted、persistErr 分别是应用层已脱敏的登录结果及其持久化错误。
persisted, persistErr := transport.service.PersistQRLoginSuccess(ctx, userID, sessionID, result, targetAccountID)
if persistErr != nil {
return server.AccountLoginResult{}, persistErr
}
return server.AccountLoginResult{AccountID: persisted.AccountID, IsNew: persisted.IsNew}, nil
}
// RegisterQRSession 注册二维码会话所有权。
func (transport accountLoginTransport) RegisterQRSession(sessionID string, userID int64, createdAt time.Time) {
transport.service.RegisterQRSession(sessionID, userID, createdAt)
}
// AuthorizeQRSession 验证二维码会话所有权。
func (transport accountLoginTransport) AuthorizeQRSession(sessionID string, userID int64) error {
return transport.service.AuthorizeQRSession(sessionID, userID)
}
// CleanupQRSessions 清理过期的二维码会话。
func (transport accountLoginTransport) CleanupQRSessions(now time.Time) []string {
return transport.service.CleanupQRSessions(now)
}
// qrLoginTransport 以应用 Port 封装底层二维码会话协议和可选清理操作。
type qrLoginTransport struct {
// service 是组合根创建的二维码平台能力,不进入 Server 状态。
service adapter.QRLoginService
}
// GenerateQRCode 创建二维码平台会话。
func (transport qrLoginTransport) GenerateQRCode(ctx context.Context) (string, string, error) {
return transport.service.GenerateQRCode(ctx)
}
// GetSessionStatus 读取二维码平台会话状态。
func (transport qrLoginTransport) GetSessionStatus(sessionID string) map[string]any {
return transport.service.GetSessionStatus(sessionID)
}
// CompleteVerification 完成二维码平台的风控验证。
func (transport qrLoginTransport) CompleteVerification(ctx context.Context, sessionID string) (string, string, error) {
return transport.service.CompleteVerification(ctx, sessionID)
}
// DeleteSession 尽力释放终态或过期的二维码平台会话。
func (transport qrLoginTransport) DeleteSession(sessionID string) {
// cleaner、ok 分别是可选会话清理能力及其实现存在标记。
if cleaner, ok := transport.service.(interface{ DeleteSession(string) }); ok {
cleaner.DeleteSession(sessionID)
}
}
// sessionRecoveryTransport 将 adapter 中的平台错误分类限制在组合层,并向 Server 暴露恢复用例。
type sessionRecoveryTransport struct {
// handler 是组合根创建的脱敏会话恢复回调。
handler adapter.SessionRecoveryHandler
}
// ordersTransport 将应用层订单服务集合投影为 HTTP transport 消费的扁平 Port。
// 它只转发用例调用,不承担 HTTP 错误映射或业务规则。
type ordersTransport struct {
// services 是组合根已经验证完整性的订单应用服务集合。
services *orderapp.ServiceSet
}
// RefreshSingle 转发单订单刷新用例。
func (transport ordersTransport) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderapp.SingleRefreshResult, error) {
return transport.services.Refresh.RefreshSingle(ctx, userID, orderID)
}
// Refresh 转发批量订单刷新用例。
func (transport ordersTransport) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderapp.RefreshResult, error) {
return transport.services.Refresh.Refresh(ctx, userID, cookieID, status)
}
// List 转发订单列表查询用例。
func (transport ordersTransport) List(ctx context.Context, query orderapp.ListQuery) (orderapp.ListResult, error) {
return transport.services.List.List(ctx, query)
}
// Get 转发订单详情查询用例。
func (transport ordersTransport) Get(ctx context.Context, userID int64, orderID string) (*orderapp.Order, error) {
return transport.services.Detail.Get(ctx, userID, orderID)
}
// GetView 转发订单详情视图查询用例。
func (transport ordersTransport) GetView(ctx context.Context, userID int64, orderID string) (orderapp.DetailResult, error) {
return transport.services.Detail.GetView(ctx, userID, orderID)
}
// Delete 转发订单逻辑删除用例。
func (transport ordersTransport) Delete(ctx context.Context, userID int64, orderID string) error {
return transport.services.Delete.Delete(ctx, userID, orderID)
}
// Update 转发订单更新用例。
func (transport ordersTransport) Update(ctx context.Context, userID int64, orderID string, request orderapp.UpdateRequest) error {
return transport.services.Update.Update(ctx, userID, orderID, request)
}
// Import 转发订单导入用例。
func (transport ordersTransport) Import(ctx context.Context, userID int64, inputs []orderapp.ImportOrder) (orderapp.ImportResult, error) {
return transport.services.Import.Import(ctx, userID, inputs)
}
// ManualShip 转发订单手动发货用例。
func (transport ordersTransport) ManualShip(ctx context.Context, request orderapp.ManualShipRequest) (orderapp.ManualShipResult, error) {
return transport.services.ManualShip.ManualShip(ctx, request)
}
// Recover 对确认会话失效的平台错误启动账号恢复。
func (transport sessionRecoveryTransport) Recover(ctx context.Context, accountID string, err error) bool {
return transport.handler != nil && transport.handler(ctx, accountID, err)
}
// HTTPDependencies 是组合根创建 Server 所需的非业务 transport 基础依赖。
type HTTPDependencies struct {
// Auth 是会话认证服务。
Auth *auth.Service
// WebDir 是静态前端资源目录。
WebDir string
// Addr 是已经由 cmd 配置解析的 HTTP 监听地址。
Addr string
// Logger 是不记录敏感凭证的结构化日志器。
Logger *slog.Logger
// DatabaseHealth 是健康检查使用的窄数据库探测 Port。
DatabaseHealth server.DatabaseHealthPort
}
// ServerDependencies 将组合层服务投影为 HTTP Server 需要的不可变最小 Port 快照。
func ServerDependencies(services *composition.Services, base HTTPDependencies, sessionRecovery adapter.SessionRecoveryHandler) (server.Dependencies, error) {
if services == nil {
return server.Dependencies{}, fmt.Errorf("组合层账号登录服务未初始化")
}
// ports 是组合层将具体服务投影出的最小 HTTP transport Port 集合。
ports := services.TransportPorts()
if ports.AccountLogin == nil || ports.QRLogin == nil {
return server.Dependencies{}, fmt.Errorf("组合层 transport Port 未初始化")
}
return server.Dependencies{
Auth: base.Auth, WebDir: base.WebDir, Addr: base.Addr, Logger: base.Logger, DatabaseHealth: base.DatabaseHealth,
Applications: server.NewApplicationPorts(server.ApplicationPortsInput{
Orders: ordersTransport{services: ports.Orders}, OrderRefreshJobs: ports.OrderRefreshJobs,
ItemSinglePublish: ports.ItemSinglePublish, ItemBatchPreview: ports.ItemBatchPreview,
ItemBatchManagement: ports.ItemBatchManagement, ItemCategoryRecommendation: ports.ItemCategoryRecommendation,
ItemBatchPreviewPersistence: ports.ItemBatchPreviewPersistence, ItemBatchLocalPublish: ports.ItemBatchLocalPublish,
ItemSync: ports.ItemSync, ItemCatalog: ports.ItemCatalog, ItemCatalogMutation: ports.ItemCatalogMutation,
AccountLogin: accountLoginTransport{service: ports.AccountLogin},
QRLogin: qrLoginTransport{service: ports.QRLogin},
SessionRecovery: sessionRecoveryTransport{handler: sessionRecovery},
PlatformCredentials: ports.PlatformCredentials, Authentication: ports.Authentication, LoginAudit: ports.LoginAudit,
PasswordLogin: ports.PasswordLogin, AccountDelete: ports.AccountDelete, AccountProfile: ports.AccountProfile,
AccountLongLogin: ports.AccountLongLogin, AccountSettings: ports.AccountSettings, AccountRuntime: ports.AccountRuntime,
AccountSummaries: ports.AccountSummaries, AccountTasks: ports.AccountTasks, Chat: ports.Chat,
UncertainNotifications: ports.UncertainNotifications, NotificationChannels: ports.NotificationChannels,
Analytics: ports.Analytics, AutomationIssues: ports.AutomationIssues, AutomationRules: ports.AutomationRules,
Cards: ports.Cards, PublishAutomationRules: ports.PublishAutomationRules, DefaultReplies: ports.DefaultReplies,
Keywords: ports.Keywords, Settings: ports.Settings, Admin: ports.Admin,
}),
}, nil
}
@@ -1,14 +0,0 @@
package server
import "testing"
// TestServerCookieWriterRejectsMissingRepository 验证 Server 缺少窄凭证端口时快速失败。
func TestServerCookieWriterRejectsMissingRepository(t *testing.T) {
// srv 模拟尚未完成账号应用服务装配的 Server。
srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}}
// sessionPort 保存缺少凭证仓储时的会话写回端口。
sessionPort := srv.platformCredentialSessionPort()
if sessionPort != nil {
t.Fatal("缺少凭证 Port 时 Server 不应暴露伪造的会话端口")
}
}
-152
View File
@@ -1,152 +0,0 @@
package server
import (
"context"
"errors"
"strings"
"time"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
)
// accountLoginService 是账号登录相关应用服务,负责凭证写入、登录审计、资料刷新和运行时重启编排。
type accountLoginService struct {
// cookieWriterFactory 按请求创建新增 Cookie 写入端口;明文只进入返回的短生命周期实例。
cookieWriterFactory func(string) accountapp.CookieWriter
// cookieUpdaterFactory 按请求创建既有 Cookie 更新端口;明文只进入返回的短生命周期实例。
cookieUpdaterFactory func(string) accountapp.CookieUpdater
// sessionPort 提供平台会话写回所需的最小凭证能力,不暴露完整账号仓储。
sessionPort accountapp.CredentialSessionPort
// createApplication 提供已迁移的手动 Cookie 登录应用用例。
createApplication *accountapp.LoginService
// qrApplication 提供扫码成功凭证持久化应用用例。
qrApplication *accountapp.QRLoginService
// qrSessions 持有扫码会话所有权和幂等结果,Server 只负责 HTTP 适配。
qrSessions *accountapp.QRLoginSessionRegistry
}
// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其生命周期适配器。
func newAccountLoginCreateApplication(lifecycle accountapp.LoginLifecyclePort) (*accountapp.LoginService, error) {
return accountapp.NewLoginService(lifecycle)
}
// accountLoginApplication 返回当前 Server 绑定的账号登录应用服务。
func (s *Server) accountLoginApplication() *accountLoginService {
return s.applicationServiceSet().accountLogin
}
// platformCredentialSessionPort 返回平台 Cookie 会话写回所需的最小应用端口。
// Server 不通过该端口读取账号或登录秘密;凭证锁仍由调用方在慢速平台 I/O 之外管理。
func (s *Server) platformCredentialSessionPort() accountapp.CredentialSessionPort {
if s == nil || s.accountLoginApplication() == nil {
return nil
}
return s.accountLoginApplication().sessionPort
}
// accountLoginInput 是新增账号登录凭证用例的业务输入。
type accountLoginInput struct {
// AccountID 是待创建的账号标识。
AccountID string
// Cookies 是平台登录 Cookie 字符串。
Cookies string
// UserID 是当前用户标识。
UserID int64
// LoginMethod 是账号登录方式。
LoginMethod string
}
// accountCookieUpdateInput 是更新账号登录凭证用例的业务输入。
type accountCookieUpdateInput struct {
// AccountID 是待更新的账号标识。
AccountID string
// Cookies 是新的平台登录 Cookie 字符串。
Cookies string
// UserID 是当前用户标识。
UserID int64
// LoginMethod 是可选的登录方式。
LoginMethod string
// ExpectedRevision 是客户端读取到的最近 Cookie 刷新时间,用于检测并发覆盖。
ExpectedRevision int64
}
// CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。
func (svc *accountLoginService) CreateCookie(ctx context.Context, input accountLoginInput) error {
if svc == nil || svc.createApplication == nil {
return errors.New("账号登录应用服务未初始化")
}
if svc.cookieWriterFactory == nil {
return errors.New("账号 Cookie 写入端口未初始化")
}
return svc.createApplication.CreateCookie(ctx, accountapp.CreateCookieInput{
AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod,
}, svc.cookieWriterFactory(input.Cookies))
}
// UpdateCookie 更新账号凭证并完成登录审计、资料刷新和运行时重启。
func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountCookieUpdateInput) error {
if svc == nil || svc.createApplication == nil {
return errors.New("账号登录应用服务未初始化")
}
if svc.cookieUpdaterFactory == nil {
return errors.New("账号 Cookie 更新端口未初始化")
}
return svc.createApplication.UpdateCookie(ctx, accountapp.UpdateCookieInput{
AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod, ExpectedRevision: input.ExpectedRevision,
}, svc.cookieUpdaterFactory(input.Cookies))
}
// PersistQRLoginSuccess 将 HTTP/平台 map 适配为纯应用 DTO,并复用会话级幂等锁。
func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
if svc == nil || svc.qrApplication == nil || svc.qrSessions == nil {
return qrLoginPersistence{}, errors.New("扫码登录应用服务未初始化")
}
// persisted 保存注册表执行凭证持久化后返回的非敏感幂等结果。
persisted, persistErr := svc.qrSessions.PersistOnce(sessionID, userID, func() (accountapp.QRLoginSessionPersistence, error) {
// cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。
cookies := qrString(result, "cookies")
// cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。
cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result)
// scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), adapter.AccountIDFromCookie(cookies)))
// input 保存转换后的纯应用扫码登录输入;Cookie 只交给凭证端口消费。
input := accountapp.QRLoginInput{UserID: userID, ScannedAccountID: scannedAccountID, TargetAccountID: targetAccountID, Cookies: cookies}
if snapshotComplete {
input.Snapshot = cookieSnapshot
}
// resultValue 保存应用服务返回的非敏感持久化结果。
resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input)
if persistErr != nil {
if errors.Is(persistErr, accountapp.ErrQRLoginIncomplete) {
return accountapp.QRLoginSessionPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
}
if errors.Is(persistErr, accountapp.ErrQRLoginAccountMismatch) {
return accountapp.QRLoginSessionPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
}
if errors.Is(persistErr, accountapp.ErrForbidden) {
return accountapp.QRLoginSessionPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
}
if errors.Is(persistErr, accountapp.ErrAlreadyExists) {
return accountapp.QRLoginSessionPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态")
}
return accountapp.QRLoginSessionPersistence{}, persistErr
}
return accountapp.QRLoginSessionPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, CreatedAt: time.Now().UTC()}, nil
})
if persistErr != nil {
if errors.Is(persistErr, accountapp.ErrQRLoginSessionForbidden) {
return qrLoginPersistence{}, errors.New("扫码会话不属于当前用户")
}
return qrLoginPersistence{}, persistErr
}
return qrLoginPersistence{AccountID: persisted.AccountID, IsNew: persisted.IsNew, UserID: persisted.UserID, CreatedAt: persisted.CreatedAt}, nil
}
// ValidateCookieInput 校验账号标识和 Cookie 输入,供 HTTP 适配层复用一致规则。
func (svc *accountLoginService) ValidateCookieInput(input accountLoginInput) error {
if strings.TrimSpace(input.AccountID) == "" || strings.TrimSpace(input.Cookies) == "" {
return errors.New("缺少账号 ID 或 Cookie")
}
return nil
}
@@ -1,31 +0,0 @@
package server
import (
"context"
"testing"
)
// TestAccountLoginServiceValidateCookieInput 验证账号登录输入的基础校验规则。
func TestAccountLoginServiceValidateCookieInput(t *testing.T) {
// service 使用空 Server 即可测试纯输入校验。
service := (&Server{}).accountLoginApplication()
// err 表示空账号输入的校验结果。
if err := service.ValidateCookieInput(accountLoginInput{AccountID: "", Cookies: "cookie"}); err == nil {
t.Fatal("空账号 ID 应该校验失败")
}
// err 表示有效账号输入的校验结果。
if err := service.ValidateCookieInput(accountLoginInput{AccountID: "acc1", Cookies: "cookie"}); err != nil {
t.Fatalf("有效账号登录输入不应失败: %v", err)
}
}
// TestAccountLoginServicePersistQRLoginRejectsIncompleteResult 验证扫码结果缺少凭证时不会写入账号。
func TestAccountLoginServicePersistQRLoginRejectsIncompleteResult(t *testing.T) {
// service 使用空 Server 即可在凭证校验前验证失败结果。
service := (&Server{}).accountLoginApplication()
// err 保存扫码结果校验错误。
_, err := service.PersistQRLoginSuccess(context.Background(), 1, "session", map[string]any{"status": "success"}, "")
if err == nil {
t.Fatal("缺少 cookies 或 unb 的扫码结果应该失败")
}
}
-4
View File
@@ -85,10 +85,6 @@ func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if s.automation == nil {
writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用")
return
}
if !s.ownsAccount(r, cid) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
+1 -1
View File
@@ -11,7 +11,7 @@ import (
)
// analyticsApplication 返回当前 Server 绑定的订单分析应用服务。
func (s *Server) analyticsApplication() *analyticsapp.Service {
func (s *Server) analyticsApplication() AnalyticsPort {
return s.applicationServiceSet().analytics
}
@@ -17,10 +17,10 @@ func TestAPIContractChatAutomationAndItemErrors(t *testing.T) {
// srv 是用于验证聊天、自动化和商品错误契约的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// srv.MTop 是返回缺少商品 ID 结果的测试平台客户端。
srv.MTop = &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
// 测试平台客户端返回缺少商品 ID 的发布结果。
setTestMTop(srv, &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return &mtop.PublishItemResult{Title: "测试商品"}, nil
}}
}})
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
+656
View File
@@ -0,0 +1,656 @@
package server
import (
"context"
"fmt"
"time"
accountapp "xianyu-go/internal/application/account"
adminapp "xianyu-go/internal/application/admin"
analyticsapp "xianyu-go/internal/application/analytics"
automationapp "xianyu-go/internal/application/automation"
cardsapp "xianyu-go/internal/application/cards"
chatapp "xianyu-go/internal/application/chat"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
itemapp "xianyu-go/internal/application/items"
keywordsapp "xianyu-go/internal/application/keywords"
notificationsapp "xianyu-go/internal/application/notifications"
orderapp "xianyu-go/internal/application/orders"
settingsapp "xianyu-go/internal/application/settings"
)
// AccountLoginResult 是账号登录持久化后可供 HTTP 响应使用的非敏感结果。
type AccountLoginResult struct {
// AccountID 是已创建或更新的账号标识。
AccountID string
// IsNew 表示本次是否创建了新账号。
IsNew bool
}
// AccountLoginPort 定义 Cookie 与二维码登录 transport 消费的最小用例能力。
type AccountLoginPort interface {
CreateCookie(context.Context, string, string, int64, string) error
UpdateCookie(context.Context, string, string, int64, string, int64) error
PersistQRLoginSuccess(context.Context, int64, string, map[string]any, string) (AccountLoginResult, error)
RegisterQRSession(string, int64, time.Time)
AuthorizeQRSession(string, int64) error
CleanupQRSessions(time.Time) []string
}
// QRLoginPort 定义二维码平台流程的用例 Port;HTTP 层不接触具体平台实现。
type QRLoginPort interface {
GenerateQRCode(context.Context) (string, string, error)
GetSessionStatus(string) map[string]any
CompleteVerification(context.Context, string) (string, string, error)
DeleteSession(string)
}
// SessionRecoveryPort 定义已确认平台会话失效后的恢复用例。
type SessionRecoveryPort interface {
Recover(context.Context, string, error) bool
}
// OrdersPort 定义订单 HTTP transport 实际消费的用例集合,避免持有应用层服务容器。
type OrdersPort interface {
RefreshSingle(context.Context, int64, string) (orderapp.SingleRefreshResult, error)
Refresh(context.Context, int64, string, string) (orderapp.RefreshResult, error)
List(context.Context, orderapp.ListQuery) (orderapp.ListResult, error)
Get(context.Context, int64, string) (*orderapp.Order, error)
GetView(context.Context, int64, string) (orderapp.DetailResult, error)
Delete(context.Context, int64, string) error
Update(context.Context, int64, string, orderapp.UpdateRequest) error
Import(context.Context, int64, []orderapp.ImportOrder) (orderapp.ImportResult, error)
ManualShip(context.Context, orderapp.ManualShipRequest) (orderapp.ManualShipResult, error)
}
// OrderRefreshJobsPort 定义订单刷新任务 HTTP 接口所需的最小能力。
type OrderRefreshJobsPort interface {
CreateAndStart(context.Context, context.Context, int64, string, string) (orderapp.RefreshJobStartResult, error)
GetJob(context.Context, int64, string) (*orderapp.RefreshJob, error)
CancelForUser(context.Context, int64, string) (orderapp.RefreshJobCancelResult, error)
}
// ItemSinglePublishPort 定义单商品发布用例。
type ItemSinglePublishPort interface {
PublishSingle(context.Context, itemapp.PublishInput) (itemapp.PublishOutcome, error)
}
// ItemBatchPreviewPort 定义批量发布预检所需能力。
type ItemBatchPreviewPort interface {
CookieOwned(context.Context, int64, string) (bool, error)
Preview(context.Context, itemapp.BatchPreviewInput) ([]itemapp.BatchPreviewRow, error)
}
// ItemBatchManagementPort 定义批量发布管理和清理能力。
type ItemBatchManagementPort interface {
StartBatch(context.Context, int64, string, time.Duration) (string, error)
ListBatches(context.Context, int64, int) ([]itemapp.BatchInfo, error)
GetBatch(context.Context, int64, string) (itemapp.BatchDetails, error)
CancelBatch(context.Context, int64, string) (string, error)
DeleteBatch(context.Context, int64, string) error
CleanupExpiredUploads(context.Context, time.Time, int) error
RetryFailedBatch(context.Context, int64, string, time.Duration) (string, error)
}
// ItemCategoryRecommendationPort 定义批量发布类目推荐能力。
type ItemCategoryRecommendationPort interface {
Recommend(context.Context, int64, string, string) (itemapp.BatchPreviewCategory, error)
}
// ItemBatchPreviewPersistencePort 定义批量预检结果保存能力。
type ItemBatchPreviewPersistencePort interface {
Persist(context.Context, itemapp.BatchPreviewPersistenceBatch, []itemapp.BatchPreviewRow) (itemapp.BatchPreviewPersistenceResult, error)
}
// ItemBatchLocalPublishPort 定义批量远端发布后的本地持久化和规则收口能力。
type ItemBatchLocalPublishPort interface {
Complete(context.Context, int64, itemapp.BatchRow, string, *itemapp.BatchPublishResult) error
EnsureAutomationRules(context.Context, int64, itemapp.BatchRow, *itemapp.BatchPublishResult) error
}
// ItemSyncPort 定义商品同步能力。
type ItemSyncPort interface {
SyncAll(context.Context, itemapp.SyncQuery) (itemapp.SyncAllResult, error)
SyncPage(context.Context, itemapp.SyncQuery) (itemapp.SyncPageResult, error)
}
// ItemCatalogPort 定义商品目录读取能力。
type ItemCatalogPort interface {
ListForUser(context.Context, int64, string) ([]itemapp.CatalogItem, error)
ListByCookie(context.Context, string) ([]itemapp.CatalogItem, error)
Get(context.Context, string, string) (itemapp.CatalogItem, error)
}
// ItemCatalogMutationPort 定义商品目录写入能力。
type ItemCatalogMutationPort interface {
Create(context.Context, string, itemapp.CatalogWriteInput) error
Update(context.Context, string, string, itemapp.CatalogPatchInput) error
Delete(context.Context, string, string) error
SetMultiSpec(context.Context, string, string, bool) error
SetMultiQuantity(context.Context, string, string, bool) error
}
// PlatformCredentialPort 定义平台凭证受控读取能力。
type PlatformCredentialPort interface {
LoadPlatformDetail(context.Context, string) (*accountapp.CredentialDetail, error)
ValidateOwned(context.Context, int64, string) (int64, error)
LoadOwnedValue(context.Context, int64, string) (string, error)
}
// AuthenticationPort 定义 HTTP 登录和管理员初始化能力。
type AuthenticationPort interface {
IsSystemInitialized(context.Context) (bool, error)
InitializeAdmin(context.Context, string, string) (bool, error)
UsernameByEmail(context.Context, string) (string, error)
Login(context.Context, string, string) (string, *accountapp.AuthUser, error)
VerifyPassword(context.Context, string, string) (accountapp.AuthUser, bool, error)
UpdatePassword(context.Context, string, string) (bool, error)
UpdateCredentials(context.Context, int64, string, string) error
}
// LoginAuditPort 定义账号登录成功后的审计能力。
type LoginAuditPort interface {
RecordSuccessfulLogin(context.Context, accountapp.SuccessfulLoginInput) error
}
// PasswordLoginPort 定义历史密码登录端点的关闭策略能力。
type PasswordLoginPort interface {
Start(context.Context, accountapp.PasswordLoginStartInput) error
Check(context.Context, accountapp.PasswordLoginSessionInput) error
Cancel(context.Context, accountapp.PasswordLoginSessionInput) error
}
// AccountDeletePort 定义账号删除能力。
type AccountDeletePort interface {
Delete(context.Context, int64, string) error
}
// AccountProfilePort 定义账号资料刷新能力。
type AccountProfilePort interface {
RefreshProfile(context.Context, int64, string) (accountapp.ProfileResult, error)
}
// AccountLongLoginPort 定义账号长登录查询和修改能力。
type AccountLongLoginPort interface {
Query(context.Context, int64, string) (accountapp.LongLoginResult, error)
Set(context.Context, int64, string, bool) (accountapp.LongLoginResult, error)
}
// AccountSettingsPort 定义账号设置和状态更新能力。
type AccountSettingsPort interface {
UpdateSettings(context.Context, accountapp.SettingsUpdateInput) (accountapp.SettingsResult, error)
UpdateLoginInfo(context.Context, accountapp.LoginInfoUpdateInput) error
SetStatus(context.Context, int64, string, bool) (accountapp.StatusResult, error)
SetAutoConfirm(context.Context, int64, string, bool) (accountapp.SettingsResult, error)
SetRemark(context.Context, int64, string, string) (accountapp.SettingsResult, error)
SetPause(context.Context, int64, string, int) (accountapp.SettingsResult, error)
GetPause(context.Context, int64, string) (accountapp.PauseState, error)
}
// AccountRuntimePort 定义账号运行时状态与 Cookie 同步能力。
type AccountRuntimePort interface {
UpdateCookie(context.Context, string, string) error
RuntimeStatuses(context.Context) (map[string]accountapp.RuntimeStatus, error)
Restart(context.Context, string) error
RecoverExpiredCredential(context.Context, string) bool
}
// AccountSummaryPort 定义账号摘要、归属和管理员视图能力。
type AccountSummaryPort interface {
ListOwnedIDs(context.Context, int64) ([]string, error)
ListSummaries(context.Context, int64) ([]accountapp.AccountSummary, error)
GetOwnedSummary(context.Context, int64, string) (accountapp.AccountSummary, error)
ExistsOwned(context.Context, int64, string) (bool, error)
StatusOwned(context.Context, int64, string) (bool, error)
RequireOwnership(context.Context, int64, string) error
ListAdminSummaries(context.Context) ([]accountapp.AdminAccountSummary, error)
}
// AccountTasksPort 定义账号自动化任务配置和执行能力。
type AccountTasksPort interface {
GetSettings(context.Context, string) (automationapp.AccountTaskSettings, error)
UpdateSettings(context.Context, automationapp.AccountTaskSettings) (automationapp.AccountTaskSettings, error)
ListRuns(context.Context, string, int) ([]automationapp.AccountTaskRun, error)
Run(context.Context, string, string) (automationapp.TaskSummary, error)
}
// ChatPort 定义聊天 HTTP 端点消费的会话、消息和平台投递能力。
type ChatPort interface {
SendingAvailable() bool
ImageUploadAvailable() bool
Subscribe(context.Context, int64) (<-chan chatapp.Event, func(), error)
RefreshConversations(context.Context, string, int64, int) (chatapp.ConversationPage, error)
RefreshHistory(context.Context, string, string, int64, int, chatapp.Session) (chatapp.HistoryPage, error)
SendText(context.Context, chatapp.OutgoingInput) (*chatapp.Message, error)
SendImage(context.Context, chatapp.ImageInput) (*chatapp.Message, error)
ListStoredMessages(context.Context, int64, string, string, int64, int) (chatapp.Page, error)
ListSessions(context.Context, int64, string, int) ([]chatapp.Session, error)
FindSession(context.Context, int64, string, string) (chatapp.Session, error)
ResolveReadMessageID(context.Context, string, string, string) string
CleanupEmptySessions(context.Context, string) error
OwnsAccount(context.Context, int64, string) (bool, error)
MarkRead(context.Context, int64, string, string) error
ReportPlatformRead(context.Context, string, string, []map[string]any) error
ResolveSessionIdentity(context.Context, chatapp.Session) (chatapp.Session, error)
RefreshSessionIdentities(context.Context, string, []chatapp.Session) ([]chatapp.Session, error)
}
// UncertainNotificationsPort 定义通知不确定状态的查询能力。
type UncertainNotificationsPort interface {
ListForUser(context.Context, int64, int) ([]notificationsapp.UncertainSummary, int, error)
ListForAdmin(context.Context, int) ([]notificationsapp.UncertainSummary, int, error)
}
// NotificationChannelsPort 定义通知渠道和账号绑定的管理能力。
type NotificationChannelsPort interface {
ListChannels(context.Context, int64) ([]notificationsapp.ChannelSummary, error)
CreateChannel(context.Context, int64, notificationsapp.ChannelInput) (int64, error)
UpdateChannel(context.Context, int64, int64, notificationsapp.ChannelPatch) error
DeleteChannel(context.Context, int64, int64) error
TestChannel(context.Context, int64, int64, time.Time) error
ListBindings(context.Context, int64) ([]notificationsapp.BindingSummary, error)
GetBindingIDs(context.Context, int64, string) ([]int64, error)
SetBindings(context.Context, int64, string, []int64) error
SetSingleBinding(context.Context, int64, string, int64, bool) error
DeleteBinding(context.Context, int64, int64) error
DeleteAccountBindings(context.Context, int64, string) error
}
// AnalyticsPort 定义仪表盘和订单分析能力。
type AnalyticsPort interface {
DashboardStats(context.Context, int64) (analyticsapp.DashboardStats, error)
OrderAnalytics(context.Context, analyticsapp.Query) (analyticsapp.OrderAnalytics, error)
ValidOrders(context.Context, analyticsapp.Query, int, int) (analyticsapp.ValidOrders, error)
}
// AutomationIssuesPort 定义自动化异常的查询和人工处理能力。
type AutomationIssuesPort interface {
ListIssues(context.Context, int64) ([]automationapp.RunIssue, []automationapp.DeferredIssue, error)
ResolveRunIssue(context.Context, int64, int64, string) error
ResolveDeferredIssue(context.Context, int64, int64, string) error
}
// AutomationRulesPort 定义自动化规则的查询、规范化和写入能力。
type AutomationRulesPort interface {
ListForUser(context.Context, int64) ([]automationapp.Rule, error)
ListPageForUser(context.Context, automationapp.RuleFilter) ([]automationapp.Rule, int, error)
CountByTriggerForUser(context.Context, automationapp.RuleFilter) (map[string]int, error)
Normalize(context.Context, int64, automationapp.RuleDraft) (automationapp.RuleInput, error)
Create(context.Context, automationapp.RuleInput) (int64, error)
Update(context.Context, int64, int64, automationapp.RuleInput) error
Delete(context.Context, int64, int64) error
}
// PublishAutomationRulesPort 定义发布后自动化规则的幂等准备能力。
type PublishAutomationRulesPort interface {
Ensure(context.Context, automationapp.RuleInput) error
}
// CardsPort 定义卡券库存 CRUD 与归属校验能力。
type CardsPort interface {
List(context.Context, int64) ([]cardsapp.Card, error)
Get(context.Context, int64, int64) (cardsapp.Card, error)
ExistsOwned(context.Context, int64, int64) (bool, error)
Create(context.Context, int64, cardsapp.Draft) (int64, error)
Update(context.Context, int64, int64, cardsapp.Draft) error
Delete(context.Context, int64, int64) error
AppendData(context.Context, int64, int64, string) (int, error)
}
// DefaultRepliesPort 定义默认回复配置能力。
type DefaultRepliesPort interface {
Get(context.Context, int64, string) (defaultreplyapp.Reply, error)
Upsert(context.Context, int64, string, defaultreplyapp.Reply) error
List(context.Context, int64) ([]defaultreplyapp.Summary, error)
Delete(context.Context, int64, string) error
ClearRecords(context.Context, int64, string) error
}
// KeywordsPort 定义关键词与指定商品回复能力。
type KeywordsPort interface {
List(context.Context, int64, string) ([]keywordsapp.Keyword, error)
Add(context.Context, int64, string, keywordsapp.Draft) (int64, error)
Replace(context.Context, int64, string, []keywordsapp.Draft) error
Update(context.Context, int64, string, int64, keywordsapp.Draft) error
DeleteByID(context.Context, int64, string, int64) error
DeleteByIndex(context.Context, int64, string, int) error
ListItemReplies(context.Context, int64) ([]keywordsapp.ItemReply, error)
GetItemReply(context.Context, int64, string, string) (keywordsapp.ItemReply, error)
SetItemReply(context.Context, int64, string, string, string) error
DeleteItemReply(context.Context, int64, string, string) error
}
// SettingsPort 定义系统、用户和账号 AI 设置能力。
type SettingsPort interface {
IsSensitiveSettingKey(string) bool
PublicSystem(context.Context) (map[string]string, error)
GetSystem(context.Context, int64) (map[string]string, error)
ApplySystemChanges(context.Context, int64, map[string]string, map[string]settingsapp.SecretChange) error
SetSystem(context.Context, int64, string, string, string) error
ListUser(context.Context, int64) (map[string]string, error)
GetUser(context.Context, int64, string) (string, error)
SetUser(context.Context, int64, string, string) error
ListAIReply(context.Context, int64) ([]settingsapp.AIReplySettings, error)
GetAIReply(context.Context, int64, string) (settingsapp.AIReplySettings, error)
UpsertAIReply(context.Context, int64, string, settingsapp.AIReplySettings) error
ListAIModels(context.Context, int64, string, string) ([]string, error)
}
// AdminPort 定义管理员用户与统计能力。
type AdminPort interface {
ListUsers(context.Context) ([]adminapp.UserSummary, error)
DeleteUser(context.Context, int64, int64) error
Stats(context.Context) (adminapp.Stats, error)
}
// ApplicationPorts 是构造期注入 HTTP transport 的不可变应用 Port 集合。
// 它不包含 adapter、数据库、平台 client、账号 Manager 或 worker 生命周期拥有权。
type ApplicationPorts struct {
// orders 是订单应用服务集合,HTTP 仅做 DTO 转换和错误映射。
orders OrdersPort
// orderRefreshJobs 是订单刷新任务用例。
orderRefreshJobs OrderRefreshJobsPort
// itemSinglePublish 是单商品发布用例。
itemSinglePublish ItemSinglePublishPort
// itemBatchPreview 是批量发布预检用例。
itemBatchPreview ItemBatchPreviewPort
// itemBatchManagement 是批量发布查询、取消和重试用例。
itemBatchManagement ItemBatchManagementPort
// itemCategoryRecommendation 是发布类目推荐用例。
itemCategoryRecommendation ItemCategoryRecommendationPort
// itemBatchPreviewPersistence 是批量预检结果保存用例。
itemBatchPreviewPersistence ItemBatchPreviewPersistencePort
// itemBatchLocalPublish 是远端发布成功后的本地收口用例。
itemBatchLocalPublish ItemBatchLocalPublishPort
// itemSync 是商品同步用例。
itemSync ItemSyncPort
// itemCatalog 是商品目录读取用例。
itemCatalog ItemCatalogPort
// itemCatalogMutation 是商品目录写入用例。
itemCatalogMutation ItemCatalogMutationPort
// accountLogin 是 Cookie 与二维码登录用例 Port。
accountLogin AccountLoginPort
// qrLogin 是二维码平台流程用例 Port。
qrLogin QRLoginPort
// sessionRecovery 是平台会话恢复用例 Port。
sessionRecovery SessionRecoveryPort
// platformCredentials 是受控的平台凭证读取用例。
platformCredentials PlatformCredentialPort
// authentication 是用户登录认证用例。
authentication AuthenticationPort
// loginAudit 是登录审计用例。
loginAudit LoginAuditPort
// passwordLogin 是密码登录策略用例。
passwordLogin PasswordLoginPort
// accountDelete 是账号删除用例。
accountDelete AccountDeletePort
// accountProfile 是账号资料刷新用例。
accountProfile AccountProfilePort
// accountLongLogin 是账号长登录设置用例。
accountLongLogin AccountLongLoginPort
// accountSettings 是账号设置用例。
accountSettings AccountSettingsPort
// accountRuntime 是账号运行时状态用例。
accountRuntime AccountRuntimePort
// accountSummaries 是账号摘要用例。
accountSummaries AccountSummaryPort
// accountTasks 是账号自动化任务用例。
accountTasks AccountTasksPort
// chat 是聊天应用用例。
chat ChatPort
// uncertainNotifications 是通知不确定状态用例。
uncertainNotifications UncertainNotificationsPort
// notificationChannels 是通知渠道用例。
notificationChannels NotificationChannelsPort
// analytics 是订单分析用例。
analytics AnalyticsPort
// automationIssues 是自动化异常用例。
automationIssues AutomationIssuesPort
// automationRules 是自动化规则用例。
automationRules AutomationRulesPort
// cards 是卡券库存用例。
cards CardsPort
// publishAutomationRules 是发布后自动化规则用例。
publishAutomationRules PublishAutomationRulesPort
// defaultReplies 是默认回复用例。
defaultReplies DefaultRepliesPort
// keywords 是关键词回复用例。
keywords KeywordsPort
// settings 是系统设置用例。
settings SettingsPort
// admin 是管理员用户与统计用例。
admin AdminPort
}
// ApplicationPortsInput 是组合根向 HTTP transport 交付的完整应用 Port 快照。
// 所有字段必须在进程启动期构造完成,Server 不会在请求期回填或替换它们。
type ApplicationPortsInput struct {
Orders OrdersPort
OrderRefreshJobs OrderRefreshJobsPort
ItemSinglePublish ItemSinglePublishPort
ItemBatchPreview ItemBatchPreviewPort
ItemBatchManagement ItemBatchManagementPort
ItemCategoryRecommendation ItemCategoryRecommendationPort
ItemBatchPreviewPersistence ItemBatchPreviewPersistencePort
ItemBatchLocalPublish ItemBatchLocalPublishPort
ItemSync ItemSyncPort
ItemCatalog ItemCatalogPort
ItemCatalogMutation ItemCatalogMutationPort
AccountLogin AccountLoginPort
QRLogin QRLoginPort
SessionRecovery SessionRecoveryPort
PlatformCredentials PlatformCredentialPort
Authentication AuthenticationPort
LoginAudit LoginAuditPort
PasswordLogin PasswordLoginPort
AccountDelete AccountDeletePort
AccountProfile AccountProfilePort
AccountLongLogin AccountLongLoginPort
AccountSettings AccountSettingsPort
AccountRuntime AccountRuntimePort
AccountSummaries AccountSummaryPort
AccountTasks AccountTasksPort
Chat ChatPort
UncertainNotifications UncertainNotificationsPort
NotificationChannels NotificationChannelsPort
Analytics AnalyticsPort
AutomationIssues AutomationIssuesPort
AutomationRules AutomationRulesPort
Cards CardsPort
PublishAutomationRules PublishAutomationRulesPort
DefaultReplies DefaultRepliesPort
Keywords KeywordsPort
Settings SettingsPort
Admin AdminPort
}
// NewApplicationPorts 将组合根已经验证的用例依赖冻结为 Server 私有快照。
func NewApplicationPorts(input ApplicationPortsInput) *ApplicationPorts {
return &ApplicationPorts{
orders: input.Orders, orderRefreshJobs: input.OrderRefreshJobs,
itemSinglePublish: input.ItemSinglePublish, itemBatchPreview: input.ItemBatchPreview,
itemBatchManagement: input.ItemBatchManagement, itemCategoryRecommendation: input.ItemCategoryRecommendation,
itemBatchPreviewPersistence: input.ItemBatchPreviewPersistence, itemBatchLocalPublish: input.ItemBatchLocalPublish,
itemSync: input.ItemSync, itemCatalog: input.ItemCatalog, itemCatalogMutation: input.ItemCatalogMutation,
accountLogin: input.AccountLogin, qrLogin: input.QRLogin, sessionRecovery: input.SessionRecovery,
platformCredentials: input.PlatformCredentials, authentication: input.Authentication, loginAudit: input.LoginAudit,
passwordLogin: input.PasswordLogin, accountDelete: input.AccountDelete, accountProfile: input.AccountProfile,
accountLongLogin: input.AccountLongLogin, accountSettings: input.AccountSettings, accountRuntime: input.AccountRuntime,
accountSummaries: input.AccountSummaries, accountTasks: input.AccountTasks, chat: input.Chat,
uncertainNotifications: input.UncertainNotifications, notificationChannels: input.NotificationChannels,
analytics: input.Analytics, automationIssues: input.AutomationIssues, automationRules: input.AutomationRules,
cards: input.Cards, publishAutomationRules: input.PublishAutomationRules, defaultReplies: input.DefaultReplies,
keywords: input.Keywords, settings: input.Settings, admin: input.Admin,
}
}
// validate 确认组合根已经为 HTTP 路由绑定全部必需应用 Port。
// 此处只校验启动期容器完整性,不在请求期创建、替换或查找任何依赖。
func (ports *ApplicationPorts) validate() error {
if ports == nil {
return fmt.Errorf("应用 Port 容器不能为空")
}
// required 保存每个 HTTP 路由组启动前必须可用的应用 Port。
required := []struct {
// name 是缺失依赖时返回的稳定诊断名称,不包含实现类型或敏感数据。
name string
// port 是构造期由 composition 注入的消费者接口。
port any
}{
{"orders", ports.orders}, {"order_refresh_jobs", ports.orderRefreshJobs}, {"item_single_publish", ports.itemSinglePublish},
{"item_batch_preview", ports.itemBatchPreview}, {"item_batch_management", ports.itemBatchManagement}, {"item_category_recommendation", ports.itemCategoryRecommendation},
{"item_batch_preview_persistence", ports.itemBatchPreviewPersistence}, {"item_batch_local_publish", ports.itemBatchLocalPublish}, {"item_sync", ports.itemSync},
{"item_catalog", ports.itemCatalog}, {"item_catalog_mutation", ports.itemCatalogMutation}, {"account_login", ports.accountLogin},
{"qr_login", ports.qrLogin}, {"session_recovery", ports.sessionRecovery}, {"platform_credentials", ports.platformCredentials},
{"authentication", ports.authentication}, {"login_audit", ports.loginAudit}, {"password_login", ports.passwordLogin},
{"account_delete", ports.accountDelete}, {"account_profile", ports.accountProfile}, {"account_long_login", ports.accountLongLogin},
{"account_settings", ports.accountSettings}, {"account_runtime", ports.accountRuntime}, {"account_summaries", ports.accountSummaries},
{"account_tasks", ports.accountTasks}, {"chat", ports.chat}, {"uncertain_notifications", ports.uncertainNotifications},
{"notification_channels", ports.notificationChannels}, {"analytics", ports.analytics}, {"automation_issues", ports.automationIssues},
{"automation_rules", ports.automationRules}, {"cards", ports.cards}, {"publish_automation_rules", ports.publishAutomationRules},
{"default_replies", ports.defaultReplies}, {"keywords", ports.keywords}, {"settings", ports.settings}, {"admin", ports.admin},
}
// requiredPort 是当前必须在 Server 构造前绑定的应用 Port 名称。
for _, requiredPort := range required {
if requiredPort.port == nil {
return fmt.Errorf("应用 Port %s 未初始化", requiredPort.name)
}
}
return nil
}
// emptyApplicationPorts 为零值 Server 的防御性读取提供不可变空快照。
var emptyApplicationPorts = &ApplicationPorts{}
// accountLoginApplication 返回 Cookie 与二维码登录用例 Port。
func (server *Server) accountLoginApplication() AccountLoginPort {
return server.applicationServiceSet().accountLogin
}
// qrLoginApplication 返回二维码平台流程用例 Port。
func (server *Server) qrLoginApplication() QRLoginPort {
return server.applicationServiceSet().qrLogin
}
// accountRuntimeApplication 返回账号运行时状态用例。
func (server *Server) accountRuntimeApplication() AccountRuntimePort {
return server.applicationServiceSet().accountRuntime
}
// orderRefreshJobsApplication 返回订单刷新任务用例。
func (server *Server) orderRefreshJobsApplication() OrderRefreshJobsPort {
return server.applicationServiceSet().orderRefreshJobs
}
// itemCatalogApplication 返回商品目录读取用例。
func (server *Server) itemCatalogApplication() ItemCatalogPort {
return server.applicationServiceSet().itemCatalog
}
// itemSinglePublishApplication 返回单商品发布用例。
func (server *Server) itemSinglePublishApplication() ItemSinglePublishPort {
return server.applicationServiceSet().itemSinglePublish
}
// itemCatalogMutationApplication 返回商品目录写入用例。
func (server *Server) itemCatalogMutationApplication() ItemCatalogMutationPort {
return server.applicationServiceSet().itemCatalogMutation
}
// itemSyncApplication 返回商品同步用例。
func (server *Server) itemSyncApplication() ItemSyncPort {
return server.applicationServiceSet().itemSync
}
// cardsApplication 返回卡券库存用例。
func (server *Server) cardsApplication() CardsPort {
return server.applicationServiceSet().cards
}
// accountTaskApplication 返回账号自动化任务用例。
func (server *Server) accountTaskApplication() AccountTasksPort {
return server.applicationServiceSet().accountTasks
}
// automationIssuesApplication 返回自动化异常用例。
func (server *Server) automationIssuesApplication() AutomationIssuesPort {
return server.applicationServiceSet().automationIssues
}
// automationRulesApplication 返回自动化规则用例。
func (server *Server) automationRulesApplication() AutomationRulesPort {
return server.applicationServiceSet().automationRules
}
// itemBatchPreviewApplication 返回批量发布预检用例。
func (server *Server) itemBatchPreviewApplication() ItemBatchPreviewPort {
return server.applicationServiceSet().itemBatchPreview
}
// itemBatchManagementApplication 返回批量发布管理用例。
func (server *Server) itemBatchManagementApplication() ItemBatchManagementPort {
return server.applicationServiceSet().itemBatchManagement
}
// itemCategoryRecommendationApplication 返回类目推荐用例。
func (server *Server) itemCategoryRecommendationApplication() ItemCategoryRecommendationPort {
return server.applicationServiceSet().itemCategoryRecommendation
}
// itemBatchPreviewPersistenceApplication 返回批量预检保存用例。
func (server *Server) itemBatchPreviewPersistenceApplication() ItemBatchPreviewPersistencePort {
return server.applicationServiceSet().itemBatchPreviewPersistence
}
// accountProfileApplication 返回账号资料刷新用例。
func (server *Server) accountProfileApplication() AccountProfilePort {
return server.applicationServiceSet().accountProfile
}
// accountLongLoginApplication 返回账号长登录用例。
func (server *Server) accountLongLoginApplication() AccountLongLoginPort {
return server.applicationServiceSet().accountLongLogin
}
// accountSettingsApplication 返回账号设置用例。
func (server *Server) accountSettingsApplication() AccountSettingsPort {
return server.applicationServiceSet().accountSettings
}
// platformCredentialApplication 返回受控的平台凭证读取用例。
func (server *Server) platformCredentialApplication() PlatformCredentialPort {
return server.applicationServiceSet().platformCredentials
}
// authenticationApplication 返回用户登录认证用例。
func (server *Server) authenticationApplication() AuthenticationPort {
return server.applicationServiceSet().authentication
}
// accountSummaryApplication 返回账号摘要用例。
func (server *Server) accountSummaryApplication() AccountSummaryPort {
return server.applicationServiceSet().accountSummaries
}
// accountDeleteApplication 返回账号删除用例。
func (server *Server) accountDeleteApplication() AccountDeletePort {
return server.applicationServiceSet().accountDelete
}
// loginAuditApplication 返回登录审计用例。
func (server *Server) loginAuditApplication() LoginAuditPort {
return server.applicationServiceSet().loginAudit
}
// settingsApplication 返回系统设置用例。
func (server *Server) settingsApplication() SettingsPort {
return server.applicationServiceSet().settings
}
// applicationServiceSet 返回构造期注入的不可变 Port 快照;零值 Server 不会隐式装配业务服务。
func (server *Server) applicationServiceSet() *ApplicationPorts {
if server == nil || server.applications == nil {
return emptyApplicationPorts
}
return server.applications
}
-571
View File
@@ -1,571 +0,0 @@
package server
import (
"context"
"fmt"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
adminapp "xianyu-go/internal/application/admin"
analyticsapp "xianyu-go/internal/application/analytics"
automationapp "xianyu-go/internal/application/automation"
cardsapp "xianyu-go/internal/application/cards"
chatapp "xianyu-go/internal/application/chat"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
itemapp "xianyu-go/internal/application/items"
keywordsapp "xianyu-go/internal/application/keywords"
lifecycleapp "xianyu-go/internal/application/lifecycle"
notificationsapp "xianyu-go/internal/application/notifications"
orderapp "xianyu-go/internal/application/orders"
settingsapp "xianyu-go/internal/application/settings"
)
// applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。
type ApplicationServices struct {
// platformCredentials 负责按需读取平台凭证窄视图并执行归属复核。
platformCredentials *accountapp.PlatformCredentialService
// orders 是订单 HTTP 适配器;业务服务集合由应用层统一构造。
orders *orderHTTPAdapter
// orderRefreshJobs 是订单刷新任务创建、取消、恢复和 worker 生命周期应用服务。
orderRefreshJobs *orderapp.RefreshJobService
// orderReconciliationRecovery 是订单补偿扫描器的应用层生命周期协调器。
orderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
// itemSinglePublish 是仅负责单商品发布用例的纯应用服务。
itemSinglePublish *itemapp.Service
// itemBatchCoordinator 是商品批量发布 worker、恢复扫描和关闭等待的生命周期拥有者。
itemBatchCoordinator *itemapp.BatchWorkerCoordinator
// itemBatchPreview 是商品批量发布表格预检应用服务。
itemBatchPreview *itemapp.BatchPreviewService
// itemBatchManagement 是商品批次查询、取消和重试应用服务。
itemBatchManagement *itemapp.BatchManagementService
// itemCategoryRecommendation 是商品类目推荐应用服务。
itemCategoryRecommendation *itemapp.CategoryRecommendationService
// itemBatchPreviewPersistence 是预检结果持久化应用服务。
itemBatchPreviewPersistence *itemapp.BatchPreviewPersistenceService
// itemBatchLocalPublish 是远端发布成功后的本地商品与规则收口服务。
itemBatchLocalPublish *itemapp.BatchLocalPublishService
// itemSync 是商品全量和分页同步应用服务。
itemSync *itemapp.SyncService
// itemCatalog 是商品列表和详情读取应用服务。
itemCatalog *itemapp.CatalogService
// itemCatalogMutation 是商品创建、更新、删除和交付开关应用服务。
itemCatalogMutation *itemapp.CatalogMutationService
// accountLogin 是账号登录应用服务。
accountLogin *accountLoginService
// authentication 是用户会话、密码校验和登录凭据应用服务。
authentication *accountapp.AuthenticationService
// loginAudit 是登录成功审计应用服务,负责方式归一化和账号启用编排。
loginAudit *accountapp.LoginAuditService
// passwordLogin 是密码登录策略应用服务;当前只返回关闭策略,不保存登录秘密或会话。
passwordLogin *accountapp.PasswordLoginService
// accountDelete 是账号删除应用服务,负责停止 fencing 和归属复核后的持久化删除。
accountDelete *accountapp.DeleteService
// accountProfile 是账号资料刷新应用服务。
accountProfile *accountapp.ProfileService
// accountLongLogin 是账号长登录设置应用服务。
accountLongLogin *accountapp.LongLoginService
// accountSettings 是账号设置、登录信息、启停和暂停应用服务。
accountSettings *accountapp.SettingsService
// accountRuntime 是账号凭证写回后的运行时同步与状态快照应用服务。
accountRuntime *accountapp.RuntimeService
// accountSummaries 是账号摘要、所有权和管理员账号列表应用服务。
accountSummaries *accountapp.SummaryService
// accountTasks 是账号任务设置、历史和手动执行应用服务。
accountTasks *automationapp.Service
// credentialWake 是凭证恢复后唤醒自动化任务的应用服务。
credentialWake *automationapp.CredentialWakeService
// chat 是聊天历史查询应用服务,负责用户归属和分页编排。
chat *chatapp.Service
// uncertainNotifications 是通知不确定状态运维查询应用服务。
uncertainNotifications *notificationsapp.Service
// notificationChannels 是通知渠道 CRUD 与账号绑定应用服务。
notificationChannels *notificationsapp.ChannelService
// analytics 是订单分析应用服务。
analytics *analyticsapp.Service
// automationIssues 是自动化异常查询与人工处理应用服务。
automationIssues *automationapp.IssueService
// automationRules 是自动化规则校验、分页和持久化应用服务。
automationRules *automationapp.RuleService
// cards 是卡券 CRUD、输入校验和所有权编排应用服务。
cards *cardsapp.Service
// publishAutomationRules 是批量发布成功后幂等准备自动化规则的应用服务。
publishAutomationRules *automationapp.PublishRuleService
// defaultReplies 是默认回复配置与投递记录应用服务。
defaultReplies *defaultreplyapp.Service
// keywords 是关键词规则与指定商品回复应用服务。
keywords *keywordsapp.Service
// settings 是系统、用户和账号 AI 设置应用服务。
settings *settingsapp.Service
// admin 是管理员用户管理与全局统计应用服务。
admin *adminapp.Service
}
// applicationServices 是旧测试和兼容访问器使用的内部别名;生产组合根应使用导出的集合类型注入。
type applicationServices = ApplicationServices
// emptyApplicationServices 是零值 Server 和隔离 handler 测试共享的只读空服务集合。
// 它不包含任何生产依赖,禁止写入;生产 Server 必须在 New 阶段注入完整集合。
var emptyApplicationServices = &applicationServices{accountLogin: &accountLoginService{}}
// LifecycleComponents 返回由组合根登记的应用 worker 生命周期组件。
// 组件只暴露 Start/Close 端口,启动顺序与进程取消责任由 cmd 的协调器拥有。
func (services *ApplicationServices) LifecycleComponents() []lifecycleapp.NamedComponent {
if services == nil {
return nil
}
// components 保存按应用依赖登记的 worker 生命周期组件。
components := make([]lifecycleapp.NamedComponent, 0, 3)
if services.orderRefreshJobs != nil {
// service 保存订单刷新恢复与 worker 生命周期应用服务。
service := services.orderRefreshJobs
components = append(components, lifecycleapp.NamedComponent{
Name: "order-refresh-recovery",
Component: lifecycleapp.FuncComponent{
StartFunc: service.StartRecovery,
CloseFunc: service.Close,
},
})
}
if services.itemBatchCoordinator != nil {
// coordinator 保存批量发布 worker 与恢复扫描生命周期协调器。
coordinator := services.itemBatchCoordinator
components = append(components, lifecycleapp.NamedComponent{
Name: "publish-batch-workers",
Component: lifecycleapp.FuncComponent{
StartFunc: coordinator.StartRecovery,
CloseFunc: coordinator.Close,
},
})
}
if services.orderReconciliationRecovery != nil {
// coordinator 保存订单补偿扫描生命周期协调器。
coordinator := services.orderReconciliationRecovery
components = append(components, lifecycleapp.NamedComponent{
Name: "order-reconciliation-recovery",
Component: lifecycleapp.FuncComponent{
StartFunc: coordinator.Start,
CloseFunc: coordinator.Close,
},
})
}
return components
}
// newApplicationServices 为指定 Server 装配全部应用服务实例,并把任何依赖构造错误交给上层启动流程处理。
func newApplicationServices(server *Server) (*applicationServices, error) {
// orderRepository 保存订单应用服务共享的基础设施适配器。
orderRepository := server.orderDependencies.NewOrderRepository()
// orderReconciliation 保存订单补偿写入应用 Port 的数据库适配器。
orderReconciliation := server.orderDependencies.NewOrderReconciliationRepository()
// orderRuntime 保存订单服务共享的运行时能力适配器。
orderRuntime := newServerOrderRuntime(server, orderReconciliation)
// orderServices 保存应用层统一构造的订单业务服务集合。
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.orderDependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize)
// orderRefreshRunner 是订单刷新后台 worker 与恢复扫描的生命周期拥有者。
orderRefreshRunner, orderRefreshRunnerErr := orderapp.NewRefreshJobRunner(
orderServices.RefreshJobs,
orderServices.Refresh,
orderapp.RefreshJobRunnerOptions{
OnWorkerError: func(jobID string, err error) {
if server.Logger != nil {
server.Logger.Warn("订单刷新后台任务结束", "job_id", jobID, "err", err)
}
},
OnRecoveryError: func(err error) {
if server.Logger != nil {
server.Logger.Warn("扫描订单刷新恢复任务失败", "err", err)
}
},
},
)
if orderRefreshRunnerErr != nil {
return nil, fmt.Errorf("构造订单刷新运行器失败: %w", orderRefreshRunnerErr)
}
// orderRefreshJobs 是订单刷新任务应用 facade,封装归属、租约和 worker 启动编排。
orderRefreshJobs, orderRefreshJobsErr := orderapp.NewRefreshJobService(
orderServices.RefreshJobs,
orderServices.Refresh,
orderRefreshRunner,
orderapp.RefreshJobServiceOptions{},
)
if orderRefreshJobsErr != nil {
return nil, fmt.Errorf("构造订单刷新应用服务失败: %w", orderRefreshJobsErr)
}
// accountProfile 保存账号资料刷新用例的构造结果。
// accountRepository 提供账号登录、资料摘要和删除共用的数据库适配器。
accountRepository := server.accountDependencies.NewAccountLoginRepository()
// platformCredentials 将账号凭证读取限制在消费者定义的只读应用端口。
platformCredentials, platformCredentialsErr := accountapp.NewPlatformCredentialService(accountRepository)
if platformCredentialsErr != nil {
return nil, fmt.Errorf("构造平台凭证服务失败: %w", platformCredentialsErr)
}
// cookieWriterFactory 将明文 Cookie 封装在 adapter 的请求范围实例中,Server 不持有凭证仓储。
cookieWriterFactory := func(cookies string) accountapp.CookieWriter {
return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, server.Logger)
}
// cookieUpdaterFactory 将既有账号的明文 Cookie 封装在 adapter 的请求范围实例中。
cookieUpdaterFactory := func(cookies string) accountapp.CookieUpdater {
return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, server.Logger)
}
// sessionRecovery 统一适配平台 Session 失效分类、诊断日志和账号运行时恢复。
sessionRecovery := server.sessionRecoveryCallback()
// accountProfile 由应用层服务编排平台资料刷新与非敏感摘要持久化。
accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, sessionRecovery, server.Logger))
if profileErr != nil {
return nil, fmt.Errorf("构造账号资料服务失败: %w", profileErr)
}
// accountLongLogin 由适配器承载平台调用、Cookie 快照合并和凭证写回。
accountLongLogin, longLoginErr := accountapp.NewLongLoginService(
accountRepository,
adapter.NewLongLoginAdapter(accountRepository, server.longLoginClient, server.updateRunningCookie, server.Logger),
)
if longLoginErr != nil {
return nil, fmt.Errorf("构造账号长登录服务失败: %w", longLoginErr)
}
// accountSettings 由独立适配器承载账号设置写入与敏感登录信息更新。
var settingsRuntime accountapp.SettingsRuntime
if server.Manager != nil {
settingsRuntime = server.Manager
}
// accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。
accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.accountDependencies.NewAccountSettingsRepository(), settingsRuntime)
if accountSettingsErr != nil {
return nil, fmt.Errorf("构造账号设置服务失败: %w", accountSettingsErr)
}
// accountSummaryRepository 保存普通用户与管理员共用的摘要查询适配器。
accountSummaryRepository := server.accountDependencies.NewAccountSummaryRepository()
// accountSummaries、accountSummariesErr 保存账号摘要应用服务及其装配错误。
accountSummaries, accountSummariesErr := accountapp.NewSummaryService(accountSummaryRepository, accountSummaryRepository)
if accountSummariesErr != nil {
return nil, fmt.Errorf("构造账号摘要服务失败: %w", accountSummariesErr)
}
// credentialWake 负责将凭证恢复后的任务唤醒写入收口到适配器。
// automationDependencies 提供自动化、默认回复和关键词用例的显式适配器工厂。
automationDependencies := server.automationDependencies
if automationDependencies == nil {
return nil, fmt.Errorf("自动化专用依赖未装配")
}
// credentialWake、credentialWakeErr 保存凭证恢复后的自动化唤醒应用服务及装配错误。
credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(automationDependencies.NewAutomationCredentialWakeRepository())
if credentialWakeErr != nil {
return nil, fmt.Errorf("构造凭证恢复唤醒服务失败: %w", credentialWakeErr)
}
// accountRuntime 将 Manager 与凭证恢复后的自动化唤醒收口到账号应用端口。
accountRuntime := accountapp.NewRuntimeService(adapter.NewAccountRuntimePort(server.Manager), credentialWake)
// loginSuccess 负责登录成功后的资料刷新和启用账号运行时重启,避免 Server 持有业务编排。
loginSuccess := accountapp.NewLoginSuccessService(accountRepository, accountProfile, accountRepository, accountRuntime, func(message string, err error) {
if server.Logger != nil {
server.Logger.Warn(message, "err", err)
}
})
// loginAudit 负责登录方式、账号启用和审计日志写入,生命周期适配器只组合应用端口。
loginAudit := accountapp.NewLoginAuditService(server.accountDependencies.NewAccountLoginAuditRepository())
// loginLifecycle 将手动登录与扫码登录的成功后续动作收口到 adapter,不再反向持有 Server。
loginLifecycle := adapter.NewAccountLoginLifecycle(loginAudit, loginSuccess, server.Logger)
// deleteRuntime 是可选的账号运行时端口;显式保持 nil,避免把 nil *Manager 装入非空接口后触发 panic。
var deleteRuntime accountapp.DeleteRuntime
if server.Manager != nil {
deleteRuntime = server.Manager
}
// accountDelete 是账号删除用例的构造结果,运行时端口可为空以兼容无 Manager 的测试 Server。
accountDelete, deleteErr := accountapp.NewDeleteService(accountRepository, deleteRuntime)
if deleteErr != nil {
return nil, fmt.Errorf("构造账号删除服务失败: %w", deleteErr)
}
// itemBatchPublish 是批量远端发布适配器,图片安全回调由 Server 装配时注入。
itemBatchPublish := server.itemDependencies.NewItemBatchPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
if sessionRecovery != nil {
sessionRecovery(ctx, cookieID, err)
}
}, readBatchImageFile, downloadImageURL)
// itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。
itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService(
server.itemDependencies.NewItemBatchRepository(),
server.itemDependencies.NewItemCatalogRepository(),
automationDependencies.NewAutomationRepository(),
)
if itemBatchLocalPublishErr != nil {
return nil, fmt.Errorf("构造批量发布本地收口服务失败: %w", itemBatchLocalPublishErr)
}
// itemBatchRunner 是批量发布 worker 的构造结果,失败表示必需端口装配错误。
itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server, itemBatchPublish, itemBatchLocalPublish)
if batchRunnerErr != nil {
return nil, fmt.Errorf("构造批量发布运行器失败: %w", batchRunnerErr)
}
// itemBatchRecovery 负责恢复扫描的批次状态编排;worker 生命周期由协调器拥有。
itemBatchRecovery, batchRecoveryErr := itemapp.NewBatchRecoveryService(
server.itemDependencies.NewItemBatchRepository(),
itemapp.BatchRecoveryOptions{LeaseDuration: publishBatchLease},
)
if batchRecoveryErr != nil {
return nil, fmt.Errorf("构造批量发布恢复服务失败: %w", batchRecoveryErr)
}
// itemBatchCoordinator 负责批次 worker 的超时、恢复扫描和停止等待。
itemBatchCoordinator, batchCoordinatorErr := itemapp.NewBatchWorkerCoordinator(itemBatchRunner, itemBatchRecovery, itemapp.BatchWorkerCoordinatorOptions{
OnWorkerError: func(batchID string, err error) {
if server.Logger != nil {
server.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", err)
}
},
OnRecoveryError: func(err error) {
if server.Logger != nil {
server.Logger.Warn("扫描可恢复批量发布任务失败", "err", err)
}
},
})
if batchCoordinatorErr != nil {
return nil, fmt.Errorf("构造批量发布协调器失败: %w", batchCoordinatorErr)
}
// itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。
itemBatchPreviewPort := server.itemDependencies.NewItemBatchPreviewPort()
// itemBatchPreview 是批量发布预检应用服务的构造结果。
itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort)
if itemBatchPreviewErr != nil {
return nil, fmt.Errorf("构造批量发布预检服务失败: %w", itemBatchPreviewErr)
}
// itemBatchManagement 是批次管理应用服务的构造结果。
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.itemDependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server, coordinator: itemBatchCoordinator})
if itemBatchManagementErr != nil {
return nil, fmt.Errorf("构造批量发布管理服务失败: %w", itemBatchManagementErr)
}
// accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。
accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(loginLifecycle)
if accountLoginCreateErr != nil {
return nil, fmt.Errorf("构造账号登录创建服务失败: %w", accountLoginCreateErr)
}
// accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。
var accountQRLogin *accountapp.QRLoginService
if server.accountDependencies != nil {
// accountQRLoginErr 保存扫码应用服务装配失败原因。
var accountQRLoginErr error
accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.accountDependencies.NewQRLoginRepository(), loginLifecycle)
if accountQRLoginErr != nil {
return nil, fmt.Errorf("构造扫码登录服务失败: %w", accountQRLoginErr)
}
}
// qrSessionRegistry 将扫码会话所有权、过期回收和幂等结果放在应用边界内。
qrSessionRegistry := accountapp.NewQRLoginSessionRegistry()
// itemCatalogRepository 是商品读写用例共用的数据库适配器。
itemCatalogRepository := server.itemDependencies.NewItemCatalogRepository()
// itemCatalog 是商品列表和详情读取用例的应用服务。
itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository)
if itemCatalogErr != nil {
return nil, fmt.Errorf("构造商品目录服务失败: %w", itemCatalogErr)
}
// itemCatalogMutation 是商品写入用例的应用服务。
itemCatalogMutation, itemCatalogMutationErr := itemapp.NewCatalogMutationService(itemCatalogRepository)
if itemCatalogMutationErr != nil {
return nil, fmt.Errorf("构造商品目录写入服务失败: %w", itemCatalogMutationErr)
}
// itemPublishPort 是单商品与批量发布共享的平台凭证适配器。
itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) bool {
return sessionRecovery != nil && sessionRecovery(ctx, cookieID, err)
})
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
if itemCategoryRecommendationErr != nil {
return nil, fmt.Errorf("构造商品类目推荐服务失败: %w", itemCategoryRecommendationErr)
}
// itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.itemDependencies.NewItemBatchRepository())
if itemBatchPreviewPersistenceErr != nil {
return nil, fmt.Errorf("构造批量预检持久化服务失败: %w", itemBatchPreviewPersistenceErr)
}
// itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。
itemSinglePublish, itemSinglePublishErr := itemapp.NewService(
itemPublishPort,
server.itemDependencies.NewItemPublishRepository(),
)
if itemSinglePublishErr != nil {
return nil, fmt.Errorf("构造单商品发布服务失败: %w", itemSinglePublishErr)
}
// services 是完成构造后只读注入 Server 的应用服务集合。
services := &applicationServices{
platformCredentials: platformCredentials,
orders: &orderHTTPAdapter{services: orderServices},
orderRefreshJobs: orderRefreshJobs,
orderReconciliationRecovery: server.orderReconciliationRecovery,
itemSinglePublish: itemSinglePublish,
itemBatchCoordinator: itemBatchCoordinator,
itemBatchPreview: itemBatchPreview,
itemBatchManagement: itemBatchManagement,
itemCategoryRecommendation: itemCategoryRecommendation,
itemBatchPreviewPersistence: itemBatchPreviewPersistence,
itemBatchLocalPublish: itemBatchLocalPublish,
itemSync: itemapp.NewSyncService(server.itemDependencies.NewItemSyncRepository(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
if sessionRecovery != nil {
sessionRecovery(ctx, cookieID, err)
}
})),
itemCatalog: itemCatalog,
itemCatalogMutation: itemCatalogMutation,
accountLogin: &accountLoginService{cookieWriterFactory: cookieWriterFactory, cookieUpdaterFactory: cookieUpdaterFactory, sessionPort: accountRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin, qrSessions: qrSessionRegistry},
authentication: nil,
loginAudit: loginAudit,
passwordLogin: accountapp.NewPasswordLoginService(),
accountDelete: accountDelete,
accountProfile: accountProfile,
accountLongLogin: accountLongLogin,
accountSettings: accountSettings,
accountRuntime: accountRuntime,
accountSummaries: accountSummaries,
accountTasks: server.transportApplications.AccountTasks,
credentialWake: credentialWake,
chat: newChatSendingApplication(server),
uncertainNotifications: server.transportApplications.UncertainNotifications,
notificationChannels: server.transportApplications.NotificationChannels,
analytics: server.transportApplications.Analytics,
automationRules: server.transportApplications.AutomationRules,
cards: server.transportApplications.Cards,
publishAutomationRules: server.transportApplications.PublishAutomationRules,
automationIssues: server.transportApplications.AutomationIssues,
defaultReplies: server.transportApplications.DefaultReplies,
keywords: server.transportApplications.Keywords,
settings: server.transportApplications.Settings,
admin: server.transportApplications.Admin,
}
// authentication、authenticationErr 分别是认证应用服务及其构造错误。
authentication, authenticationErr := newAuthenticationApplication(server)
if authenticationErr != nil {
return nil, authenticationErr
}
services.authentication = authentication
return services, nil
}
// accountRuntimeApplication 返回当前 Server 绑定的账号运行时应用服务。
func (s *Server) accountRuntimeApplication() *accountapp.RuntimeService {
return s.applicationServiceSet().accountRuntime
}
// newAuthenticationApplication 构造用户认证应用服务及其数据库适配器。
func newAuthenticationApplication(server *Server) (*accountapp.AuthenticationService, error) {
// authentication、authenticationErr 保存认证应用服务及其装配错误。
authentication, authenticationErr := accountapp.NewAuthenticationService(server.accountDependencies.NewAuthenticationRepository())
if authenticationErr != nil {
return nil, fmt.Errorf("构造认证应用服务失败: %w", authenticationErr)
}
return authentication, nil
}
// orderRefreshJobsApplication 返回当前 Server 绑定的订单刷新任务应用服务。
func (s *Server) orderRefreshJobsApplication() *orderapp.RefreshJobService {
return s.applicationServiceSet().orderRefreshJobs
}
// itemCatalogApplication 返回当前 Server 绑定的商品读取应用服务。
func (s *Server) itemCatalogApplication() *itemapp.CatalogService {
return s.applicationServiceSet().itemCatalog
}
// itemSinglePublishApplication 返回当前 Server 绑定的单商品发布应用服务。
func (s *Server) itemSinglePublishApplication() *itemapp.Service {
return s.applicationServiceSet().itemSinglePublish
}
// itemCatalogMutationApplication 返回当前 Server 绑定的商品写入应用服务。
func (s *Server) itemCatalogMutationApplication() *itemapp.CatalogMutationService {
return s.applicationServiceSet().itemCatalogMutation
}
// itemSyncApplication 返回当前 Server 绑定的商品同步应用服务。
func (s *Server) itemSyncApplication() *itemapp.SyncService {
return s.applicationServiceSet().itemSync
}
// cardsApplication 返回当前 Server 绑定的卡券 CRUD 应用服务。
func (s *Server) cardsApplication() *cardsapp.Service {
return s.applicationServiceSet().cards
}
// accountTaskApplication 返回当前 Server 绑定的账号任务应用服务。
func (s *Server) accountTaskApplication() *automationapp.Service {
return s.applicationServiceSet().accountTasks
}
// automationIssuesApplication 返回当前 Server 绑定的自动化异常应用服务。
func (s *Server) automationIssuesApplication() *automationapp.IssueService {
return s.applicationServiceSet().automationIssues
}
// automationRulesApplication 返回当前 Server 绑定的自动化规则应用服务。
func (s *Server) automationRulesApplication() *automationapp.RuleService {
return s.applicationServiceSet().automationRules
}
// itemBatchPreviewApplication 返回当前 Server 绑定的批量预检应用服务。
func (s *Server) itemBatchPreviewApplication() *itemapp.BatchPreviewService {
return s.applicationServiceSet().itemBatchPreview
}
// itemBatchManagementApplication 返回当前 Server 绑定的批次管理应用服务。
func (s *Server) itemBatchManagementApplication() *itemapp.BatchManagementService {
return s.applicationServiceSet().itemBatchManagement
}
// itemCategoryRecommendationApplication 返回商品类目推荐应用服务。
func (s *Server) itemCategoryRecommendationApplication() *itemapp.CategoryRecommendationService {
return s.applicationServiceSet().itemCategoryRecommendation
}
// itemBatchPreviewPersistenceApplication 返回预检结果持久化应用服务。
func (s *Server) itemBatchPreviewPersistenceApplication() *itemapp.BatchPreviewPersistenceService {
return s.applicationServiceSet().itemBatchPreviewPersistence
}
// accountProfileApplication 返回当前 Server 绑定的账号资料应用服务。
func (s *Server) accountProfileApplication() *accountapp.ProfileService {
return s.applicationServiceSet().accountProfile
}
// accountLongLoginApplication 返回当前 Server 绑定的长登录应用服务。
func (s *Server) accountLongLoginApplication() *accountapp.LongLoginService {
return s.applicationServiceSet().accountLongLogin
}
// accountSettingsApplication 返回当前 Server 绑定的账号设置应用服务。
func (s *Server) accountSettingsApplication() *accountapp.SettingsService {
return s.applicationServiceSet().accountSettings
}
// platformCredentialApplication 返回当前 Server 绑定的平台凭证只读应用服务。
func (s *Server) platformCredentialApplication() *accountapp.PlatformCredentialService {
if s == nil || s.applications == nil {
return nil
}
return s.applications.platformCredentials
}
// authenticationApplication 返回当前 Server 绑定的用户认证应用服务。
func (s *Server) authenticationApplication() *accountapp.AuthenticationService {
return s.applicationServiceSet().authentication
}
// accountSummaryApplication 返回当前 Server 绑定的账号摘要应用服务。
func (s *Server) accountSummaryApplication() *accountapp.SummaryService {
return s.applicationServiceSet().accountSummaries
}
// accountDeleteApplication 返回当前 Server 绑定的账号删除应用服务。
func (s *Server) accountDeleteApplication() *accountapp.DeleteService {
return s.applicationServiceSet().accountDelete
}
// loginAuditApplication 返回当前 Server 绑定的登录成功审计应用服务。
func (s *Server) loginAuditApplication() *accountapp.LoginAuditService {
return s.applicationServiceSet().loginAudit
}
// settingsApplication 返回当前 Server 绑定的设置应用服务。
func (s *Server) settingsApplication() *settingsapp.Service {
return s.applicationServiceSet().settings
}
// applicationServiceSet 返回当前 Server 构造阶段注入的不可变应用服务集合。
// 零值 Server 返回共享空集合以支持防御性测试,绝不在请求期构造或缓存业务服务。
func (s *Server) applicationServiceSet() *applicationServices {
if s == nil || s.applications == nil {
return emptyApplicationServices
}
return s.applications
}
@@ -1,93 +0,0 @@
package server
import (
"sync"
"testing"
)
// TestNewServerAssemblesApplicationServices 验证 Server 构造时统一装配全部应用服务。
func TestNewServerAssemblesApplicationServices(t *testing.T) {
// srv 是使用测试依赖创建的 Server。
srv, _, cleanup := newTestServer(t)
defer cleanup()
if srv.applications == nil {
t.Fatal("Server 应在构造时装配应用服务集合")
}
// services 是统一应用服务集合。
services := srv.applicationServiceSet()
if services.orders == nil || services.orderRefreshJobs == nil || services.itemBatchCoordinator == nil || services.itemSinglePublish == nil || services.itemCatalog == nil || services.itemCatalogMutation == nil || services.accountLogin == nil || services.authentication == nil || services.loginAudit == nil || services.passwordLogin == nil || services.accountDelete == nil || services.accountSettings == nil || services.uncertainNotifications == nil || services.notificationChannels == nil || services.analytics == nil || services.cards == nil || services.publishAutomationRules == nil || services.defaultReplies == nil || services.keywords == nil {
t.Fatal("应用服务集合存在未装配的服务")
}
if services.orders.services == nil || services.orders.services.List == nil || services.orders.services.Detail == nil || services.orders.services.Refresh == nil || services.orders.services.RefreshJobs == nil {
t.Fatal("订单应用服务应由应用层 ServiceSet 完整装配")
}
if srv.orders() != services.orders || srv.itemCatalogApplication() != services.itemCatalog || srv.itemCatalogMutationApplication() != services.itemCatalogMutation || srv.accountLoginApplication() != services.accountLogin || srv.analyticsApplication() != services.analytics || srv.defaultReplyApplication() != services.defaultReplies || srv.keywordApplication() != services.keywords {
t.Fatal("应用服务访问器未返回统一装配实例")
}
}
// TestApplicationServicesExposeWorkerOwnership 验证应用服务集合暴露只读 worker 生命周期端口,不让 Server 反向返还组件。
func TestApplicationServicesExposeWorkerOwnership(t *testing.T) {
// srv、cleanup 保存带完整应用服务装配的测试 Server 及其资源清理函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// components 保存交给进程生命周期协调器登记的应用 worker 组件。
components := srv.ApplicationServices().LifecycleComponents()
if len(components) != 3 {
t.Fatalf("应用生命周期组件数量=%d,期望=3", len(components))
}
// names 保存组件稳定名称,顺序同时表达启动依赖与关闭逆序。
names := make([]string, 0, len(components))
// component 表示当前应用 worker 生命周期组件。
for _, component := range components {
names = append(names, component.Name)
if component.Component == nil {
t.Fatalf("组件 %q 缺少生命周期实现", component.Name)
}
}
// want 是 cmd 应登记的应用 worker 稳定名称与启动顺序。
want := []string{"order-refresh-recovery", "publish-batch-workers", "order-reconciliation-recovery"}
if len(names) != len(want) {
t.Fatalf("组件名称数量=%d,期望=%d", len(names), len(want))
}
// index 表示当前比较的生命周期组件下标。
for index := range want {
if names[index] != want[index] {
t.Fatalf("组件名称[%d]=%q,期望=%q", index, names[index], want[index])
}
}
}
// TestApplicationServiceSetUsesStableZeroValueSet 验证零值 Server 不会在请求期创建服务集合,并支持并发防御性读取。
func TestApplicationServiceSetUsesStableZeroValueSet(t *testing.T) {
// srv 是未注入依赖的零值 Server,仅用于验证防御性访问不触发隐式装配。
var srv Server
// first 是首次读取到的共享空服务集合。
first := srv.applicationServiceSet()
if first != emptyApplicationServices {
t.Fatal("零值 Server 应返回共享空服务集合")
}
// readers 是并发读取服务集合的工作数,用于覆盖请求期读路径的数据竞争风险。
const readers = 32
// group 等待全部并发读取完成后再检查结果。
var group sync.WaitGroup
// failures 记录任何一次读取没有返回同一只读集合的情况。
failures := make(chan *applicationServices, readers)
for range readers {
group.Add(1)
go func() {
defer group.Done()
// services 是当前 goroutine 读取到的应用服务集合。
services := srv.applicationServiceSet()
if services != first {
failures <- services
}
}()
}
group.Wait()
close(failures)
// services 是未满足稳定集合约束的错误读取结果,仅用于在失败时提供诊断。
for services := range failures {
t.Fatalf("并发读取返回了不同服务集合: %p", services)
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
srv, _, cleanup := newTestServerWithChat(t)
defer cleanup()
// service 用于本次流程后续判断的service
service := srv.chat
service := testChatDomain(srv)
// handler 用于本次流程后续判断的handler
handler := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
-17
View File
@@ -1,17 +0,0 @@
package server
import (
"xianyu-go/internal/adapter"
chatapp "xianyu-go/internal/application/chat"
)
// newChatSendingApplication 创建实时聊天应用服务,Server 仅负责注入运行时依赖。
func newChatSendingApplication(server *Server) *chatapp.Service {
if server == nil {
return adapter.NewChatSendingApplication(nil, nil, nil, nil)
}
if server.chatDependencies == nil {
return adapter.NewChatSendingApplication(server.chat, nil, server.Manager, server.mtopClient)
}
return server.chatDependencies.NewChatSendingApplication(server.chat, server.Manager, server.mtopClient)
}
+4 -14
View File
@@ -40,7 +40,7 @@ func (s *Server) mountChat(r chi.Router) {
}
// chatApplication 返回当前 Server 绑定的聊天历史应用服务。
func (s *Server) chatApplication() *chatapp.Service {
func (s *Server) chatApplication() ChatPort {
return s.applicationServiceSet().chat
}
@@ -328,19 +328,9 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
return
}
if s.Manager != nil {
// sender、ok 保存当前账号运行时及其在线状态。
if sender, ok := s.Manager.GetInstance(input.AccountID); ok {
// reader、ok 保存运行时是否支持平台已读上报。
if reader, ok := sender.(interface {
MarkChatRead(context.Context, string, []map[string]any) error
}); ok {
// err 保存平台已读上报失败,失败不影响本地状态已落库。
if err := reader.MarkChatRead(r.Context(), input.ChatID, input.MessageIDs); err != nil {
slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", err)
}
}
}
// reportErr 表示平台已读上报失败;本地已读状态已成功保存,不能回滚。
if reportErr := s.chatApplication().ReportPlatformRead(r.Context(), input.AccountID, input.ChatID, input.MessageIDs); reportErr != nil {
slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", reportErr)
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
+2 -2
View File
@@ -442,7 +442,7 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 用于本次流程后续判断的err
err := s.accountLoginApplication().CreateCookie(r.Context(), accountLoginInput{AccountID: req.ID, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
err := s.accountLoginApplication().CreateCookie(r.Context(), req.ID, req.Value, sess.UserID, req.LoginMethod); err != nil {
if errors.Is(err, accountapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
return
@@ -486,7 +486,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 用于本次流程后续判断的err
err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod, ExpectedRevision: req.LastRefreshAt}); err != nil {
err := s.accountLoginApplication().UpdateCookie(r.Context(), cid, req.Value, sess.UserID, req.LoginMethod, req.LastRefreshAt); err != nil {
if errors.Is(err, accountapp.ErrCredentialConflict) {
writeErr(w, http.StatusConflict, err.Error())
return
+6 -10
View File
@@ -95,11 +95,11 @@ func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.CookieRenew = xrenew.Service{
setTestCookieRenew(srv, xrenew.Service{
HTTPClient: passport.Client(),
QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
SetLoginSettingsURL: passport.URL + "/setLoginSettings.do",
}
})
// detail、err 用于本次流程后续判断的detail、err
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
@@ -173,10 +173,10 @@ func TestLongLoginFailureStillPersistsResponseCookiesWithoutInventingSnapshot(t
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.CookieRenew = xrenew.Service{
setTestCookieRenew(srv, xrenew.Service{
HTTPClient: passport.Client(),
QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
}
})
// h 用于本次流程后续判断的h
h := srv.Router()
// session 用于本次流程后续判断的会话
@@ -229,10 +229,10 @@ func TestLongLoginAuthoritativeSnapshotCanBeDeletedToEmpty(t *testing.T) {
err := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", "only_cookie=old", metadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
srv.CookieRenew = xrenew.Service{
setTestCookieRenew(srv, xrenew.Service{
HTTPClient: passport.Client(),
QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
}
})
// h 用于本次流程后续判断的h
h := srv.Router()
// session 用于本次流程后续判断的会话
@@ -612,7 +612,6 @@ func TestUpdateRunningCookieWakesCredentialBlockedAutomationWithoutManager(t *te
}); err != nil {
t.Fatal(err)
}
srv.Manager = nil
srv.updateRunningCookie(ctx, "acc1", "unb=123; _m_h5_tk=fresh_1;")
// got 用于本次流程后续判断的got
var got int64
@@ -710,7 +709,6 @@ func TestSetCookieStatusWaitsForCredentialTransition(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -753,7 +751,6 @@ func TestDeleteCookieRechecksOwnershipInsideCredentialLock(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
if // ok、err 用于本次流程后续判断的ok、err
@@ -1091,7 +1088,6 @@ func TestAddCookieDefaultsManualLoginAudit(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// h 用于本次流程后续判断的h
+1 -3
View File
@@ -1,9 +1,7 @@
package server
import defaultreplyapp "xianyu-go/internal/application/defaultreply"
// defaultReplyApplication 返回默认回复应用服务。
// 该方法在主装配集合接入前提供同一 Port 的兼容构造入口,后续由统一装配复用实例。
func (s *Server) defaultReplyApplication() *defaultreplyapp.Service {
func (s *Server) defaultReplyApplication() DefaultRepliesPort {
return s.applicationServiceSet().defaultReplies
}
@@ -7,7 +7,7 @@ import (
)
// newBatchLocalPublishService 返回构造阶段已完成依赖校验的批量本地收口应用服务。
func (s *Server) newBatchLocalPublishService() (*itemapp.BatchLocalPublishService, error) {
func (s *Server) newBatchLocalPublishService() (ItemBatchLocalPublishPort, error) {
if s == nil || s.applicationServiceSet() == nil || s.applicationServiceSet().itemBatchLocalPublish == nil {
return nil, itemapp.ErrBatchLocalPublishUnavailable
}
@@ -1,31 +0,0 @@
package server
import (
"errors"
itemapp "xianyu-go/internal/application/items"
)
// serverBatchManagementRuntime 将批次管理应用端口接到 Server 的 worker 生命周期边界。
type serverBatchManagementRuntime struct {
// server 保存批次 worker 启动与取消所需的 Server 生命周期入口。
server *Server
// coordinator 保存应用层批次 worker 生命周期协调器。
coordinator *itemapp.BatchWorkerCoordinator
}
// StartBatch 启动已由应用服务声明租约的批量 worker,并返回协调器登记失败。
func (runtime serverBatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) error {
if runtime.server == nil || runtime.coordinator == nil {
return errors.New("批量 worker 协调器未装配")
}
return runtime.coordinator.Start(runtime.server.lifecycleContext(), userID, batchID, workerToken)
}
// CancelBatch 取消指定批次的后台 worker。
func (runtime serverBatchManagementRuntime) CancelBatch(batchID, workerToken string) {
if runtime.coordinator == nil {
return
}
_ = runtime.coordinator.Cancel(batchID, workerToken)
}
+41 -36
View File
@@ -30,12 +30,17 @@ func TestRecommendItemPublishCategory(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx、cancel 用于本次流程后续判断的ctx、cancel
// manager 是测试组合根登记的账号运行时,用于验证平台 Cookie 回调会同步活动实例。
manager := testAccountManager(srv)
if manager == nil {
t.Fatal("测试账号管理器未登记")
}
// ctx、cancel 用于创建已取消的测试运行实例,避免发起真实平台连接。
ctx, cancel := context.WithCancel(context.Background())
cancel()
if // err 用于本次流程后续判断的err
err := srv.Manager.Start(ctx, "acc1", "unb=123; _m_h5_tk=tk1_1;"); err != nil {
t.Fatal(err)
// startErr 表示已取消测试运行实例的启动结果;该调用不允许建立真实平台连接。
if startErr := manager.Start(ctx, "acc1", "unb=123; _m_h5_tk=tk1_1;"); startErr != nil {
t.Fatal(startErr)
}
if // err 用于本次流程后续判断的err
err := store.Tokens.Save(context.Background(), "acc1", "device", "stale-token", time.Now().Add(time.Hour).Unix()); err != nil {
@@ -58,7 +63,7 @@ func TestRecommendItemPublishCategory(t *testing.T) {
Request: req,
}, nil
})}
srv.MTop = client
setTestMTop(srv, client)
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -334,8 +339,8 @@ func TestPublishItemSuccess(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 替换为按 URL 分发的 mock。
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
prev := testMTop(srv)
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// u 用于本次流程后续判断的u
u := req.URL.String()
// respBody 用于本次流程后续判断的resp请求体
@@ -356,8 +361,8 @@ func TestPublishItemSuccess(t *testing.T) {
Body: io.NopCloser(strings.NewReader(respBody)),
Request: req,
}, nil
}))
defer func() { srv.MTop = prev }()
})))
defer func() { setTestMTop(srv, prev) }()
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -391,9 +396,9 @@ func TestPublishItemRejectsMissingRemoteItemID(t *testing.T) {
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
setTestMTop(srv, &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return &mtop.PublishItemResult{Title: "测试商品"}, nil
}}
}})
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -417,10 +422,10 @@ func TestPublishItemReportsRemoteSuccessLocalSaveFailure(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
setTestMTop(srv, &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
_, _ = store.DB.ExecContext(context.Background(), `DELETE FROM cookies WHERE id='acc1'`)
return &mtop.PublishItemResult{ItemID: "remote-only", ItemURL: "https://example/item/remote-only", Title: "测试商品"}, nil
}}
}})
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -445,8 +450,8 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 用于本次流程后续判断的prev
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
prev := testMTop(srv)
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// u 用于本次流程后续判断的u
u := req.URL.String()
// respBody 用于本次流程后续判断的resp请求体
@@ -468,8 +473,8 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
Body: io.NopCloser(strings.NewReader(respBody)),
Request: req,
}, nil
}))
defer func() { srv.MTop = prev }()
})))
defer func() { setTestMTop(srv, prev) }()
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -524,8 +529,8 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
t.Fatal(err)
}
// prev 用于本次流程后续判断的prev
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
prev := testMTop(srv)
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 用于本次流程后续判断的请求体
body := `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[` +
`{"cardData":{"id":"it-sync-1","title":"同步商品A","priceInfo":{"price":"12.50","preText":"¥"},"picInfo":{"picUrl":"https://img.alicdn.com/a.png"},"categoryId":"9","detailParams":{"itemId":"it-sync-1"}}}]}}`
@@ -535,8 +540,8 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
}))
defer func() { srv.MTop = prev }()
})))
defer func() { setTestMTop(srv, prev) }()
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -587,13 +592,13 @@ func TestSyncItemsFromAccountReleasesCredentialLockDuringRemoteCall(t *testing.T
release := make(chan struct{})
// once 保证 started 只关闭一次。
var once sync.Once
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
once.Do(func() { close(started) })
<-release
// body 是空商品列表的成功响应。
body := `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
})))
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -640,7 +645,7 @@ func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 用于本次流程后续判断的请求体
body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
if strings.Contains(req.URL.String(), "mtop.idle.web.xyh.item.list") {
@@ -649,7 +654,7 @@ func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
body = `{"ret":["SUCCESS::调用成功"],"data":{"multiSKU":true,"skuDO":{"skuList":[{"id":"a"},{"id":"b"}]}}}`
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
})))
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -676,8 +681,8 @@ func TestSyncItemsFromAccountFail(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 用于本次流程后续判断的prev
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
prev := testMTop(srv)
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 用于本次流程后续判断的请求体
body := `{"ret":["FAIL_SYS_USER_VALIDATE::用户校验失败"]}`
return &http.Response{
@@ -686,8 +691,8 @@ func TestSyncItemsFromAccountFail(t *testing.T) {
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
}))
defer func() { srv.MTop = prev }()
})))
defer func() { setTestMTop(srv, prev) }()
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -757,8 +762,8 @@ func TestSyncItemsPageFromAccountSuccess(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 用于本次流程后续判断的prev
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
prev := testMTop(srv)
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 用于本次流程后续判断的请求体
body := `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[` +
`{"cardData":{"id":"it-page-1","title":"分页商品","priceInfo":{"price":"9.90","preText":"¥"},"picInfo":{"picUrl":"https://img.alicdn.com/p.png"},"categoryId":"1","detailParams":{"itemId":"it-page-1"}}}]}}`
@@ -768,8 +773,8 @@ func TestSyncItemsPageFromAccountSuccess(t *testing.T) {
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
}))
defer func() { srv.MTop = prev }()
})))
defer func() { setTestMTop(srv, prev) }()
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -801,9 +806,9 @@ func TestSyncItemsPageFromAccountFail(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 用于本次流程后续判断的prev
prev := srv.MTop
srv.MTop = newMockMTop(t, mtopResp{ret: []string{"FAIL_SYS_USER_VALIDATE::失败"}})
defer func() { srv.MTop = prev }()
prev := testMTop(srv)
setTestMTop(srv, newMockMTop(t, mtopResp{ret: []string{"FAIL_SYS_USER_VALIDATE::失败"}}))
defer func() { setTestMTop(srv, prev) }()
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -16,7 +16,6 @@ import (
"github.com/go-chi/chi/v5"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/auth"
@@ -744,58 +743,6 @@ func firstNonEmpty(values ...string) string {
return ""
}
// serverBatchPublisher 将 Server 的商品发布细节适配为应用层批量发布端口。
type serverBatchPublisher struct {
// remotePort 保存已装配的平台与凭证端口,避免 worker 再进入 Server 远端逻辑。
remotePort itemapp.BatchPublishPort
// localService 保存已装配的本地商品、自动化规则和成功检查点收口服务。
localService *itemapp.BatchLocalPublishService
}
// PublishRow 调用批量远端端口并收口本地结果,应用层不接触数据库或 MTOP 类型。
func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string, beforePublish func(context.Context) error) error {
if p.remotePort == nil {
return errors.New("批量发布端口未装配")
}
if p.localService == nil {
return errors.New("批量发布本地收口端口未装配")
}
// outcome、err 保存远端发布结果及适配器错误。
outcome, err := p.remotePort.PublishRemoteRow(ctx, userID, row, workerToken, beforePublish)
if err != nil {
// uncertainErr 表示远端调用已经发生但结果无法可靠确认。
var uncertainErr *itemapp.UncertainRemotePublishError
if errors.As(err, &uncertainErr) {
return &uncertainRemotePublishError{err: err}
}
return err
}
if outcome.Result == nil {
return errors.New("发布商品接口未返回结果")
}
if outcome.ResponseCookieErr != nil {
return &itemapp.PostPublishError{Err: outcome.ResponseCookieErr}
}
if ctx.Err() != nil {
return &itemapp.PostPublishError{Err: ctx.Err()}
}
return p.localService.Complete(ctx, userID, row, workerToken, outcome.Result)
}
// newItemBatchRunnerApplication 创建批量发布应用层 worker 编排器。
func newItemBatchRunnerApplication(server *Server, remotePort itemapp.BatchPublishPort, localService *itemapp.BatchLocalPublishService) (*itemapp.BatchRunner, error) {
if server == nil || remotePort == nil || localService == nil {
return nil, errors.New("批量发布端口未装配")
}
// options 配置批量 worker 的租约、间隔和平台错误语义。
options := itemapp.BatchRunOptions{
LeaseDuration: publishBatchLease,
IsSessionExpired: adapter.IsSessionExpiredError,
ClassifyFailure: publishBatchFailure,
}
return itemapp.NewBatchRunner(server.itemDependencies.NewItemBatchRepository(), serverBatchPublisher{remotePort: remotePort, localService: localService}, options)
}
// publishBatchLocation 保存批量发布请求中的发货地字段,不让平台 DTO 进入 HTTP 层。
type publishBatchLocation struct {
Area string `json:"area"`
+1 -1
View File
@@ -82,7 +82,7 @@ func (s *Server) mountKeywordsReal(r chi.Router) {
}
// keywordApplication 返回关键词回复应用服务;具体依赖由 Server 统一装配。
func (s *Server) keywordApplication() *keywords.Service {
func (s *Server) keywordApplication() KeywordsPort {
return s.applicationServiceSet().keywords
}
-28
View File
@@ -1,28 +0,0 @@
package server
import (
"context"
"errors"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
)
// persistMTopCookieSessionLocked 原子保存业务 MTOP 响应后的完整 Cookie Jar。
// 调用方必须持有账号凭证锁,并且 detail 必须是加锁后重读的最新记录。
// handled 表示本次请求由完整 Cookie Jar 接管,或 session 已产生可持久化更新;
// 此时即使 Jar 未变化,也不得因扁平 Cookie 的顺序/尾分号差异退回
// UpdatedCookies 写回,否则会把刚保存的完整 Jar 清掉。
// persistMTopCookieSessionLocked 封装persistMTop登录凭证会话Locked业务协调。
func (s *Server) persistMTopCookieSessionLocked(
ctx context.Context,
detail *accountapp.CredentialDetail,
session *adapter.CookieSession,
) (value string, valueChanged, handled bool, err error) {
if s == nil {
return "", false, true, errors.New("cookie 会话持久化服务未初始化")
}
// sessionPort 只负责在凭证适配器内保存 Cookie 与加密 metadata;Server 不直接访问 Store。
sessionPort := s.platformCredentialSessionPort()
return adapter.PersistCookieSessionLocked(ctx, sessionPort, detail, session)
}
+5 -5
View File
@@ -62,7 +62,7 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
Request: req,
}, nil
})}
srv.MTop = client
setTestMTop(srv, client)
detail, err = store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
@@ -110,12 +110,12 @@ func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.
defer cleanup()
seedStaleCookieSnapshot(t, store, "acc1")
srv.MTop = &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
setTestMTop(srv, &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
return &mtop.UserProfileResult{
Nickname: "mock-profile",
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
}})
// detail、err 用于本次流程后续判断的detail、err
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
@@ -143,12 +143,12 @@ func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T)
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
setTestMTop(srv, &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
return &mtop.UserProfileResult{
Nickname: "mock-profile",
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
}})
// detail、err 用于本次流程后续判断的detail、err
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
+2 -7
View File
@@ -50,12 +50,12 @@ type notificationBindingRequest struct {
}
// notificationChannelsApplication 返回当前 Server 绑定的通知渠道应用服务。
func (s *Server) notificationChannelsApplication() *notificationsapp.ChannelService {
func (s *Server) notificationChannelsApplication() NotificationChannelsPort {
return s.applicationServiceSet().notificationChannels
}
// uncertainNotificationsApplication 返回当前 Server 绑定的通知不确定状态应用服务。
func (s *Server) uncertainNotificationsApplication() *notificationsapp.Service {
func (s *Server) uncertainNotificationsApplication() UncertainNotificationsPort {
return s.applicationServiceSet().uncertainNotifications
}
@@ -201,11 +201,6 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "无效ID")
return
}
// notifier 表示当前 Server 是否装配了实际通知发送器;未装配时保持旧接口的 503 语义,避免先执行归属查询。
if s.notifier == nil {
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
return
}
// err 保存应用层测试发送结果。
if err := s.notificationChannelsApplication().TestChannel(r.Context(), authSess(r).UserID, id, time.Now()); err != nil {
if errors.Is(err, notificationsapp.ErrNotifierUnavailable) {
+11 -11
View File
@@ -149,7 +149,7 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
// body 用于本次流程后续判断的请求体
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
@@ -162,7 +162,7 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
`"priceVO":{"totalPrice":"19.90","buyNum":"2"},` +
`"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
})))
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -209,13 +209,13 @@ func TestRefreshOrdersReleasesCredentialLockDuringDiscovery(t *testing.T) {
release := make(chan struct{})
// once 保证 started 只关闭一次。
var once sync.Once
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
once.Do(func() { close(started) })
<-release
// body 是空订单列表的成功响应。
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"0","items":[]}}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
})))
// h 保存 HTTP 路由处理器。
h := srv.Router()
// cookie 保存登录凭证。
@@ -265,7 +265,7 @@ func TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList(t *testing.T) {
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,cookie_id,order_status) VALUES ('buyer-order','buy-item','seller-account','acc1','pending_ship')`)
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
// body 用于本次流程后续判断的请求体
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"1"},"priceInfo":{"amount":{"value":"10.00"}}}}]}}`
@@ -276,7 +276,7 @@ func TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList(t *testing.T) {
`"commonData":{"orderId":"seller-order","itemId":"seller-item","orderStatus":"待发货"},` +
`"buyerInfoVO":{"buyerId":"buyer-1"},"priceVO":{"totalPrice":"10.00","buyNum":"1"}}]}}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
})))
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -329,11 +329,11 @@ func TestRefreshSingleOrderUsesGoMTop(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 用于本次流程后续判断的请求体
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2","specName":"套餐","specValue":"30天"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
})))
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id, order_status) VALUES ('ord-x','item1','acc1','2')`)
@@ -846,9 +846,9 @@ func TestManualShipOrdersConsignFail(t *testing.T) {
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id, chat_id) VALUES ('ord-f','item1','b1','2','acc1','chat1')`)
// 覆盖 mtop client:返回非 success ret。
prev := srv.MTop
srv.MTop = newMockMTop(t, mtopResp{ret: []string{"FAIL_BIZ_ORDER_NOT_FOUND::订单不存在"}})
defer func() { srv.MTop = prev }()
prev := testMTop(srv)
setTestMTop(srv, newMockMTop(t, mtopResp{ret: []string{"FAIL_BIZ_ORDER_NOT_FOUND::订单不存在"}}))
defer func() { setTestMTop(srv, prev) }()
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -59,7 +59,7 @@ func (s *Server) startOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
// cookieID、filterStatus 保存订单刷新筛选条件。
cookieID, filterStatus := r.FormValue("cookie_id"), r.FormValue("status")
// started、err 保存应用服务创建并启动任务的结果。
started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), s.lifecycleContext(), sess.UserID, cookieID, filterStatus)
started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), r.Context(), sess.UserID, cookieID, filterStatus)
if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问")
return
@@ -226,8 +226,13 @@ func TestOrderRefreshWorkerUsesCanceledServerLifecycle(t *testing.T) {
}
// job 是传给后台 worker 的应用层任务模型。
job := &orderapp.RefreshJob{ID: dbJob.ID, UserID: dbJob.UserID}
// services 是测试组合根拥有的订单服务集合,生产 Server 不暴露 worker 依赖。
services := testOrderServices(srv)
if services == nil {
t.Fatal("测试组合根未登记订单服务")
}
// runner、runnerErr 保存直接由应用层拥有的订单刷新 worker。
runner, runnerErr := orderapp.NewRefreshJobRunner(srv.orders().services.RefreshJobs, srv.orders().services.Refresh, orderapp.RefreshJobRunnerOptions{})
runner, runnerErr := orderapp.NewRefreshJobRunner(services.RefreshJobs, services.Refresh, orderapp.RefreshJobRunnerOptions{})
if runnerErr != nil {
t.Fatalf("构造订单刷新运行器: %v", runnerErr)
}
+11 -186
View File
@@ -3,190 +3,21 @@ package server
import (
"context"
"errors"
"log/slog"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
)
// serverOrderRuntimeAdapter 将 Server 的运行时能力适配为订单应用 Port。
// 适配器只存在于装配边界,订单应用服务本身不再依赖 *Server。
type serverOrderRuntimeAdapter struct {
// runtime 保存已下沉到 adapter 包的订单运行时端口。
runtime *adapter.OrderRuntime
}
// newServerOrderRuntime 创建订单运行时 Port 的 Server 适配器。
func newServerOrderRuntime(server *Server, reconciliation orderapp.ReconciliationRecorder) serverOrderRuntimeAdapter {
// hooks 保存 adapter 内部构造的账号、自动化、通知和平台回调,Server 不再编排业务闭包。
hooks := adapter.OrderRuntimeHooks{}
if server != nil {
// automation、notifier 显式保持 nil 接口语义,避免把 nil 指针转换为非空接口后误报能力已装配。
var automation adapter.OrderAutomation
if server.automation != nil {
automation = server.automation
}
// notifier 只在真实通知器存在时转换为接口,避免 nil 指针伪装成已装配能力。
var notifier adapter.OrderNotifier
if server.notifier != nil {
notifier = server.notifier
}
hooks = adapter.NewOrderRuntimeHooks(server.mtopClient, server.Manager, automation, notifier, server.updateRunningCookie, server.sessionRecoveryCallback())
}
// logger 保存 Server 使用的日志器;适配器会在缺失时使用默认日志器。
var logger = (*slog.Logger)(nil)
if server != nil {
logger = server.Logger
}
// runtime 保存已完成数据库与 Server 回调装配的订单运行时;零值 Server 只用于测试缺失依赖分支。
var runtime *adapter.OrderRuntime
if server == nil {
runtime = adapter.NewOrderRuntime(nil, hooks, reconciliation, logger)
} else {
runtime = server.orderDependencies.NewOrderRuntime(hooks, reconciliation, logger)
}
return serverOrderRuntimeAdapter{runtime: runtime}
}
// AccountRunning 判断指定账号是否在线运行。
func (a serverOrderRuntimeAdapter) AccountRunning(cookieID string) bool {
return a.runtime != nil && a.runtime.AccountRunning(cookieID)
}
// AutomationReady 判断完整发货自动化依赖是否已装配。
func (a serverOrderRuntimeAdapter) AutomationReady() bool {
return a.runtime != nil && a.runtime.AutomationReady()
}
// ManualFullDelivery 执行完整自动化发货。
func (a serverOrderRuntimeAdapter) ManualFullDelivery(ctx context.Context, order *orderapp.Order) (int, error) {
if a.runtime == nil {
return 0, errors.New("订单运行时未初始化")
}
return a.runtime.ManualFullDelivery(ctx, order)
}
// MTopAvailable 判断平台客户端是否已注入。
func (a serverOrderRuntimeAdapter) MTopAvailable() bool {
return a.runtime != nil && a.runtime.MTopAvailable()
}
// ConfirmShipment 将 Server 的确认发货能力适配为应用层结果模型。
func (a serverOrderRuntimeAdapter) ConfirmShipment(ctx context.Context, cookieID, orderID string, userID int64) orderapp.ConsignResult {
if a.runtime == nil {
return orderapp.ConsignResult{Err: errors.New("订单运行时未初始化")}
}
return a.runtime.ConfirmShipment(ctx, cookieID, orderID, userID)
}
// updateRunningCookie 同步运行时账号 Cookie。
func (a serverOrderRuntimeAdapter) updateRunningCookie(ctx context.Context, cookieID, value string) {
if a.runtime != nil {
a.runtime.UpdateRunningCookie(ctx, cookieID, value)
}
}
// UpdateRunningCookie 将运行时账号 Cookie 能力暴露给手动发货应用 Port。
func (a serverOrderRuntimeAdapter) UpdateRunningCookie(ctx context.Context, cookieID, value string) {
a.updateRunningCookie(ctx, cookieID, value)
}
// notifyDelivery 发送发货结果通知。
func (a serverOrderRuntimeAdapter) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
if a.runtime != nil {
a.runtime.NotifyDelivery(cookieID, buyerID, itemID, chatID, message)
}
}
// NotifyDelivery 将发货通知能力暴露给手动发货应用 Port。
func (a serverOrderRuntimeAdapter) NotifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
a.notifyDelivery(cookieID, buyerID, itemID, chatID, message)
}
// RecordOrderReconciliation 将外部动作成功后的本地状态异常写入补偿记录。
func (a serverOrderRuntimeAdapter) RecordOrderReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
if a.runtime == nil {
return "", errors.New("订单运行时未初始化")
}
return a.runtime.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message)
}
// RecordReconciliation 将补偿记录能力暴露给手动发货应用 Port。
func (a serverOrderRuntimeAdapter) RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
return a.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message)
}
// ReportPersistenceFailure 记录手动发货本地订单状态持久化失败。
func (a serverOrderRuntimeAdapter) ReportPersistenceFailure(orderID string, err error) {
if a.runtime != nil {
a.runtime.ReportPersistenceFailure(orderID, err)
}
}
// RecoverExpiredSession 处理订单刷新应用服务报告的平台会话过期。
func (a serverOrderRuntimeAdapter) RecoverExpiredSession(ctx context.Context, cookieID string, err error) bool {
return a.runtime != nil && a.runtime.RecoverExpiredSession(ctx, cookieID, err)
}
// DetailAvailable 判断订单详情接口是否可用。
func (a serverOrderRuntimeAdapter) DetailAvailable() bool {
return a.runtime != nil && a.runtime.DetailAvailable()
}
// SoldAvailable 判断已售订单列表接口是否可用。
func (a serverOrderRuntimeAdapter) SoldAvailable() bool {
return a.runtime != nil && a.runtime.SoldAvailable()
}
// CredentialAvailable 判断平台请求视图是否包含可用 Cookie。
func (a serverOrderRuntimeAdapter) CredentialAvailable(detail *orderapp.PlatformRuntimeData) bool {
return a.runtime != nil && a.runtime.CredentialAvailable(detail)
}
// FetchOrderDetail 调用平台详情接口并收集 Cookie 会话变化。
func (a serverOrderRuntimeAdapter) FetchOrderDetail(ctx context.Context, detail *orderapp.PlatformRuntimeData, orderID string) (orderapp.RefreshDetailFetchResult, error) {
if a.runtime == nil {
return orderapp.RefreshDetailFetchResult{}, errors.New("订单运行时未初始化")
}
return a.runtime.FetchOrderDetail(ctx, detail, orderID)
}
// FetchSoldOrders 调用平台已售订单接口并收集 Cookie 会话变化。
func (a serverOrderRuntimeAdapter) FetchSoldOrders(ctx context.Context, detail *orderapp.PlatformRuntimeData) (orderapp.RefreshSoldFetchResult, error) {
if a.runtime == nil {
return orderapp.RefreshSoldFetchResult{}, errors.New("订单运行时未初始化")
}
return a.runtime.FetchSoldOrders(ctx, detail)
}
// PersistCookieSession 在凭证锁内保存应用层 Cookie 更新。
func (a serverOrderRuntimeAdapter) PersistCookieSession(ctx context.Context, detail *orderapp.PlatformRuntimeData, update orderapp.RefreshCookieUpdate) (string, bool, bool, error) {
if a.runtime == nil {
if detail == nil {
return update.Value, false, update.Handled, errors.New("订单运行时未初始化")
}
return update.Value, update.Value != detail.Value, update.Handled, errors.New("订单运行时未初始化")
}
return a.runtime.PersistCookieSession(ctx, detail, update)
}
// IsSessionExpired 判断平台错误是否为会话过期。
func (a serverOrderRuntimeAdapter) IsSessionExpired(err error) bool {
return a.runtime != nil && a.runtime.IsSessionExpired(err)
}
// orderHTTPAdapter 将 HTTP 请求模型和兼容响应模型适配到应用层订单服务。
// 订单业务编排由 internal/application/orders.ServiceSet 负责。
type orderHTTPAdapter struct {
// services 保存应用层统一构造的订单业务服务集合。
services *orderapp.ServiceSet
services OrdersPort
}
// RefreshSingle 刷新单个订单详情并转换为兼容 HTTP 响应模型。
func (a *orderHTTPAdapter) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderSingleRefreshResponse, error) {
// result、err 保存应用层单订单刷新结果和错误。
result, err := a.services.Refresh.RefreshSingle(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
result, err := a.services.RefreshSingle(ctx, userID, orderID)
if errors.Is(err, orderapp.ErrNotFound) {
return orderSingleRefreshResponse{}, orderapp.ErrNotFound
}
@@ -208,8 +39,7 @@ func (a *orderHTTPAdapter) RefreshSingle(ctx context.Context, userID int64, orde
// Refresh 刷新当前用户订单并转换为兼容 HTTP 响应模型。
func (a *orderHTTPAdapter) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderRefreshResponse, error) {
// result、err 保存应用层批量刷新结果和错误。
result, err := a.services.Refresh.Refresh(ctx, userID, cookieID, status)
err = adapter.NormalizeOrderError(err)
result, err := a.services.Refresh(ctx, userID, cookieID, status)
if errors.Is(err, orderapp.ErrForbidden) {
return orderRefreshResponse{}, orderapp.ErrForbidden
}
@@ -312,7 +142,7 @@ func orderErrorKindOf(err error) (orderErrorKind, bool) {
// orders 返回当前 Server 绑定的订单应用服务。
func (s *Server) orders() *orderHTTPAdapter {
return s.applicationServiceSet().orders
return &orderHTTPAdapter{services: s.applicationServiceSet().orders}
}
// orderListQuery 描述订单列表的业务查询条件。
@@ -391,11 +221,10 @@ type orderDetailResult struct {
// List 查询当前用户可见的订单,并集中处理分页和账号所有权规则。
func (a *orderHTTPAdapter) List(ctx context.Context, query orderListQuery) (orderListResult, error) {
// result、err 保存应用层订单列表结果及错误。
result, err := a.services.List.List(ctx, orderapp.ListQuery{
result, err := a.services.List(ctx, orderapp.ListQuery{
UserID: query.UserID, CookieID: query.CookieID, Status: query.Status,
Search: query.Search, Page: query.Page, PageSize: query.PageSize,
})
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrForbidden) {
return orderListResult{}, orderapp.ErrForbidden
}
@@ -417,8 +246,7 @@ func (a *orderHTTPAdapter) List(ctx context.Context, query orderListQuery) (orde
// Get 查询订单并校验订单绑定账号属于当前用户。
func (a *orderHTTPAdapter) Get(ctx context.Context, userID int64, orderID string) (*orderapp.Order, error) {
// order、err 保存应用层订单详情结果及错误。
order, err := a.services.Detail.Get(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
order, err := a.services.Get(ctx, userID, orderID)
if errors.Is(err, orderapp.ErrNotFound) {
return nil, orderapp.ErrNotFound
}
@@ -431,8 +259,7 @@ func (a *orderHTTPAdapter) Get(ctx context.Context, userID int64, orderID string
// GetView 查询订单并补全商品标题和主图,供详情 handler 直接编码。
func (a *orderHTTPAdapter) GetView(ctx context.Context, userID int64, orderID string) (orderDetailResult, error) {
// result、err 保存应用层详情结果及错误。
result, err := a.services.Detail.GetView(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
result, err := a.services.GetView(ctx, userID, orderID)
if errors.Is(err, orderapp.ErrNotFound) {
return orderDetailResult{}, orderapp.ErrNotFound
}
@@ -448,8 +275,7 @@ func (a *orderHTTPAdapter) GetView(ctx context.Context, userID int64, orderID st
// Delete 逻辑删除订单,保留历史记录供审计使用。
func (a *orderHTTPAdapter) Delete(ctx context.Context, userID int64, orderID string) error {
// err 保存应用层订单删除错误。
err := a.services.Delete.Delete(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
err := a.services.Delete(ctx, userID, orderID)
if errors.Is(err, orderapp.ErrForbidden) {
return orderapp.ErrForbidden
}
@@ -494,7 +320,7 @@ type orderUpdateRequest struct {
// Update 在单事务内更新订单及可选的商品标题。
func (a *orderHTTPAdapter) Update(ctx context.Context, userID int64, orderID string, request orderUpdateRequest) error {
// err 保存应用层订单更新错误。
err := a.services.Update.Update(ctx, userID, orderID, orderapp.UpdateRequest{
err := a.services.Update(ctx, userID, orderID, orderapp.UpdateRequest{
OrderStatus: request.OrderStatus, ItemID: request.ItemID, BuyerID: request.BuyerID,
SpecName: request.SpecName, SpecValue: request.SpecValue, Quantity: request.Quantity,
Amount: request.Amount, ReceiverName: request.ReceiverName, ReceiverPhone: request.ReceiverPhone,
@@ -509,7 +335,6 @@ func (a *orderHTTPAdapter) Update(ctx context.Context, userID int64, orderID str
if errors.As(err, &validationErr) {
return newOrderBadRequest(validationErr.Error())
}
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrForbidden) {
return orderapp.ErrForbidden
}
@@ -540,7 +365,7 @@ func (a *orderHTTPAdapter) Import(ctx context.Context, userID int64, rawOrders [
inputs = append(inputs, importOrderFromRaw(raw))
}
// result、err 保存应用层导入结果和错误。
result, err := a.services.Import.Import(ctx, userID, inputs)
result, err := a.services.Import(ctx, userID, inputs)
if err != nil {
return orderImportResult{}, err
}
@@ -596,7 +421,7 @@ type manualShipResult struct {
// ManualShip 执行状态确认或完整自动化发货,并集中处理逐单失败而不中断批次的规则。
func (a *orderHTTPAdapter) ManualShip(ctx context.Context, request manualShipRequest) (manualShipResult, error) {
// result 保存应用层手动发货结果。
result, err := a.services.ManualShip.ManualShip(ctx, orderapp.ManualShipRequest{UserID: request.UserID, OrderIDs: request.OrderIDs, ShipMode: request.ShipMode})
result, err := a.services.ManualShip(ctx, orderapp.ManualShipRequest{UserID: request.UserID, OrderIDs: request.OrderIDs, ShipMode: request.ShipMode})
if err != nil {
return manualShipResult{}, err
}
@@ -5,6 +5,7 @@ import (
"errors"
"testing"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
)
@@ -57,7 +58,7 @@ func TestServerOrderRuntimeAdapterReconciliationPort(t *testing.T) {
recorder = testCase.recorder
}
// runtime 保存当前场景构造的 Server 订单运行时适配器。
runtime := newServerOrderRuntime(nil, recorder)
runtime := adapter.NewOrderRuntimeAdapter(nil, nil, nil, nil, nil, nil, nil, nil, recorder)
// recordID、recordErr 保存适配器转发后的补偿写入结果。
recordID, recordErr := runtime.RecordOrderReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "本地订单写入失败")
// errMatches 表示当前返回错误是否符合场景预期;缺失依赖场景只校验错误文本。
+1 -1
View File
@@ -19,7 +19,7 @@ func (s *Server) mountPasswordLogin(r chi.Router) {
}
// passwordLoginApplication 返回当前 Server 绑定的密码登录应用服务。
func (s *Server) passwordLoginApplication() *accountapp.PasswordLoginService {
func (s *Server) passwordLoginApplication() PasswordLoginPort {
return s.applicationServiceSet().passwordLogin
}
@@ -1,78 +0,0 @@
package server
import (
"context"
"testing"
"xianyu-go/internal/adapter"
"xianyu-go/internal/xianyu/renew"
)
// serverPlatformQRFake 是 Server 平台访问器测试使用的二维码服务替身。
type serverPlatformQRFake struct{}
// GenerateQRCode 返回固定二维码数据,验证 Server 不参与平台协议编排。
func (serverPlatformQRFake) GenerateQRCode(context.Context) (string, string, error) {
return "session", "https://example.test/qr", nil
}
// GetSessionStatus 返回固定轮询状态,验证二维码能力可由显式依赖提供。
func (serverPlatformQRFake) GetSessionStatus(string) map[string]any {
return map[string]any{"status": "waiting"}
}
// CompleteVerification 返回脱敏验证结果,测试不输出真实凭证。
func (serverPlatformQRFake) CompleteVerification(context.Context, string) (string, string, error) {
return "masked-cookie", "account", nil
}
// TestServerPlatformAccessorsUseInjectedDependencies 验证生产访问器读取构造阶段的平台依赖。
func TestServerPlatformAccessorsUseInjectedDependencies(t *testing.T) {
// mtopClient、longLoginClient 和 qrService 保存本测试注入的客户端能力。
mtopClient := adapter.NewMTOPClient()
// longLoginClient 保存注入的长登录协议实现。
longLoginClient := renew.Service{}
// qrService 保存注入的二维码协议实现。
qrService := serverPlatformQRFake{}
// platformDependencies 保存通过 adapter 边界校验的平台能力集合。
platformDependencies, err := adapter.NewPlatformDependencies(mtopClient, longLoginClient, qrService)
if err != nil {
t.Fatalf("NewPlatformDependencies: %v", err)
}
// server 保存仅含平台能力的最小 HTTP 服务测试对象。
server := &Server{platformDependencies: platformDependencies}
if server.mtopClient() != mtopClient {
t.Fatalf("mtopClient 未返回显式注入客户端")
}
if server.longLoginClient() != longLoginClient {
t.Fatalf("longLoginClient 未返回显式注入客户端")
}
if server.qrLoginService() != qrService {
t.Fatalf("qrLoginService 未返回显式注入服务")
}
}
// TestServerPlatformAccessorsKeepLegacyTestAliases 验证兼容字段仍能替换平台能力以支撑现有测试。
func TestServerPlatformAccessorsKeepLegacyTestAliases(t *testing.T) {
// platformDependencies 保存生产默认平台能力,legacyMTop 和 legacyQR 保存旧测试替身。
platformDependencies, err := adapter.NewDefaultPlatformDependencies(nil)
if err != nil {
t.Fatalf("NewDefaultPlatformDependencies: %v", err)
}
// legacyMTop 保存仅用于兼容测试注入的 MTOP 客户端。
legacyMTop := adapter.NewMTOPClient()
// legacyQR 保存仅用于兼容测试注入的二维码服务。
legacyQR := serverPlatformQRFake{}
// legacyLongLogin 保存仅用于兼容测试注入的长登录客户端。
legacyLongLogin := renew.Service{}
// server 保存同时包含新边界和旧测试字段的过渡期对象。
server := &Server{
platformDependencies: platformDependencies,
MTop: legacyMTop,
CookieRenew: legacyLongLogin,
QRLogin: legacyQR,
}
if server.mtopClient() != legacyMTop || server.longLoginClient() != legacyLongLogin || server.qrLoginService() != legacyQR {
t.Fatalf("旧测试兼容字段未优先覆盖平台访问器")
}
}
@@ -4,7 +4,6 @@ import (
"context"
"testing"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
)
@@ -15,61 +14,32 @@ type serverPlatformCredentialPortFake struct {
}
// LoadPlatformDetail 返回测试平台凭证视图。
func (f serverPlatformCredentialPortFake) LoadPlatformDetail(context.Context, string) (*accountapp.CredentialDetail, error) {
return f.detail, nil
func (fake serverPlatformCredentialPortFake) LoadPlatformDetail(context.Context, string) (*accountapp.CredentialDetail, error) {
return fake.detail, nil
}
// TestLoadCookiePlatformDetailRequiresCredentialPort 验证平台运行时读取不会在缺少应用 Port 时直接访问 Store。
// TestLoadCookiePlatformDetailRequiresCredentialPort 验证缺少应用 Port 时 Server 不会绕过边界读取数据库。
func TestLoadCookiePlatformDetailRequiresCredentialPort(t *testing.T) {
// srv 是仅装配空账号登录服务的测试 Server,模拟凭证适配器缺失场景。
srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}}
// loadErr 保存缺少凭证 Port 时的平台视图读取错误。
_, loadErr := srv.loadCookiePlatformDetail(context.Background(), "cid")
if loadErr == nil {
// server 是故意缺失平台凭证 Port 的 transport 实例。
server := &Server{applications: NewApplicationPorts(ApplicationPortsInput{})}
// loadErr 是缺失 Port 时阻止 Server 越过应用边界的预期错误。
if _, loadErr := server.loadCookiePlatformDetail(context.Background(), "cid"); loadErr == nil {
t.Fatal("缺少凭证 Port 时不应继续读取平台运行视图")
}
}
// TestLoadCookiePlatformDetailUsesCredentialApplication 验证平台运行视图通过应用 Port 读取。
// TestLoadCookiePlatformDetailUsesCredentialApplication 验证平台运行时读取只通过应用 Port。
func TestLoadCookiePlatformDetailUsesCredentialApplication(t *testing.T) {
// service 是绑定最小凭证读取端口的平台应用服务。
// service、serviceErr 分别是测试凭证应用服务及其构造错误。
service, serviceErr := accountapp.NewPlatformCredentialService(serverPlatformCredentialPortFake{detail: &accountapp.CredentialDetail{ID: "cid", UserID: 9, Value: "sid=masked"}})
if serviceErr != nil {
t.Fatalf("构造凭证服务失败: %v", serviceErr)
}
// srv 是只装配平台凭证应用服务的测试 Server。
srv := &Server{applications: &applicationServices{platformCredentials: service}}
// detail、loadErr 保存应用 Port 返回的平台视图及错误。
detail, loadErr := srv.loadCookiePlatformDetail(context.Background(), "cid")
// server 是仅通过凭证应用 Port 访问平台运行视图的 transport 实例。
server := &Server{applications: NewApplicationPorts(ApplicationPortsInput{PlatformCredentials: service})}
// detail、loadErr 分别是应用层返回的脱敏凭证视图及读取错误。
detail, loadErr := server.loadCookiePlatformDetail(context.Background(), "cid")
if loadErr != nil || detail == nil || detail.ID != "cid" || detail.Value == "" {
t.Fatalf("平台凭证视图读取异常: detail=%+v err=%v", detail, loadErr)
}
}
// TestPersistMTopCookieSessionRequiresCredentialPort 验证 MTOP Cookie 会话写回通过凭证 Port 而非直接访问 Store。
func TestPersistMTopCookieSessionRequiresCredentialPort(t *testing.T) {
// srv 是仅装配空账号登录服务的测试 Server,模拟写回适配器缺失场景。
srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}}
// detail 是不含登录密码的兼容平台凭证模型。
detail := &accountapp.CredentialDetail{ID: "cid", Value: "sid=old", MetadataJSON: "{}"}
// ctx、session 保存发生权威 Cookie 变化的 MTOP 会话。
ctx, session := adapter.WithFlatCookieSession(context.Background(), detail.Value)
session.ReplaceSnapshot([]adapter.BrowserCookie{{Name: "sid", Value: "new", Domain: ".goofish.com", Path: "/"}})
// value、changed、handled、persistErr 保存会话写回结果及其错误阶段。
_, changed, handled, persistErr := srv.persistMTopCookieSessionLocked(ctx, detail, session)
if !changed || !handled || persistErr == nil {
t.Fatalf("缺少凭证 Port 时应报告写回错误: changed=%v handled=%v err=%v", changed, handled, persistErr)
}
}
// TestPlatformCredentialSessionPortIsAvailable 验证平台会话写回通过专用最小端口暴露。
func TestPlatformCredentialSessionPortIsAvailable(t *testing.T) {
// srv、cleanup 保存完整应用装配的测试 Server 及资源清理函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// sessionPort 保存仅包含 Cookie 写回能力的平台会话端口。
sessionPort := srv.platformCredentialSessionPort()
if sessionPort == nil {
t.Fatal("完整应用装配应提供平台会话写回端口")
}
}
@@ -0,0 +1,332 @@
package server
import (
"context"
"errors"
"sync"
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
lifecycleapp "xianyu-go/internal/application/lifecycle"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/chat"
)
// testServerManagers 保存仅供测试夹具访问的账号运行时;生产 Server 不持有该对象。
var testServerManagers sync.Map
// testServerPlatforms 保存仅供测试夹具替换的平台能力;生产 Server 不保存该对象。
var testServerPlatforms sync.Map
// testServerBatchLifecycle 保存测试需要观测的批量发布恢复组件;生产 Server 不持有 worker。
var testServerBatchLifecycle sync.Map
// testServerChats 保存测试构造时的聊天领域事件中心,生产 Server 不持有该实现。
var testServerChats sync.Map
// testServerOrderServices 保存仅供生命周期测试访问的订单服务集合;生产 Server 不持有该对象。
var testServerOrderServices sync.Map
// testBatchLifecycle 是测试调用组合层批量恢复组件的窄句柄。
type testBatchLifecycle struct {
// start 启动恢复扫描。
start func(context.Context) error
// close 取消并等待恢复组件。
close func(context.Context) error
}
// testPlatformPort 是测试专用的可变平台 Port,允许单个测试替换客户端而不污染生产 Server 状态。
type testPlatformPort struct {
// mu 保护测试过程中可变的平台客户端引用。
mu sync.RWMutex
// mtop 保存当前测试使用的 MTOP 客户端。
mtop adapter.MTOPClient
// longLogin 保存当前测试使用的长登录客户端。
longLogin adapter.LongLoginClient
// qr 保存当前测试使用的二维码登录客户端。
qr adapter.QRLoginService
}
// testOrdersTransport 将测试组合根订单服务集合投影为 Server 的订单 Port。
type testOrdersTransport struct {
// services 是测试组合根已经完成构造的订单服务集合。
services *orderapp.ServiceSet
}
// RefreshSingle 转发测试的单订单刷新用例。
func (transport testOrdersTransport) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderapp.SingleRefreshResult, error) {
return transport.services.Refresh.RefreshSingle(ctx, userID, orderID)
}
// Refresh 转发测试的批量订单刷新用例。
func (transport testOrdersTransport) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderapp.RefreshResult, error) {
return transport.services.Refresh.Refresh(ctx, userID, cookieID, status)
}
// List 转发测试的订单列表用例。
func (transport testOrdersTransport) List(ctx context.Context, query orderapp.ListQuery) (orderapp.ListResult, error) {
return transport.services.List.List(ctx, query)
}
// Get 转发测试的订单详情用例。
func (transport testOrdersTransport) Get(ctx context.Context, userID int64, orderID string) (*orderapp.Order, error) {
return transport.services.Detail.Get(ctx, userID, orderID)
}
// GetView 转发测试的订单详情视图用例。
func (transport testOrdersTransport) GetView(ctx context.Context, userID int64, orderID string) (orderapp.DetailResult, error) {
return transport.services.Detail.GetView(ctx, userID, orderID)
}
// Delete 转发测试的订单删除用例。
func (transport testOrdersTransport) Delete(ctx context.Context, userID int64, orderID string) error {
return transport.services.Delete.Delete(ctx, userID, orderID)
}
// Update 转发测试的订单更新用例。
func (transport testOrdersTransport) Update(ctx context.Context, userID int64, orderID string, request orderapp.UpdateRequest) error {
return transport.services.Update.Update(ctx, userID, orderID, request)
}
// Import 转发测试的订单导入用例。
func (transport testOrdersTransport) Import(ctx context.Context, userID int64, inputs []orderapp.ImportOrder) (orderapp.ImportResult, error) {
return transport.services.Import.Import(ctx, userID, inputs)
}
// ManualShip 转发测试的订单手动发货用例。
func (transport testOrdersTransport) ManualShip(ctx context.Context, request orderapp.ManualShipRequest) (orderapp.ManualShipResult, error) {
return transport.services.ManualShip.ManualShip(ctx, request)
}
// newTestPlatformPort 将生产平台 Port 包装为可替换的测试 Port。
func newTestPlatformPort(platform *adapter.PlatformDependencies) *testPlatformPort {
if platform == nil {
return &testPlatformPort{}
}
return &testPlatformPort{mtop: platform.MTOPClient(), longLogin: platform.LongLoginClient(), qr: platform.QRLoginService()}
}
// MTOPClient 返回当前测试注入的 MTOP 客户端。
func (port *testPlatformPort) MTOPClient() adapter.MTOPClient {
port.mu.RLock()
defer port.mu.RUnlock()
return port.mtop
}
// LongLoginClient 返回当前测试注入的长登录客户端。
func (port *testPlatformPort) LongLoginClient() adapter.LongLoginClient {
port.mu.RLock()
defer port.mu.RUnlock()
return port.longLogin
}
// QRLoginService 返回当前测试注入的二维码登录客户端。
func (port *testPlatformPort) QRLoginService() adapter.QRLoginService {
port.mu.RLock()
defer port.mu.RUnlock()
return port.qr
}
// GenerateQRCode 通过当前测试客户端生成二维码,使替身替换在已构造的组合层 Port 中立即生效。
func (port *testPlatformPort) GenerateQRCode(ctx context.Context) (string, string, error) {
// client 是当前测试用二维码客户端,读取后不持有 Port 锁执行外部调用。
client := port.QRLoginService()
if client == nil {
return "", "", errors.New("测试二维码客户端未设置")
}
return client.GenerateQRCode(ctx)
}
// GetSessionStatus 通过当前测试客户端读取二维码会话状态,使状态替身保持可替换。
func (port *testPlatformPort) GetSessionStatus(sessionID string) map[string]any {
// client 是当前测试用二维码客户端,读取后不持有 Port 锁执行平台查询。
client := port.QRLoginService()
if client == nil {
return nil
}
return client.GetSessionStatus(sessionID)
}
// CompleteVerification 通过当前测试客户端完成二维码风控验证,使失败替身能覆盖组合层调用。
func (port *testPlatformPort) CompleteVerification(ctx context.Context, sessionID string) (string, string, error) {
// client 是当前测试用二维码客户端,读取后不持有 Port 锁执行验证请求。
client := port.QRLoginService()
if client == nil {
return "", "", errors.New("测试二维码客户端未设置")
}
return client.CompleteVerification(ctx, sessionID)
}
// mutableTestPlatform 返回测试 Server 装配的可变平台 Port;非测试构造对象不提供替换能力。
func mutableTestPlatform(server *Server) *testPlatformPort {
// value、ok 分别表示测试组合根登记的平台 Port 及其存在状态。
value, ok := testServerPlatforms.Load(server)
if !ok {
return nil
}
// port、ok 分别是登记对象转换出的可变测试平台 Port 及其类型匹配结果。
port, ok := value.(*testPlatformPort)
if !ok {
return nil
}
return port
}
// setTestMTop 替换测试 Server 使用的 MTOP 客户端。
func setTestMTop(server *Server, client adapter.MTOPClient) {
// port 是当前测试 Server 的可变平台 Port;非测试对象保持无副作用。
if port := mutableTestPlatform(server); port != nil {
port.mu.Lock()
port.mtop = client
port.mu.Unlock()
}
}
// testMTop 返回测试 Server 当前注入的 MTOP 客户端,供暂存和恢复替身时保持同一 Port。
func testMTop(server *Server) adapter.MTOPClient {
// port 是当前测试 Server 的可变平台 Port;非测试对象不提供客户端。
if port := mutableTestPlatform(server); port != nil {
return port.MTOPClient()
}
return nil
}
// setTestCookieRenew 替换测试 Server 使用的长登录客户端。
func setTestCookieRenew(server *Server, client adapter.LongLoginClient) {
// port 是当前测试 Server 的可变平台 Port;非测试对象保持无副作用。
if port := mutableTestPlatform(server); port != nil {
port.mu.Lock()
port.longLogin = client
port.mu.Unlock()
}
}
// setTestQRLogin 替换测试 Server 使用的二维码登录客户端。
func setTestQRLogin(server *Server, client adapter.QRLoginService) {
// port 是当前测试 Server 的可变平台 Port;非测试对象保持无副作用。
if port := mutableTestPlatform(server); port != nil {
port.mu.Lock()
port.qr = client
port.mu.Unlock()
}
}
// testQRLogin 返回测试 Server 当前注入的二维码登录客户端,供测试直接检查替身调用结果。
func testQRLogin(server *Server) adapter.QRLoginService {
// port 是当前测试 Server 的可变平台 Port;非测试对象不提供客户端。
if port := mutableTestPlatform(server); port != nil {
return port.QRLoginService()
}
return nil
}
// registerTestAccountManager 登记测试组合根创建的账号管理器,避免为测试向生产 Server 回填字段。
func registerTestAccountManager(server *Server, manager *account.Manager) {
if server != nil && manager != nil {
testServerManagers.Store(server, manager)
}
}
// registerTestChatDomain 登记聊天领域事件中心,供 WebSocket 行为测试发布确定性事件。
func registerTestChatDomain(server *Server, service *chat.Service) {
if server != nil && service != nil {
testServerChats.Store(server, service)
}
}
// registerTestOrderServices 登记生命周期测试所需的订单服务集合。
func registerTestOrderServices(server *Server, services *orderapp.ServiceSet) {
if server != nil && services != nil {
testServerOrderServices.Store(server, services)
}
}
// testOrderServices 返回测试组合根创建的订单服务集合;生产 Server 不提供该访问路径。
func testOrderServices(server *Server) *orderapp.ServiceSet {
// value、ok 分别是测试组合根登记的订单服务对象及其存在状态。
value, ok := testServerOrderServices.Load(server)
if !ok {
return nil
}
// services、ok 分别是类型安全转换后的订单服务集合及其匹配结果。
services, ok := value.(*orderapp.ServiceSet)
if !ok {
return nil
}
return services
}
// testChatDomain 返回测试组合根登记的聊天事件中心。
func testChatDomain(server *Server) *chat.Service {
// value、ok 分别是测试组合根登记的聊天领域对象及其存在状态。
value, ok := testServerChats.Load(server)
if !ok {
return nil
}
// service 是转换后的聊天领域服务,类型不匹配时保留 nil 供测试自行失败。
service, _ := value.(*chat.Service)
return service
}
// registerTestPlatform 登记测试组合根创建的可变平台 Port,避免将替身回填到生产 Server。
func registerTestPlatform(server *Server, platform *testPlatformPort) {
if server != nil && platform != nil {
testServerPlatforms.Store(server, platform)
}
}
// registerTestBatchLifecycle 从组合层生命周期清单登记批量恢复组件,避免测试反向读取 Server worker。
func registerTestBatchLifecycle(server *Server, components []lifecycleapp.NamedComponent) {
// component 是按组合层启动顺序遍历的测试生命周期组件。
for _, component := range components {
if component.Name == "publish-batch-workers" && component.Component != nil {
testServerBatchLifecycle.Store(server, testBatchLifecycle{start: component.Component.Start, close: component.Component.Close})
return
}
}
}
// startTestBatchRecovery 启动测试 Server 对应的组合层批量恢复组件。
func startTestBatchRecovery(server *Server, ctx context.Context) error {
// value、ok 分别是已登记批量恢复组件及其存在状态。
value, ok := testServerBatchLifecycle.Load(server)
if !ok {
return errors.New("测试批量恢复组件未登记")
}
// lifecycle、ok 分别是类型安全转换后的批量恢复生命周期及其匹配结果。
lifecycle, ok := value.(testBatchLifecycle)
if !ok || lifecycle.start == nil {
return errors.New("测试批量恢复组件无效")
}
return lifecycle.start(ctx)
}
// closeTestBatchRecovery 取消并等待测试 Server 对应的组合层批量恢复组件。
func closeTestBatchRecovery(server *Server, ctx context.Context) error {
// value、ok 分别是已登记批量恢复组件及其存在状态。
value, ok := testServerBatchLifecycle.Load(server)
if !ok {
return errors.New("测试批量恢复组件未登记")
}
// lifecycle、ok 分别是类型安全转换后的批量恢复生命周期及其匹配结果。
lifecycle, ok := value.(testBatchLifecycle)
if !ok || lifecycle.close == nil {
return errors.New("测试批量恢复组件无效")
}
return lifecycle.close(ctx)
}
// testAccountManager 返回测试组合根登记的账号管理器;调用方必须在标准测试夹具上使用。
func testAccountManager(server *Server) *account.Manager {
// manager、ok 分别表示已登记的测试账号管理器及其存在状态。
manager, ok := testServerManagers.Load(server)
if !ok {
return nil
}
// typedManager、ok 分别表示映射值的类型断言结果及其有效性。
typedManager, ok := manager.(*account.Manager)
if !ok {
return nil
}
return typedManager
}
+14 -9
View File
@@ -160,14 +160,14 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 注入 mock mtop:所有请求返回非成功 ret(触发 PublishError)。
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"ret":["FAIL_SYS_PERMISSION::无发布权限"],"data":{}}`)),
Request: req,
}, nil
}))
})))
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -246,7 +246,7 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
select {
case <-req.Context().Done():
return nil, req.Context().Err()
@@ -258,7 +258,7 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"itemId":"late-item"}}`)),
Request: req,
}, nil
}))
})))
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -338,7 +338,7 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
// publishedCategory 用于本次流程后续判断的published分类
var publishedCategory map[string]any
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
setTestMTop(srv, withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// u 用于本次流程后续判断的u
u := req.URL.String()
// body 用于本次流程后续判断的请求体
@@ -365,7 +365,7 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
}))
})))
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -521,7 +521,7 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
}))
// port 将测试平台客户端接入批量远端应用端口;已保存远端结果时不会再次发起平台请求。
port := adapter.NewItemBatchPublishPort(store, func() mtop.Client { return client }, srv.Logger, srv.updateRunningCookie, func(callCtx context.Context, cookieID string, callErr error) {
srv.recoverExpiredMTOPSession(callCtx, cookieID, callErr)
srv.recoverExpiredSession(callCtx, cookieID, callErr)
}, readBatchImageFile, downloadImageURL)
// localService 保存本地商品和批次成功检查点收口能力。
localService, serviceErr := srv.newBatchLocalPublishService()
@@ -530,8 +530,13 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
}
// applicationRow 保存恢复测试所需的非敏感批次明细模型。
applicationRow := itemapp.BatchRow{ID: rows[0].ID, BatchID: rows[0].BatchID, RowNo: rows[0].RowNo, CookieID: rows[0].CookieID, Title: rows[0].Title, Description: rows[0].Description, Price: rows[0].Price, OriginalPrice: rows[0].OriginalPrice, Quantity: rows[0].Quantity, PostageMode: rows[0].PostageMode, Postage: rows[0].Postage, ImagesJSON: rows[0].ImagesJSON, CategoryJSON: rows[0].CategoryJSON, AutomationJSON: rows[0].AutomationJSON, RawJSON: rows[0].RawJSON, ItemID: rows[0].ItemID, ItemURL: rows[0].ItemURL, Status: rows[0].Status, ErrorMessage: rows[0].ErrorMessage, FailureKind: rows[0].FailureKind, WorkerToken: rows[0].WorkerToken, CreatedAt: rows[0].CreatedAt, UpdatedAt: rows[0].UpdatedAt}
// publisher、publisherErr 分别保存已装配的批量发布适配器及其组合错误。
publisher, publisherErr := adapter.NewItemBatchPublisher(port, localService)
if publisherErr != nil {
t.Fatalf("构造批量发布适配器: %v", publisherErr)
}
// err 保存应用层批量发布适配器的恢复结果。
err = (serverBatchPublisher{remotePort: port, localService: localService}).PublishRow(ctx, admin.ID, applicationRow, "worker-2", nil)
err = publisher.PublishRow(ctx, admin.ID, applicationRow, "worker-2", nil)
if err != nil {
t.Fatalf("resume local persistence: %v", err)
}
@@ -566,7 +571,7 @@ func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
t.Fatal(err)
}
// err 保存应用层批量恢复扫描的错误。
if err := srv.applications.itemBatchCoordinator.RunRecovery(ctx); err != nil {
if err := startTestBatchRecovery(srv, ctx); err != nil {
t.Fatalf("批量恢复扫描: %v", err)
}
// deadline 用于本次流程后续判断的deadline
+3 -4
View File
@@ -15,7 +15,7 @@ func TestAPIContractQRLoginGenerationFailure(t *testing.T) {
// srv 是用于验证二维码生成错误契约的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{generateErr: errors.New("二维码服务不可用")}
setTestQRLogin(srv, &fakeQRLoginService{generateErr: errors.New("二维码服务不可用")})
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
@@ -45,8 +45,7 @@ func TestAPIContractQRLoginPersistFailure(t *testing.T) {
// srv 是用于验证扫码持久化错误契约的 HTTP 测试服务。
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "success"}}
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{"status": "success"}})
ownQRSession(t, srv, store, "persist-failure")
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
@@ -77,7 +76,7 @@ func TestAPIContractQRVerificationFailure(t *testing.T) {
// srv 是用于验证扫码风控错误契约的 HTTP 测试服务。
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{completeErr: errors.New("验证服务不可用")}
setTestQRLogin(srv, &fakeQRLoginService{completeErr: errors.New("验证服务不可用")})
ownQRSession(t, srv, store, "verification-failure")
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
+17 -24
View File
@@ -39,7 +39,7 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
generateCtx, cancel := context.WithTimeout(r.Context(), qrLoginGenerateTimeout)
defer cancel()
// qrService 是通过显式平台依赖边界取得的二维码服务;为空时拒绝执行平台调用。
qrService := s.qrLoginService()
qrService := s.qrLoginApplication()
if qrService == nil {
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
@@ -66,12 +66,12 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
return
}
// qrSessions 保存扫码会话所有权;平台二维码服务只负责平台会话本身。
qrSessions := s.accountLoginApplication().qrSessions
if qrSessions == nil {
accountLogin := s.accountLoginApplication()
if accountLogin == nil {
writeErr(w, http.StatusInternalServerError, "扫码会话服务未初始化")
return
}
qrSessions.Register(sessionID, sess.UserID, time.Now().UTC())
accountLogin.RegisterQRSession(sessionID, sess.UserID, time.Now().UTC())
writeJSON(w, http.StatusOK, qrLoginGenerateResponse{
Success: true, SessionID: sessionID, QRCodeURL: qrCodeURL,
// 生成成功响应只暴露会话标识和二维码地址。
@@ -91,7 +91,7 @@ func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
return
}
// qrService 是已完成平台依赖校验的二维码服务。
qrService := s.qrLoginService()
qrService := s.qrLoginApplication()
if qrService == nil {
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
@@ -113,7 +113,7 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
return
}
// qrService 是已完成平台依赖校验的二维码服务。
qrService := s.qrLoginService()
qrService := s.qrLoginApplication()
if qrService == nil {
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
@@ -160,7 +160,7 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
return
}
// qrService 是已完成平台依赖校验的二维码服务。
qrService := s.qrLoginService()
qrService := s.qrLoginApplication()
if qrService == nil {
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
@@ -240,17 +240,17 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s
return false
}
// qrSessions 负责所有权、过期判断和幂等状态清理,HTTP 层不再持有可变会话表。
qrSessions := s.accountLoginApplication().qrSessions
if qrSessions == nil {
accountLogin := s.accountLoginApplication()
if accountLogin == nil {
writeErr(w, http.StatusInternalServerError, "扫码会话服务未初始化")
return false
}
// err 保存扫码会话所有权校验结果。
if err := qrSessions.Authorize(sessionID, sess.UserID); err != nil {
if err := accountLogin.AuthorizeQRSession(sessionID, sess.UserID); err != nil {
if errors.Is(err, accountapp.ErrQRLoginSessionNotFound) {
// cleaner、cleanable 分别表示平台会话清理器及其接口是否可用。
if cleaner, cleanable := s.qrLoginService().(interface{ DeleteSession(string) }); cleanable {
cleaner.DeleteSession(sessionID)
if qrService := s.qrLoginApplication(); qrService != nil {
qrService.DeleteSession(sessionID)
}
}
writeErr(w, http.StatusNotFound, "扫码会话不存在或已过期")
@@ -262,14 +262,14 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s
// cleanupQRLoginSessions 封装cleanupQR登录Sessions业务协调。
func (s *Server) cleanupQRLoginSessions() {
// qrSessions 提供应用层扫码会话过期清理能力。
qrSessions := s.accountLoginApplication().qrSessions
if qrSessions == nil {
accountLogin := s.accountLoginApplication()
if accountLogin == nil {
return
}
// expired 保存应用层报告的过期扫码会话标识。
expired := qrSessions.Cleanup(time.Now().UTC())
if // cleaner、ok 用于本次流程后续判断的cleaner、ok
cleaner, ok := s.qrLoginService().(interface{ DeleteSession(string) }); ok {
expired := accountLogin.CleanupQRSessions(time.Now().UTC())
// cleaner 是可选二维码平台会话清理 Port,仅用于释放已确认过期的远端会话。
if cleaner := s.qrLoginApplication(); cleaner != nil {
// id 表示当前遍历过程中的标识
for _, id := range expired {
cleaner.DeleteSession(id)
@@ -323,10 +323,3 @@ func qrStatus(result map[string]any) string {
status, _ := result["status"].(string)
return status
}
// qrString 封装qrString业务协调。
func qrString(result map[string]any, key string) string {
// value 用于本次流程后续判断的值
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
+16 -20
View File
@@ -67,7 +67,7 @@ func TestGenerateQRLogin(t *testing.T) {
defer cleanup()
// qr 用于本次流程后续判断的qr
qr := &fakeQRLoginService{}
srv.QRLogin = qr
setTestQRLogin(srv, qr)
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -104,7 +104,7 @@ func TestQRLoginSessionCannotBeReadByAnotherUser(t *testing.T) {
ok, err := store.Users.Create(context.Background(), "member", "member@example.com", "memberpw"); err != nil || !ok {
t.Fatalf("create member: ok=%v err=%v", ok, err)
}
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{"status": "waiting"}})
// h 用于本次流程后续判断的h
h := srv.Router()
// adminCookie 用于本次流程后续判断的admin登录凭证
@@ -148,11 +148,10 @@ func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{
"status": "success", "cookies": "unb=acc1; secret=value", "unb": "acc1",
"cookie_snapshot": []cookierefresh.BrowserCookie{{Name: "secret", Value: "value", Domain: ".goofish.com", Path: "/"}},
}}
}})
ownQRSession(t, srv, store, "redacted")
// h 用于本次流程后续判断的h
h := srv.Router()
@@ -192,10 +191,10 @@ func TestQRLoginSessionExpiresWithoutAnotherGenerateRequest(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{"status": "waiting"}})
// admin 用于本次流程后续判断的admin
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
srv.accountLoginApplication().qrSessions.Register("expired-session", admin.ID, time.Now().UTC().Add(-31*time.Minute))
srv.accountLoginApplication().RegisterQRSession("expired-session", admin.ID, time.Now().UTC().Add(-31*time.Minute))
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -216,7 +215,7 @@ func TestCheckQRLoginStatusEmptySession(t *testing.T) {
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{}
setTestQRLogin(srv, &fakeQRLoginService{})
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -240,7 +239,7 @@ func TestCompleteQRVerificationBadSession(t *testing.T) {
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{completeErr: errors.New("会话不存在")}
setTestQRLogin(srv, &fakeQRLoginService{completeErr: errors.New("会话不存在")})
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 用于本次流程后续判断的登录凭证
@@ -265,7 +264,7 @@ func ownQRSession(t *testing.T, srv *Server, store *db.Store, sessionID string)
if err != nil {
t.Fatalf("GetByUsername admin: %v", err)
}
srv.accountLoginApplication().qrSessions.Register(sessionID, admin.ID, time.Now().UTC())
srv.accountLoginApplication().RegisterQRSession(sessionID, admin.ID, time.Now().UTC())
}
// TestQRLoginStatusPersistsSuccessIdempotently 封装TestQR登录状态PersistsSuccessIdempotently业务协调。
@@ -273,8 +272,7 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{
"status": "success",
"cookies": "unb=qr-new; _m_h5_tk=qr-token;",
"unb": "qr-new",
@@ -282,9 +280,9 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
{Name: "unb", Value: "qr-new", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "qr-token", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
},
}}
}})
if // snapshot、ok 用于本次流程后续判断的snapshot、ok
snapshot, ok := adapter.CookieSnapshotsFromResult(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
snapshot, ok := adapter.CookieSnapshotsFromResult(testQRLogin(srv).GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
t.Fatalf("测试扫码 Cookie 快照异常: ok=%v snapshot=%+v", ok, snapshot)
}
ownQRSession(t, srv, store, "s1")
@@ -341,11 +339,10 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
defer cleanup()
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{
setTestQRLogin(srv, &fakeQRLoginService{
completeCookies: "unb=acc1; _m_h5_tk=qr-fresh;",
completeUNB: "acc1",
}
})
ownQRSession(t, srv, store, "s1")
if // err 用于本次流程后续判断的err
err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
@@ -398,11 +395,10 @@ func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{
setTestQRLogin(srv, &fakeQRLoginService{
completeCookies: "unb=scanned-other; _m_h5_tk=qr-fresh;",
completeUNB: "scanned-other",
}
})
ownQRSession(t, srv, store, "s-mismatch")
// h 用于本次流程后续判断的h
h := srv.Router()
+25 -123
View File
@@ -7,10 +7,6 @@ import (
"net/http"
"testing"
"time"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
)
// freeAddr 获取一个空闲 TCP 端口(立即释放,供测试绑定)。
@@ -84,14 +80,14 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
// ctx、cancel 用于本次流程后续判断的ctx、cancel
ctx, cancel := context.WithCancel(context.Background())
// err 表示测试批量恢复组件启动失败的原因。
if err := srv.applications.itemBatchCoordinator.StartRecovery(ctx); err != nil {
if err := startTestBatchRecovery(srv, ctx); err != nil {
t.Fatalf("启动批量发布恢复扫描器: %v", err)
}
cancel()
// done 用于本次流程后续判断的done
done := make(chan struct{})
go func() {
srv.applications.itemBatchCoordinator.Wait()
_ = closeTestBatchRecovery(srv, context.Background())
close(done)
}()
select {
@@ -101,121 +97,32 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
}
}
// TestNewRejectsMissingRequiredDependencies 确保 HTTP 服务构造阶段拒绝缺失核心依赖。
// TestNewRejectsMissingRequiredDependencies 确保 HTTP Server 只接受完整的不可变依赖快照。
func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
// err 是缺少基础设施容器时的构造校验错误。
if _, err := NewLegacyComposedServer(nil, nil, "", ":0", nil, nil, nil); err == nil {
t.Fatal("缺少基础设施容器时应返回构造错误")
// emptyErr 表示缺少认证、应用服务和基础设施端口时的构造校验失败。
if _, emptyErr := New(Dependencies{}); emptyErr == nil {
t.Fatal("缺少依赖快照时应返回构造错误")
}
// srv 是用于提供合法 Store 的测试服务;cleanup 负责释放测试数据库。
srv, store, cleanup := newTestServer(t)
// source、cleanup 提供已经按组合根完成构造的基线 Server。
source, _, cleanup := newTestServer(t)
defer cleanup()
if srv == nil {
t.Fatal("测试服务不应为空")
// missingApplications 保存故意移除应用服务集合后的构造输入。
missingApplications := Dependencies{
Auth: source.Auth, WebDir: source.WebDir, Addr: source.Addr, Logger: source.Logger,
DatabaseHealth: source.databaseHealth,
}
// authentication 保存构造校验需要的会话中间件依赖。
authentication := &auth.Service{Store: store}
// err 是缺少 Manager 时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, nil, "", ":0", nil, nil, nil); err == nil {
t.Fatal("缺少 account.Manager 时应返回构造错误")
// applicationsErr 表示构造阶段没有应用服务集合时的失败。
if _, applicationsErr := New(missingApplications); applicationsErr == nil {
t.Fatal("缺少应用服务集合时应返回构造错误")
}
// err 是缺少订单专用装配能力时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil); err == nil {
t.Fatal("缺少订单专用依赖时应返回构造错误")
// incompleteApplications 在容器存在但未绑定全部路由 Port 时也必须于启动前失败。
incompleteApplications := Dependencies{
Auth: source.Auth, WebDir: source.WebDir, Addr: source.Addr, Logger: source.Logger,
DatabaseHealth: source.databaseHealth, Applications: NewApplicationPorts(ApplicationPortsInput{}),
}
// orderDependencies 保存账号依赖缺失测试所需的合法订单装配能力。
orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store)
if orderDependencyErr != nil {
t.Fatalf("NewOrderDependencies: %v", orderDependencyErr)
}
// err 是缺少账号专用装配能力时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies)); err == nil {
t.Fatal("缺少账号专用依赖时应返回构造错误")
}
// accountDependencies 保存账号与订单依赖均合法时的商品依赖缺失测试输入。
accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store)
if accountDependencyErr != nil {
t.Fatalf("NewAccountDependencies: %v", accountDependencyErr)
}
// err 是缺少商品专用装配能力时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies)); err == nil {
t.Fatal("缺少商品专用依赖时应返回构造错误")
}
// err 是订单、账号和商品依赖齐全但平台客户端缺失时的构造校验错误。
itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store)
if itemDependencyErr != nil {
t.Fatalf("NewItemDependencies: %v", itemDependencyErr)
}
// platformDependencies 保存依赖缺失分支测试使用的显式平台能力。
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
if platformDependencyErr != nil {
t.Fatalf("NewPlatformDependencies: %v", platformDependencyErr)
}
// chatDependencies 保存平台缺失校验所需的聊天专用依赖。
chatDependencies := adapter.NewChatDependencies(store)
// systemDependencies 保存平台缺失校验所需的系统专用依赖。
systemDependencies := adapter.NewSystemDependencies(store)
// databaseHealth 是进程组合根提供给 Server 的数据库健康检查端口。
databaseHealth := systemDependencies.NewDatabaseHealth()
// automationDependencies 保存平台缺失校验所需的自动化专用依赖及构造错误。
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
if automationDependencyErr != nil {
t.Fatalf("NewAutomationDependencies: %v", automationDependencyErr)
}
// miscDependencies 保存平台缺失校验所需的杂项专用依赖及构造错误。
miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store)
if miscDependencyErr != nil {
t.Fatalf("NewMiscDependencies: %v", miscDependencyErr)
}
// adminSettingsDependencies 保存平台缺失校验所需的管理员设置依赖。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
if chatDependencies == nil || systemDependencies == nil || databaseHealth == nil || adminSettingsDependencies == nil {
t.Fatal("显式 Server 依赖构造失败")
}
// transportApplications 是构造失败测试使用的完整 transport-facing 服务集合。
transportApplications, transportApplicationsErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies,
MiscDependencies: miscDependencies,
AdminSettingsDependencies: adminSettingsDependencies,
AccountTaskRunner: adapter.NewAccountTaskRunner(nil),
ModelClient: adapter.NewAIModelClient(),
})
if transportApplicationsErr != nil {
t.Fatalf("NewTransportApplicationServices: %v", transportApplicationsErr)
}
// orderReconciliationRecovery 是完整构造路径需要的订单补偿扫描应用服务。
orderReconciliationRecovery, reconciliationErr := orderapp.NewReconciliationRecoveryCoordinator(systemDependencies.NewReconciliationService(nil))
if reconciliationErr != nil {
t.Fatalf("NewReconciliationRecoveryCoordinator: %v", reconciliationErr)
}
// err 是聊天或健康检查端口等显式依赖缺失时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies)); err == nil {
t.Fatal("缺少聊天或健康检查端口时应返回构造错误")
}
// err 是全部业务依赖齐全但遗漏健康检查端口时的构造错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少数据库健康检查端口时应返回构造错误")
}
// err 是缺少平台依赖注入时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications)); err == nil {
t.Fatal("缺少平台依赖时应返回构造错误")
}
// err 是缺少自动化专用依赖时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少自动化专用依赖时应返回构造错误")
}
// err 是缺少 transport 应用服务集合时的构造校验错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少 transport 应用服务集合时应返回构造错误")
}
// err 是全部基础设施依赖齐全但遗漏进程装配应用服务时的构造错误。
if _, err := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少订单补偿扫描应用服务时应返回构造错误")
}
// fullyConstructedServer、constructErr 分别是完整注入后的 HTTP 服务及构造错误。
fullyConstructedServer, constructErr := NewLegacyComposedServer(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
if constructErr != nil || fullyConstructedServer == nil {
t.Fatalf("完整依赖注入应构造成功: server=%v err=%v", fullyConstructedServer, constructErr)
// incompleteErr 是容器存在但缺少路由所需 Port 时的构造失败。
if _, incompleteErr := New(incompleteApplications); incompleteErr == nil {
t.Fatal("缺少必需应用 Port 时应返回构造错误")
}
}
@@ -226,14 +133,9 @@ func TestNewAcceptsPrebuiltApplicationSet(t *testing.T) {
defer cleanup()
// dependencies 将已有构造结果转换为不可变 Server 依赖快照。
dependencies := Dependencies{
Auth: source.Auth, Manager: source.Manager, WebDir: source.WebDir, Addr: source.Addr, Logger: source.Logger,
Automation: source.automation, Notifier: source.notifier, Chat: source.chat,
OrderDependencies: source.orderDependencies.(*adapter.OrderDependencies), AccountDependencies: source.accountDependencies.(*adapter.AccountDependencies),
ItemDependencies: source.itemDependencies.(*adapter.ItemDependencies), ChatDependencies: source.chatDependencies,
AutomationDependencies: source.automationDependencies, TransportApplications: source.transportApplications,
PlatformDependencies: source.platformDependencies, DatabaseHealth: source.databaseHealth,
OrderReconciliationRecovery: source.orderReconciliationRecovery, Applications: source.applications,
ApplicationLifecycle: source.applicationLifecycle,
Auth: source.Auth, WebDir: source.WebDir, Addr: source.Addr, Logger: source.Logger,
DatabaseHealth: source.databaseHealth,
Applications: source.applications,
}
// serverInstance、constructErr 保存纯注入入口的构造结果。
serverInstance, constructErr := New(dependencies)
+25 -417
View File
@@ -21,121 +21,26 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
lifecycleapp "xianyu-go/internal/application/lifecycle"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/chat"
"xianyu-go/internal/logging"
"xianyu-go/internal/notify"
appversion "xianyu-go/internal/version"
"xianyu-go/internal/webui"
)
// qrLoginService 用于本次流程后续判断的qr登录Service
type qrLoginService = adapter.QRLoginService
// qrLoginPersistence 用于本次流程后续判断的qr登录Persistence
type qrLoginPersistence struct {
AccountID string
IsNew bool
UserID int64
CreatedAt time.Time
}
// ServerOption 是 Server 构造阶段应用可选依赖的配置函数。
type ServerOption func(*Server)
// Dependencies 是 HTTP Server 的不可变组合依赖;应用服务和生命周期组件必须在进入 Server 前完成装配。
// 旧的 ServerOption 构造器仅作为迁移期间兼容入口,生产代码应使用 New。
type Dependencies struct {
// Auth 是负责会话解析和认证中间件的应用认证服务。
Auth *auth.Service
// Manager 是账号运行时的只读 transport 端口兼容依赖;新 handler 不应直接调用其业务方法。
Manager *account.Manager
// WebDir 是嵌入或外置前端静态资源目录。
WebDir string
// Addr 是 HTTP 监听地址,默认由 cmd/server 提供 :59188。
Addr string
// Logger 是 Server 使用的结构化日志器。
Logger *slog.Logger
// Automation 是历史兼容的自动化运行时引用,新服务应通过应用 Port 访问。
Automation *automation.Center
// Notifier 是历史兼容的通知运行时引用,新服务应通过通知应用 Port 访问。
Notifier *notify.Notifier
// Chat 是聊天 transport 使用的领域事件服务。
Chat *chat.Service
// OrderDependencies 是订单应用适配器集合,仅允许在组合根构造。
OrderDependencies *adapter.OrderDependencies
// AccountDependencies 是账号应用适配器集合,仅允许在组合根构造。
AccountDependencies *adapter.AccountDependencies
// ItemDependencies 是商品应用适配器集合,仅允许在组合根构造。
ItemDependencies *adapter.ItemDependencies
// ChatDependencies 是聊天应用适配器集合,仅允许在组合根构造。
ChatDependencies *adapter.ChatDependencies
// AutomationDependencies 是自动化应用适配器集合,仅允许在组合根构造。
AutomationDependencies *adapter.AutomationDependencies
// TransportApplications 是已构造的 transport-facing 应用服务集合。
TransportApplications *adapter.TransportApplicationServices
// PlatformDependencies 是平台客户端集合,Server 不负责创建其中的实现。
PlatformDependencies *adapter.PlatformDependencies
// DatabaseHealth 是数据库健康检查应用 Port。
DatabaseHealth DatabaseHealthPort
// OrderReconciliationRecovery 是订单补偿恢复生命周期组件。
OrderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
// Applications 是完整应用服务集合;缺失时构造必须失败。
Applications *ApplicationServices
// ApplicationLifecycle 是由 cmd 拥有的生命周期协调器,仅供请求 Context 读取。
ApplicationLifecycle *lifecycleapp.Coordinator
}
// orderDependencyFactory 是订单装配所需的最小能力集合;Server 不持有通用 Store 工厂。
type orderDependencyFactory interface {
// NewOrderRepository 创建订单读写仓储。
NewOrderRepository() *adapter.OrderRepository
// NewOrderReconciliationRepository 创建订单补偿记录仓储。
NewOrderReconciliationRepository() *adapter.OrderReconciliationRepository
// NewOrderRuntime 创建订单平台运行时适配器。
NewOrderRuntime(adapter.OrderRuntimeHooks, orderapp.ReconciliationRecorder, *slog.Logger) *adapter.OrderRuntime
// NewOrderRefreshJobRepository 创建订单刷新任务仓储。
NewOrderRefreshJobRepository() orderapp.RefreshJobRepository
}
// accountDependencyFactory 是账号应用装配所需的最小能力集合;Server 不持有通用 Store 工厂。
type accountDependencyFactory interface {
// NewAccountLoginRepository 创建账号凭证与资料仓储。
NewAccountLoginRepository() *adapter.AccountLoginRepository
// NewAccountSettingsRepository 创建账号设置仓储。
NewAccountSettingsRepository() *adapter.AccountSettingsRepository
// NewAccountSummaryRepository 创建账号摘要仓储。
NewAccountSummaryRepository() *adapter.AccountSummaryRepository
// NewQRLoginRepository 创建扫码登录凭证端口。
NewQRLoginRepository() accountapp.QRLoginRepository
// NewAuthenticationRepository 创建用户认证仓储。
NewAuthenticationRepository() *adapter.AuthenticationRepository
// NewAccountLoginAuditRepository 创建账号登录审计仓储。
NewAccountLoginAuditRepository() *adapter.AccountLoginAuditRepository
}
// itemDependencyFactory 是商品应用装配所需的最小能力集合;Server 不持有通用 Store 工厂。
type itemDependencyFactory interface {
// NewItemBatchRepository 创建批量发布状态仓储。
NewItemBatchRepository() *adapter.ItemBatchRepository
// NewItemBatchPreviewPort 创建批量预检端口。
NewItemBatchPreviewPort() *adapter.ItemBatchPreviewPort
// NewItemBatchPublishPort 创建批量远端发布端口。
NewItemBatchPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error), adapter.ReadPublishImageFile, adapter.DownloadPublishImageURL) *adapter.ItemBatchPublishPort
// NewItemPublishPort 创建单商品发布端口。
NewItemPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error) bool) *adapter.ItemPublishPort
// NewItemPublishRepository 创建单商品发布结果仓储。
NewItemPublishRepository() *adapter.ItemPublishRepository
// NewItemCatalogRepository 创建商品目录仓储。
NewItemCatalogRepository() *adapter.ItemCatalogRepository
// NewItemSyncRepository 创建商品同步端口。
NewItemSyncRepository(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemSyncRepository
// Applications 是完整的 transport 应用 Port 快照;缺失时构造必须失败。
Applications *ApplicationPorts
}
// DatabaseHealthPort 定义健康检查需要的最小数据库连通性能力。
@@ -144,44 +49,15 @@ type DatabaseHealthPort interface {
Ping(context.Context) error
}
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
// Server 用于本次流程后续判断的Server
// Server 聚合 HTTP transport 依赖,不持有账号运行时或业务 worker 实现。
type Server struct {
// orderDependencies 保存订单应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
orderDependencies orderDependencyFactory
// accountDependencies 保存账号应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
accountDependencies accountDependencyFactory
// itemDependencies 保存商品应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
itemDependencies itemDependencyFactory
// chatDependencies 保存聊天应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
chatDependencies *adapter.ChatDependencies
// orderReconciliationRecovery 是进程装配层创建后注入的订单补偿扫描应用生命周期组件。
orderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
// automationDependencies 保存自动化、默认回复和关键词的显式装配能力。
automationDependencies *adapter.AutomationDependencies
// transportApplications 保存进程装配层创建的 transport-facing 应用服务集合。
transportApplications *adapter.TransportApplicationServices
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
notifier *notify.Notifier
chat *chat.Service
// platformDependencies 保存构造阶段校验通过的平台能力;生产调用必须通过下方访问器读取。
platformDependencies *adapter.PlatformDependencies
// MTop 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。
MTop adapter.MTOPClient
// CookieRenew 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。
CookieRenew adapter.LongLoginClient
// QRLogin 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。
QRLogin qrLoginService
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
// applications 保存统一装配的应用服务实例。
applications *applicationServices
// applicationLifecycle 保存由 cmd 拥有的应用生命周期协调器;Server 只读取其共享 Context。
applicationLifecycle *lifecycleapp.Coordinator
// Auth 是 HTTP 会话认证中间件依赖。
Auth *auth.Service
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
// applications 保存构造期注入的 transport 应用 Port 快照。
applications *ApplicationPorts
// databaseHealth 提供健康检查所需的数据库探测能力,避免 handler 直接触碰 SQL 连接。
databaseHealth DatabaseHealthPort
// backgroundMu 保护 Server 后台任务计数与完成信号,避免关闭等待创建不可取消的等待 goroutine。
@@ -205,136 +81,21 @@ type Server struct {
initializationMu sync.Mutex
}
// WithChatService 注入聊天持久化与实时事件中心。
func WithChatService(service *chat.Service) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入聊天服务的 HTTP 服务实例。
server.chat = service
}
}
// WithOrderDependencies 注入订单应用服务所需的专用适配器工厂。
func WithOrderDependencies(dependencies *adapter.OrderDependencies) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入订单专用依赖的 HTTP 服务实例。
if dependencies == nil {
server.orderDependencies = nil
return
}
server.orderDependencies = dependencies
}
}
// WithAccountDependencies 注入账号应用服务所需的专用适配器工厂。
func WithAccountDependencies(dependencies *adapter.AccountDependencies) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入账号专用依赖的 HTTP 服务实例。
if dependencies == nil {
server.accountDependencies = nil
return
}
server.accountDependencies = dependencies
}
}
// WithItemDependencies 注入商品应用服务所需的专用适配器工厂。
func WithItemDependencies(dependencies *adapter.ItemDependencies) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入商品专用依赖的 HTTP 服务实例。
if dependencies == nil {
server.itemDependencies = nil
return
}
server.itemDependencies = dependencies
}
}
// WithChatDependencies 注入聊天应用服务所需的专用适配器工厂。
func WithChatDependencies(dependencies *adapter.ChatDependencies) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入聊天专用依赖的 HTTP 服务实例。
server.chatDependencies = dependencies
}
}
// WithDatabaseHealth 注入由进程装配层构造的数据库健康检查端口。
func WithDatabaseHealth(health DatabaseHealthPort) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入健康检查端口的 HTTP 服务实例。
server.databaseHealth = health
}
}
// WithOrderReconciliationRecovery 注入由进程装配层拥有的订单补偿扫描应用服务。
func WithOrderReconciliationRecovery(recovery *orderapp.ReconciliationRecoveryCoordinator) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入订单补偿扫描服务的 HTTP 服务实例。
server.orderReconciliationRecovery = recovery
}
}
// WithAutomationDependencies 注入自动化领域所需的专用适配器工厂。
func WithAutomationDependencies(dependencies *adapter.AutomationDependencies) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入自动化专用依赖的 HTTP 服务实例。
server.automationDependencies = dependencies
}
}
// WithTransportApplicationServices 注入进程装配层构造完成的 transport-facing 应用服务集合。
func WithTransportApplicationServices(services *adapter.TransportApplicationServices) ServerOption {
return func(server *Server) {
if services == nil {
// server 是当前构造流程中应清空 transport-facing 应用服务集合的 HTTP 服务实例。
server.transportApplications = nil
return
}
// copiedServices 是构造期冻结的浅拷贝,避免调用方替换集合容器影响 Server。
copiedServices := *services
server.transportApplications = &copiedServices
}
}
// WithPlatformDependencies 注入 MTOP、长登录和二维码服务组成的平台能力边界。
func WithPlatformDependencies(dependencies *adapter.PlatformDependencies) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入平台依赖的 HTTP 服务实例。
server.platformDependencies = dependencies
}
}
// WithApplicationLifecycle 注入由进程装配层拥有的应用生命周期协调器。
func WithApplicationLifecycle(coordinator *lifecycleapp.Coordinator) ServerOption {
return func(server *Server) {
// server 是当前构造流程中需要读取应用生命周期 Context 的 HTTP 服务实例。
server.applicationLifecycle = coordinator
}
}
// New 构造纯 HTTP transport Server;所有应用服务、平台客户端和生命周期组件必须已由组合根创建。
func New(dependencies Dependencies) (*Server, error) {
if dependencies.Auth == nil {
return nil, fmt.Errorf("server 依赖认证服务不能为空")
}
if dependencies.Manager == nil {
return nil, fmt.Errorf("server 依赖 account.Manager 不能为空")
}
if dependencies.OrderDependencies == nil || dependencies.AccountDependencies == nil || dependencies.ItemDependencies == nil || dependencies.ChatDependencies == nil || dependencies.AutomationDependencies == nil {
return nil, fmt.Errorf("server 领域适配器依赖不能为空")
}
if dependencies.DatabaseHealth == nil || dependencies.OrderReconciliationRecovery == nil || dependencies.PlatformDependencies == nil {
if dependencies.DatabaseHealth == nil {
return nil, fmt.Errorf("server 基础设施应用端口不能为空")
}
if dependencies.TransportApplications == nil {
return nil, fmt.Errorf("server transport 应用服务集合不能为空")
}
// transportValidationErr 是组合根提供的 transport 应用服务集合校验错误。
if transportValidationErr := dependencies.TransportApplications.Validate(); transportValidationErr != nil {
return nil, fmt.Errorf("server transport 应用服务无效: %w", transportValidationErr)
}
if dependencies.Applications == nil {
return nil, fmt.Errorf("server 应用服务集合不能为空")
}
// applicationPortsErr 表示组合根提供的 Port 容器仍有未装配的 HTTP 路由能力。
if applicationPortsErr := dependencies.Applications.validate(); applicationPortsErr != nil {
return nil, fmt.Errorf("server 应用 Port 未完成装配: %w", applicationPortsErr)
}
// copiedApplications 冻结应用服务集合容器,调用方不得在 Server 启动后替换服务引用。
copiedApplications := *dependencies.Applications
// logger 是缺省时用于 transport 诊断的标准文本日志器。
@@ -343,170 +104,25 @@ func New(dependencies Dependencies) (*Server, error) {
logger = logging.NewLogger(os.Stdout, "text")
}
return &Server{
orderDependencies: dependencies.OrderDependencies,
accountDependencies: dependencies.AccountDependencies,
itemDependencies: dependencies.ItemDependencies,
chatDependencies: dependencies.ChatDependencies,
orderReconciliationRecovery: dependencies.OrderReconciliationRecovery,
automationDependencies: dependencies.AutomationDependencies,
transportApplications: dependencies.TransportApplications,
Auth: dependencies.Auth,
Manager: dependencies.Manager,
automation: dependencies.Automation,
notifier: dependencies.Notifier,
chat: dependencies.Chat,
platformDependencies: dependencies.PlatformDependencies,
Logger: logger,
WebDir: dependencies.WebDir,
Addr: dependencies.Addr,
applications: &copiedApplications,
applicationLifecycle: dependencies.ApplicationLifecycle,
databaseHealth: dependencies.DatabaseHealth,
loginLimiter: newLoginFailureLimiter(),
taskRegistry: newTaskRegistry(),
backgroundDone: closedSignal(),
}, nil
}
// ApplicationServices 返回构造期注入的应用服务集合快照,供 cmd 负责登记生命周期组件。
func (s *Server) ApplicationServices() *ApplicationServices {
if s == nil || s.applications == nil {
return nil
}
// copiedApplications 将集合容器复制后返回,避免调用方替换 Server 内部容器指针。
copiedApplications := *s.applications
return &copiedApplications
}
// NewLegacyComposedServer 是迁移期兼容构造器,会在 Server 内构建应用服务。
// 删除条件:cmd/server 和所有测试均改为由 adapter/组合根构造 ApplicationServices 后,删除本函数及 ServerOption。
func NewLegacyComposedServer(authentication *auth.Service, manager *account.Manager, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) {
if authentication == nil {
return nil, fmt.Errorf("server 依赖认证服务不能为空")
}
if manager == nil {
return nil, fmt.Errorf("server 依赖 account.Manager 不能为空")
}
if logger == nil {
logger = logging.NewLogger(os.Stdout, "text")
}
// server 是完成依赖装配、等待应用服务初始化后的 HTTP 服务实例。
server := &Server{
Auth: authentication,
Manager: manager,
automation: autoCenter,
notifier: notifier,
Auth: dependencies.Auth,
Logger: logger,
WebDir: webDir,
Addr: addr,
WebDir: dependencies.WebDir,
Addr: dependencies.Addr,
applications: &copiedApplications,
databaseHealth: dependencies.DatabaseHealth,
loginLimiter: newLoginFailureLimiter(),
taskRegistry: newTaskRegistry(),
backgroundDone: closedSignal(),
}
// option 表示当前遍历过程中的option
for _, option := range options {
// option 是当前构造调用提供的可选依赖配置。
if option != nil {
option(server)
}
}
if server.orderDependencies == nil {
return nil, fmt.Errorf("server 订单专用依赖不能为空")
}
if server.accountDependencies == nil {
return nil, fmt.Errorf("server 账号专用依赖不能为空")
}
if server.itemDependencies == nil {
return nil, fmt.Errorf("server 商品专用依赖不能为空")
}
if server.chatDependencies == nil {
return nil, fmt.Errorf("server 聊天专用依赖不能为空")
}
if server.databaseHealth == nil {
return nil, fmt.Errorf("server 数据库健康检查端口不能为空")
}
if server.orderReconciliationRecovery == nil {
return nil, fmt.Errorf("server 订单补偿扫描应用服务不能为空")
}
if server.platformDependencies == nil {
return nil, fmt.Errorf("server 平台依赖不能为空")
}
if server.automationDependencies == nil {
return nil, fmt.Errorf("server 自动化依赖不能为空")
}
// validationErr 表示进程组合根未提供完整 transport-facing 服务集合。
if validationErr := server.transportApplications.Validate(); validationErr != nil {
return nil, fmt.Errorf("server transport 应用服务无效: %w", validationErr)
}
// applications、applicationErr 分别是构造期应用服务集合及其装配错误。
applications, applicationErr := newApplicationServices(server)
if applicationErr != nil {
return nil, fmt.Errorf("server 应用服务装配失败: %w", applicationErr)
}
server.applications = applications
return server, nil
}
// mtopClient 返回构造阶段校验的平台 MTOP 客户端;零值 Server 返回 nil,避免隐式创建依赖。
func (s *Server) mtopClient() adapter.MTOPClient {
if s.MTop != nil {
return s.MTop
}
if s.platformDependencies != nil && s.platformDependencies.MTOPClient() != nil {
return s.platformDependencies.MTOPClient()
}
return nil
}
// longLoginClient 返回构造阶段注入的长登录客户端;旧公开字段仅用于兼容现有测试替身。
func (s *Server) longLoginClient() adapter.LongLoginClient {
if s.CookieRenew != nil {
return s.CookieRenew
}
if s.platformDependencies != nil && s.platformDependencies.LongLoginClient() != nil {
return s.platformDependencies.LongLoginClient()
}
return nil
}
// qrLoginService 返回构造阶段注入的二维码服务;旧公开字段仅用于兼容现有测试替身。
func (s *Server) qrLoginService() qrLoginService {
if s.QRLogin != nil {
return s.QRLogin
}
if s.platformDependencies != nil && s.platformDependencies.QRLoginService() != nil {
return s.platformDependencies.QRLoginService()
}
return nil
}
// sessionRecoveryCallback 返回平台会话失效的统一适配回调。
// 适配器负责错误分类和日志,账号运行时应用端口负责恢复;调用方不得跨凭证锁执行外部 I/O。
func (s *Server) sessionRecoveryCallback() adapter.SessionRecoveryHandler {
if s == nil {
return nil
}
return adapter.NewSessionRecoveryHandler(s.Logger, func(ctx context.Context, cookieID string) bool {
// runtime 保存账号运行时应用服务;恢复由应用端口编排而非 HTTP 层直接调用 Manager。
runtime := s.accountRuntimeApplication()
return runtime != nil && runtime.RecoverExpiredCredential(ctx, cookieID)
})
}
// recoverExpiredMTOPSession 保留旧测试入口并委托统一 Session 恢复适配回调。
// 新生产调用应直接注入 sessionRecoveryCallback,避免把 Server 方法传入基础设施适配器。
func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string, err error) bool {
// recovery 保存统一的错误分类、日志和运行时恢复回调。
recovery := s.sessionRecoveryCallback()
return recovery != nil && recovery(ctx, cookieID, err)
}, nil
}
// recoverExpiredSession 触发已注入的平台会话恢复回调,供 HTTP transport 处理应用层平台错误。
// 该方法不读取凭证、不调用 Manager,也不在凭证锁内执行外部 I/O。
func (s *Server) recoverExpiredSession(ctx context.Context, cookieID string, err error) bool {
// recovery 保存统一的错误分类、日志和运行时恢复回调。
recovery := s.sessionRecoveryCallback()
return recovery != nil && recovery(ctx, cookieID, err)
if s == nil || s.applications == nil || s.applications.sessionRecovery == nil {
return false
}
return s.applications.sessionRecovery.Recover(ctx, cookieID, err)
}
// Router 构建完整路由树。
@@ -1036,14 +652,6 @@ func closedSignal() chan struct{} {
return done
}
// lifecycleContext 封装lifecycle上下文业务协调。
func (s *Server) lifecycleContext() context.Context {
if s == nil || s.applicationLifecycle == nil {
return context.Background()
}
return s.applicationLifecycle.Context()
}
// startBackgroundTaskContext 登记并启动带显式 Context 的 Server 后台任务。
// 返回值是可供管理端查询的任务 ID;任务完成、取消或超时后会保留有限历史。
func (s *Server) startBackgroundTaskContext(name string, ctx context.Context, task func()) string {
+168 -7
View File
@@ -9,15 +9,19 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
lifecycleapp "xianyu-go/internal/application/lifecycle"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/chat"
"xianyu-go/internal/composition"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/notify"
"xianyu-go/internal/xianyu/mtop"
)
@@ -96,7 +100,7 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
// authentication 保存测试 HTTP 会话中间件需要的认证服务。
authentication := &auth.Service{Store: store}
// srv、err 保存测试 HTTP 服务构造结果及失败原因。
srv, err := NewLegacyComposedServer(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
srv, err := newTestServerFromComposition(authentication, mgr, nil, nil, nil, orderDependencies, accountDependencies, itemDependencies, chatDependencies, automationDependencies, transportApplications, platformDependencies, databaseHealth, orderReconciliationRecovery)
if err != nil {
t.Fatalf("New: %v", err)
}
@@ -112,7 +116,7 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
Request: req,
}, nil
})}
srv.MTop = mtopClient
setTestMTop(srv, mtopClient)
return srv, store, func() {
mgr.StopAll()
_ = d.Close()
@@ -125,10 +129,9 @@ func newTestServerWithChat(t *testing.T) (*Server, *db.Store, func()) {
srv, store, cleanup := newTestServer(t)
// chatService 是仅供聊天测试使用的通信应用服务实例。
chatService := chat.New(store)
// srv.chat 在测试构造阶段一次性注入通信服务,模拟构造 option 的效果。
srv.chat = chatService
// applications.chat 重新绑定测试聊天服务,确保实时订阅适配器与 srv.chat 使用同一事件中心。
srv.applications.chat = newChatSendingApplication(srv)
// applications.chat 重新绑定测试聊天服务,确保实时订阅适配器使用同一事件中心。
srv.applications.chat = adapter.NewChatSendingApplication(chatService, store, testAccountManager(srv), func() mtop.Client { return testMTop(srv) })
registerTestChatDomain(srv, chatService)
return srv, store, cleanup
}
@@ -204,7 +207,7 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
// authentication 保存未初始化数据库上的会话中间件依赖。
authentication := &auth.Service{Store: store}
// srv、err 保存未初始化测试服务构造结果及失败原因。
srv, err := NewLegacyComposedServer(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
srv, err := newTestServerFromComposition(authentication, mgr, nil, nil, nil, orderDependencies, accountDependencies, itemDependencies, chatDependencies, automationDependencies, transportApplications, platformDependencies, databaseHealth, orderReconciliationRecovery)
if err != nil {
t.Fatalf("New: %v", err)
}
@@ -214,6 +217,164 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
}
}
// newTestServerFromComposition 按生产组合根顺序构造测试 HTTP Server,禁止回退到已删除的 Server 内部装配器。
func newTestServerFromComposition(authentication *auth.Service, manager *account.Manager, autoCenter *automation.Center, notifier *notify.Notifier, chatService *chat.Service, orderDependencies *adapter.OrderDependencies, accountDependencies *adapter.AccountDependencies, itemDependencies *adapter.ItemDependencies, chatDependencies *adapter.ChatDependencies, automationDependencies *adapter.AutomationDependencies, transportApplications *adapter.TransportApplicationServices, platformDependencies *adapter.PlatformDependencies, databaseHealth DatabaseHealthPort, orderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator) (*Server, error) {
// testPlatform 将默认平台能力包装为每个 Server 独立可变的测试 Port。
testPlatform := newTestPlatformPort(platformDependencies)
// lifecycleCoordinator 保存测试应用 worker 的父 Context 所有者。
lifecycleCoordinator := lifecycleapp.NewCoordinator()
// applications 在平台回调触发时提供已完成装配的账号运行时服务。
var applications *composition.Services
// updateRunningCookie 把平台 Cookie 变化转交给应用服务,测试中忽略非敏感运行时同步错误。
updateRunningCookie := func(ctx context.Context, accountID, value string) {
if applications != nil {
_ = applications.UpdateRunningCookie(ctx, accountID, value)
}
}
// sessionRecovery 将确认过期的会话恢复请求委托给账号运行时应用服务。
sessionRecovery := adapter.NewSessionRecoveryHandler(nil, func(ctx context.Context, accountID string) bool {
return applications != nil && applications.RecoverExpiredCredential(ctx, accountID)
})
// applicationsErr 表示测试组合根装配应用服务失败的原因。
var applicationsErr error
applications, applicationsErr = composition.New(composition.Dependencies{
OrderDependencies: orderDependencies,
AccountDependencies: accountDependencies,
ItemDependencies: itemDependencies,
ChatDependencies: chatDependencies,
AutomationDependencies: automationDependencies,
TransportApplications: transportApplications,
OrderReconciliationRecovery: orderReconciliationRecovery,
Manager: manager,
Automation: autoCenter,
Notifier: notifier,
Chat: chatService,
MTopClient: testPlatform.MTOPClient,
LongLoginClient: testPlatform.LongLoginClient,
QRLogin: testPlatform,
UpdateRunningCookie: updateRunningCookie,
SessionRecovery: sessionRecovery,
LifecycleContext: lifecycleCoordinator.Context,
})
if applicationsErr != nil {
return nil, applicationsErr
}
// dependencies 保存测试组合层投影出的 HTTP transport 依赖。
dependencies := testServerDependencies(authentication, databaseHealth, applications, sessionRecovery)
// serverErr 保存 HTTP transport 注入完整 Port 快照时的构造失败。
server, serverErr := New(dependencies)
if serverErr != nil {
return nil, serverErr
}
registerTestAccountManager(server, manager)
registerTestPlatform(server, testPlatform)
registerTestBatchLifecycle(server, applications.LifecycleComponents())
registerTestOrderServices(server, applications.TransportPorts().Orders)
return server, nil
}
// testAccountLoginAdapter 将组合层账号登录 Port 适配为 Server 的测试 transport Port。
type testAccountLoginAdapter struct {
// service 是测试组合根创建的账号登录能力。
service composition.AccountLogin
}
// CreateCookie 透传测试 Cookie 创建命令。
func (adapter testAccountLoginAdapter) CreateCookie(ctx context.Context, accountID, cookies string, userID int64, loginMethod string) error {
return adapter.service.CreateCookie(ctx, accountID, cookies, userID, loginMethod)
}
// UpdateCookie 透传测试 Cookie 更新命令。
func (adapter testAccountLoginAdapter) UpdateCookie(ctx context.Context, accountID, cookies string, userID int64, loginMethod string, expectedRevision int64) error {
return adapter.service.UpdateCookie(ctx, accountID, cookies, userID, loginMethod, expectedRevision)
}
// PersistQRLoginSuccess 将组合层二维码结果转换为 Server 可编码结果。
func (adapter testAccountLoginAdapter) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (AccountLoginResult, error) {
// persisted、persistErr 分别是测试登录服务的脱敏持久化结果和失败。
persisted, persistErr := adapter.service.PersistQRLoginSuccess(ctx, userID, sessionID, result, targetAccountID)
if persistErr != nil {
return AccountLoginResult{}, persistErr
}
return AccountLoginResult{AccountID: persisted.AccountID, IsNew: persisted.IsNew}, nil
}
// RegisterQRSession 登记测试二维码会话归属。
func (adapter testAccountLoginAdapter) RegisterQRSession(sessionID string, userID int64, createdAt time.Time) {
adapter.service.RegisterQRSession(sessionID, userID, createdAt)
}
// AuthorizeQRSession 验证测试二维码会话归属。
func (adapter testAccountLoginAdapter) AuthorizeQRSession(sessionID string, userID int64) error {
return adapter.service.AuthorizeQRSession(sessionID, userID)
}
// CleanupQRSessions 清理测试二维码会话。
func (adapter testAccountLoginAdapter) CleanupQRSessions(now time.Time) []string {
return adapter.service.CleanupQRSessions(now)
}
// testQRLoginAdapter 将 adapter 二维码服务适配为 Server 的测试 transport Port。
type testQRLoginAdapter struct {
// service 是组合根创建的二维码服务。
service adapter.QRLoginService
}
// GenerateQRCode 创建测试二维码会话。
func (adapter testQRLoginAdapter) GenerateQRCode(ctx context.Context) (string, string, error) {
return adapter.service.GenerateQRCode(ctx)
}
// GetSessionStatus 读取测试二维码状态。
func (adapter testQRLoginAdapter) GetSessionStatus(sessionID string) map[string]any {
return adapter.service.GetSessionStatus(sessionID)
}
// CompleteVerification 完成测试二维码验证。
func (adapter testQRLoginAdapter) CompleteVerification(ctx context.Context, sessionID string) (string, string, error) {
return adapter.service.CompleteVerification(ctx, sessionID)
}
// DeleteSession 尽力清理测试二维码平台会话。
func (adapter testQRLoginAdapter) DeleteSession(sessionID string) {
// cleaner、ok 分别是测试二维码服务提供的可选会话清理能力及存在状态。
if cleaner, ok := adapter.service.(interface{ DeleteSession(string) }); ok {
cleaner.DeleteSession(sessionID)
}
}
// testSessionRecoveryAdapter 将 adapter 的会话错误分类函数适配为 Server Port。
type testSessionRecoveryAdapter struct {
// handler 是测试组合根构造的会话恢复函数。
handler adapter.SessionRecoveryHandler
}
// Recover 处理确认失效的测试会话。
func (adapter testSessionRecoveryAdapter) Recover(ctx context.Context, accountID string, err error) bool {
return adapter.handler != nil && adapter.handler(ctx, accountID, err)
}
// testServerDependencies 将组合层服务快照转换为 Server 测试构造所需的依赖。
func testServerDependencies(authentication *auth.Service, databaseHealth DatabaseHealthPort, services *composition.Services, sessionRecovery adapter.SessionRecoveryHandler) Dependencies {
// ports 是测试组合根投影的完整 transport Port 集合。
ports := services.TransportPorts()
return Dependencies{Auth: authentication, Addr: ":0", DatabaseHealth: databaseHealth, Applications: NewApplicationPorts(ApplicationPortsInput{
Orders: testOrdersTransport{services: ports.Orders}, OrderRefreshJobs: ports.OrderRefreshJobs, ItemSinglePublish: ports.ItemSinglePublish,
ItemBatchPreview: ports.ItemBatchPreview, ItemBatchManagement: ports.ItemBatchManagement, ItemCategoryRecommendation: ports.ItemCategoryRecommendation,
ItemBatchPreviewPersistence: ports.ItemBatchPreviewPersistence, ItemBatchLocalPublish: ports.ItemBatchLocalPublish,
ItemSync: ports.ItemSync, ItemCatalog: ports.ItemCatalog, ItemCatalogMutation: ports.ItemCatalogMutation,
AccountLogin: testAccountLoginAdapter{service: ports.AccountLogin}, QRLogin: testQRLoginAdapter{service: ports.QRLogin},
SessionRecovery: testSessionRecoveryAdapter{handler: sessionRecovery}, PlatformCredentials: ports.PlatformCredentials,
Authentication: ports.Authentication, LoginAudit: ports.LoginAudit, PasswordLogin: ports.PasswordLogin, AccountDelete: ports.AccountDelete,
AccountProfile: ports.AccountProfile, AccountLongLogin: ports.AccountLongLogin, AccountSettings: ports.AccountSettings,
AccountRuntime: ports.AccountRuntime, AccountSummaries: ports.AccountSummaries, AccountTasks: ports.AccountTasks, Chat: ports.Chat,
UncertainNotifications: ports.UncertainNotifications, NotificationChannels: ports.NotificationChannels, Analytics: ports.Analytics,
AutomationIssues: ports.AutomationIssues, AutomationRules: ports.AutomationRules, Cards: ports.Cards,
PublishAutomationRules: ports.PublishAutomationRules, DefaultReplies: ports.DefaultReplies, Keywords: ports.Keywords,
Settings: ports.Settings, Admin: ports.Admin,
})}
}
// newTestOrderReconciliationRecovery 以与进程组合根一致的路径构造订单补偿扫描应用服务。
func newTestOrderReconciliationRecovery(t *testing.T, dependencies *adapter.SystemDependencies) *orderapp.ReconciliationRecoveryCoordinator {
t.Helper()
+7 -7
View File
@@ -437,13 +437,13 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
t.Fatal("user settings response must be an object")
}
// srv.QRLogin 是二维码状态与验证的测试替身。
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
// 二维码状态与验证使用测试专用平台替身。
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{
"status": "waiting",
"session_id": "contract-qr",
"custom_field": "kept",
"cookies": "must-not-leak",
}}
}})
// statusSessionID 是二维码状态测试会话标识。
statusSessionID := "contract-qr"
ownQRSession(t, srv, store, statusSessionID)
@@ -476,8 +476,8 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
t.Fatalf("qr status response leaked cookies: %+v", rawQR)
}
// srv.QRLogin 替换为完成验证场景的测试替身。
srv.QRLogin = &fakeQRLoginService{completeCookies: "unb=contract-unb; _m_h5_tk=token;", completeUNB: "contract-unb"}
// 二维码验证完成场景替换测试专用平台替身。
setTestQRLogin(srv, &fakeQRLoginService{completeCookies: "unb=contract-unb; _m_h5_tk=token;", completeUNB: "contract-unb"})
// completeSessionID 是二维码验证完成测试会话标识。
completeSessionID := "contract-complete"
ownQRSession(t, srv, store, completeSessionID)
@@ -776,8 +776,8 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
t.Fatalf("valid orders response=%+v", validOrdersResponseValue)
}
// srv.QRLogin 是二维码生成测试替身。
srv.QRLogin = &fakeQRLoginService{}
// 二维码生成使用测试专用平台替身。
setTestQRLogin(srv, &fakeQRLoginService{})
// qrReq 是生成扫码登录二维码的请求。
qrReq := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
qrReq.AddCookie(sessionCookie)
@@ -145,8 +145,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) {
// srv 是用于验证账号凭证版本化路由的 HTTP 测试服务。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// srv.Manager 置空后,新增和更新请求不会启动后台运行时。
srv.Manager = nil
// HTTP transport 不直接持有账号运行时,新增和更新通过应用服务编排。
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
@@ -55,7 +55,7 @@ func TestVersionedChatTaskRoutesPreserveLegacyContracts(t *testing.T) {
{name: "account-task-settings-missing", method: http.MethodGet, versionedPath: "/api/v1/account-tasks/missing", legacyPath: "/api/account-tasks/missing", wantStatus: http.StatusForbidden},
{name: "account-task-settings-invalid", method: http.MethodPut, versionedPath: "/api/v1/account-tasks/acc1", legacyPath: "/api/account-tasks/acc1", body: `{"auto_rate_enabled":true,"rate_content":"","auto_polish_enabled":false,"polish_time":"03:00"}`, wantStatus: http.StatusBadRequest},
{name: "account-task-runs-missing", method: http.MethodGet, versionedPath: "/api/v1/account-tasks/missing/runs", legacyPath: "/api/account-tasks/missing/runs", wantStatus: http.StatusForbidden},
{name: "account-task-run-service-disabled", method: http.MethodPost, versionedPath: "/api/v1/account-tasks/acc1/run", legacyPath: "/api/account-tasks/acc1/run", body: `{}`, wantStatus: http.StatusServiceUnavailable},
{name: "account-task-run-service-disabled", method: http.MethodPost, versionedPath: "/api/v1/account-tasks/acc1/run", legacyPath: "/api/account-tasks/acc1/run", body: `{"task_type":"auto_rate"}`, wantStatus: http.StatusServiceUnavailable},
}
for _, routeCase := range cases { // routeCase 是当前正在执行的聊天或账号任务路由样例。
// versionedStatus 是版本化入口实际返回的状态码。
@@ -41,7 +41,7 @@ func TestVersionedQRLoginRoutesPreserveLegacyContracts(t *testing.T) {
// srv 是用于验证二维码登录版本化路由的 HTTP 测试服务。
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{"status": "waiting"}})
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
@@ -110,9 +110,9 @@ func TestCompatibilityMatrixDocumentsSunsetConditions(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// requiredPhrases 是阶段三调用方审计必须保留的证据和删除条件短语。
// requiredPhrases 是 API 调用方审计必须保留的证据和删除条件短语;正式阶段编号只由总计划定义。
requiredPhrases := []string{
"阶段 3 调用方审计",
"API 调用方审计",
"TestFrontendProductionRequestsUseVersionedAPI",
"外部调用方",
"Sunset",
+477 -9
View File
@@ -31,7 +31,7 @@ type controlledDynamicResponse struct {
sunsetVersion string
}
// controlledDynamicResponses 是阶段 9 允许保留的最小动态响应登记表。
// controlledDynamicResponses 是兼容矩阵允许保留的最小动态响应登记表。
var controlledDynamicResponses = map[string]controlledDynamicResponse{
"settingsResponse": {
matrixName: "settingsResponse",
@@ -72,6 +72,11 @@ func main() {
// checkRepository 扫描 Go 源码并汇总依赖方向与事务边界问题。
func checkRepository(root string) ([]violation, error) {
// activeStage、stageErr 分别是总计划声明的唯一当前阶段及其解析失败原因。
activeStage, stageErr := readActiveArchitectureStage(root)
if stageErr != nil {
return nil, stageErr
}
// violations 保存扫描过程中发现的全部违规。
var violations []violation
// fset 为 AST 节点提供统一文件与行号映射。
@@ -90,19 +95,25 @@ func checkRepository(root string) ([]violation, error) {
return err
}
// fileViolations 保存当前文件的架构检查结果。
fileViolations, err := checkGoFile(root, relativePath, fset)
fileViolations, err := checkGoFile(root, relativePath, fset, activeStage)
if err != nil {
return err
}
violations = append(violations, fileViolations...)
return nil
})
if architectureStageEnabled(activeStage, architectureStageServerComposition) {
// stageTwoViolations 是阶段二启用的组合根门禁;该阶段未完成前不得降级为告警或白名单。
violations = append(violations, checkStageTwoCompositionRoot(root)...)
}
// phasedViolations 是已达到激活阶段的生命周期、前端、数据库与质量门禁结果。
violations = append(violations, checkActivatedRepositoryGates(root, activeStage)...)
violations = append(violations, checkCompatibilityGovernance(root)...)
return violations, walkErr
}
// checkGoFile 检查单个 Go 文件的导入方向和事务调用位置。
func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, error) {
func checkGoFile(root, relativePath string, fset *token.FileSet, activeStage int) ([]violation, error) {
// filePath 是当前 Go 文件的绝对或仓库相对路径。
filePath := filepath.Join(root, relativePath)
// source 是当前文件原文,用于识别事务调用的精确文本边界。
@@ -161,7 +172,7 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
violations = append(violations, violation{
file: filepath.ToSlash(relativePath),
line: line,
message: fmt.Sprintf("Server 新增低层依赖必须先迁移到应用 Port 或登记临时白名单 %q", importedPath),
message: fmt.Sprintf("Server 新增低层依赖必须先迁移到应用 Port,禁止使用临时例外 %q", importedPath),
})
}
}
@@ -170,6 +181,10 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
violations = append(violations, checkHTTPRequestContracts(relativePath, syntax, fset)...)
violations = append(violations, checkRuntimeSetterCalls(relativePath, syntax, fset)...)
violations = append(violations, checkServerCompositionCalls(relativePath, syntax, fset)...)
violations = append(violations, checkServerInfrastructureFields(relativePath, syntax, fset)...)
if architectureStageEnabled(activeStage, architectureStageServerComposition) {
violations = append(violations, checkStageTwoTransportBoundary(relativePath, syntax, fset)...)
}
if strings.HasPrefix(filepath.ToSlash(relativePath), "internal/server/") && !strings.HasSuffix(relativePath, "_repository.go") {
// sourceLine 是裸 BeginTx 调用首次出现的源码行号。
sourceLine := firstLineContaining(string(source), ".DB.BeginTx(")
@@ -184,6 +199,459 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
return violations, nil
}
// checkStageTwoCompositionRoot 强制阶段二使用独立组合层,并禁止 cmd 重新承担应用服务装配职责。
func checkStageTwoCompositionRoot(root string) []violation {
// compositionPath 是阶段二唯一允许承载跨层生产装配的目录。
compositionPath := filepath.Join(root, "internal", "composition")
// entries、readErr 分别是组合层目录成员和读取失败原因。
entries, readErr := os.ReadDir(compositionPath)
if readErr != nil {
return []violation{{file: "internal/composition", line: 1, message: "阶段二要求独立 composition 包承载应用服务和 worker 装配,禁止留在 Server 或 cmd/server"}}
}
// hasProductionGo 表示组合层至少包含一个非测试 Go 源文件。
hasProductionGo := false
// entry 是当前检查的组合层目录成员;只有生产 Go 文件能够证明存在真实装配实现。
for _, entry := range entries {
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".go") && !strings.HasSuffix(entry.Name(), "_test.go") {
hasProductionGo = true
break
}
}
if !hasProductionGo {
return []violation{{file: "internal/composition", line: 1, message: "阶段二 composition 包必须包含生产装配代码,测试文件或空目录不能替代组合根"}}
}
// mainPath 是必须显式调用组合层的 Server 入口文件。
mainPath := filepath.Join(root, "cmd", "server", "main.go")
// syntax、parseErr 分别是入口源码 AST 及解析失败原因。
syntax, parseErr := parser.ParseFile(token.NewFileSet(), mainPath, nil, parser.ImportsOnly)
if parseErr != nil {
return []violation{{file: "cmd/server/main.go", line: 1, message: fmt.Sprintf("无法解析 cmd/server 组合根导入: %v", parseErr)}}
}
if !importsCompositionPath(syntax) {
return []violation{{file: "cmd/server/main.go", line: 1, message: "阶段二要求 cmd/server 显式调用 internal/composition,禁止自行装配应用服务和 worker"}}
}
return nil
}
// importsCompositionPath 判断 cmd 是否直接调用独立组合层或其明确的 runtime 子层。
func importsCompositionPath(syntax *ast.File) bool {
// imported 是当前 cmd 文件声明的导入项,逐项判断是否显式依赖组合层。
for _, imported := range syntax.Imports {
// rawPath、unquoteErr 分别是导入路径的去引号文本及其解析错误。
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
if unquoteErr != nil {
continue
}
// importPath 是标准化后的仓库内导入路径。
importPath := normalizeImportPath(rawPath)
if importPath == "internal/composition" || strings.HasPrefix(importPath, "internal/composition/") {
return true
}
}
return false
}
// checkStageTwoTransportBoundary 以 fail-closed 规则阻止组合根、平台实现和生命周期所有权重新进入 Server。
func checkStageTwoTransportBoundary(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
// normalizedPath 是统一使用斜杠的仓库相对路径。
normalizedPath := filepath.ToSlash(relativePath)
if strings.HasSuffix(normalizedPath, "_test.go") {
return nil
}
// isServer 表示当前文件是否属于 HTTP transport 包。
isServer := strings.HasPrefix(normalizedPath, "internal/server/")
// isServerCommand 表示当前文件是否属于 Server 进程入口包。
isServerCommand := strings.HasPrefix(normalizedPath, "cmd/server/")
if !isServer && !isServerCommand {
return nil
}
// violations 保存当前源码文件违反阶段二边界的全部位置。
var violations []violation
if isServer && filepath.Base(normalizedPath) == "application_services.go" {
violations = append(violations, violation{file: normalizedPath, line: 1, message: "阶段二禁止 internal/server/application_services.go;应用服务、runner 和 coordinator 必须迁入 composition 与应用层"})
}
// forbiddenImports 是当前阶段不允许出现在 transport 或 cmd 组合入口的跨层依赖。
var forbiddenImports map[string]string
if isServer {
forbiddenImports = map[string]string{
"internal/account": "Server 不得直接依赖 account.Manager,必须消费应用 Port",
"internal/adapter": "Server 不得直接依赖 adapter 实现或 factory,必须消费应用 Port",
"internal/automation": "Server 不得直接依赖 automation.Center,必须消费应用 Port",
"internal/browser": "Server 不得直接依赖 browser 实现,必须消费应用 Port",
"internal/chat": "Server 不得直接依赖 chat.Service,必须消费聊天应用 Port",
"internal/db": "Server 不得直接依赖 db.Store 或 repository,实现必须留在 adapter",
"internal/notify": "Server 不得直接依赖 notifier,实现必须留在通知应用 Port",
"internal/xianyu": "Server 不得直接依赖平台协议,实现必须留在 adapter",
}
} else {
forbiddenImports = map[string]string{
"internal/adapter": "cmd/server 不得直接装配 adapter 服务;必须委托 internal/composition",
"internal/account": "cmd/server 不得直接装配账号运行时;必须委托 internal/composition",
"internal/automation": "cmd/server 不得直接装配自动化 worker;必须委托 internal/composition",
"internal/chat": "cmd/server 不得直接装配聊天服务;必须委托 internal/composition",
"internal/notify": "cmd/server 不得直接装配通知 worker;必须委托 internal/composition",
"internal/application/": "cmd/server 不得直接构造应用服务或 worker;必须委托 internal/composition",
}
}
// imported 是当前源码声明的内部或标准库导入,必须逐项检查其是否越过当前层边界。
for _, imported := range syntax.Imports {
// rawPath、unquoteErr 分别是当前导入路径及其语法解析错误。
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
if unquoteErr != nil {
continue
}
// importPath 是去除模块前缀后的稳定内部导入路径。
importPath := normalizeImportPath(rawPath)
// forbiddenPath 是禁止导入的内部路径前缀;message 是命中后返回给迁移者的具体修复方向。
for forbiddenPath, message := range forbiddenImports {
if importPath == forbiddenPath || strings.HasPrefix(importPath, forbiddenPath) {
violations = append(violations, violation{file: normalizedPath, line: fset.Position(imported.Pos()).Line, message: message})
break
}
}
}
if isServer {
violations = append(violations, checkStageTwoServerDeclarations(normalizedPath, syntax, fset)...)
violations = append(violations, checkStageTwoServerConstruction(normalizedPath, syntax, fset)...)
violations = append(violations, checkStageTwoApplicationPortDeclarations(normalizedPath, syntax, fset)...)
}
violations = append(violations, checkStageTwoCompositionProjection(normalizedPath, syntax, fset)...)
if isServerCommand {
violations = append(violations, checkStageTwoCmdCalls(normalizedPath, syntax, fset)...)
}
return violations
}
// checkStageTwoApplicationPortDeclarations 拒绝 HTTP Port 容器重新持有具体应用服务实现。
func checkStageTwoApplicationPortDeclarations(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
if filepath.Base(relativePath) != "application_ports.go" {
return nil
}
// applicationAliases 保存当前文件中应用包的本地导入别名。
applicationAliases := applicationImportAliases(syntax)
// violations 保存具体应用服务指针泄露到 transport Port 容器的全部位置。
var violations []violation
// declaration 是当前文件的顶级声明,只有类型声明可能定义 Port 容器。
for _, declaration := range syntax.Decls {
// generalDeclaration、ok 分别是转换后的通用声明及其类型匹配状态。
generalDeclaration, ok := declaration.(*ast.GenDecl)
if !ok || generalDeclaration.Tok != token.TYPE {
continue
}
// specification 是该通用声明中的单个类型规格。
for _, specification := range generalDeclaration.Specs {
// typeSpecification、ok 分别是转换后的类型规格及其匹配状态。
typeSpecification, ok := specification.(*ast.TypeSpec)
if !ok || (typeSpecification.Name.Name != "ApplicationPorts" && typeSpecification.Name.Name != "ApplicationPortsInput") {
continue
}
// structure、ok 分别是 Port 容器的结构体定义及其类型匹配状态。
structure, ok := typeSpecification.Type.(*ast.StructType)
if !ok {
continue
}
// field 是当前 Port 容器声明的字段,用于检查是否泄露具体应用服务。
for _, field := range structure.Fields.List {
if !containsConcreteApplicationServicePointer(field.Type, applicationAliases) {
continue
}
violations = append(violations, violation{file: relativePath, line: fset.Position(field.Pos()).Line, message: "阶段二 HTTP 应用 Port 容器不得持有具体 application Service 指针;请在 internal/server 定义消费者接口并由 composition 投影实现"})
}
}
}
return violations
}
// applicationImportAliases 收集 internal/application 子包的本地别名。
func applicationImportAliases(syntax *ast.File) map[string]struct{} {
// aliases 保存应用包在当前文件中的可见名称。
aliases := make(map[string]struct{})
// imported 是当前 transport 文件的导入项,用于识别应用包的本地别名。
for _, imported := range syntax.Imports {
// rawPath、unquoteErr 分别是导入路径的去引号文本及其解析错误。
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
if unquoteErr != nil {
continue
}
// importPath 是标准化后的仓库内导入路径。
importPath := normalizeImportPath(rawPath)
if !strings.HasPrefix(importPath, "internal/application/") {
continue
}
// alias 是当前文件使用的应用包本地名称,默认取导入路径末段。
alias := filepath.Base(importPath)
if imported.Name != nil {
alias = imported.Name.Name
}
if alias != "_" && alias != "." {
aliases[alias] = struct{}{}
}
}
return aliases
}
// containsConcreteApplicationServicePointer 递归识别字段类型中隐藏的具体应用服务指针。
func containsConcreteApplicationServicePointer(expression ast.Expr, applicationAliases map[string]struct{}) bool {
// pointer 表示当前类型是否直接持有应用层对象;只有具体 Service/ServiceSet 才违反 Port 边界。
if pointer, ok := expression.(*ast.StarExpr); ok {
// selector、ok 分别是指针元素的限定类型选择器及其匹配状态。
if selector, ok := pointer.X.(*ast.SelectorExpr); ok {
// packageName、ok 分别是限定类型所属包标识符及其匹配状态。
if packageName, ok := selector.X.(*ast.Ident); ok {
// imported 表示该包名是否来自当前文件导入的应用层包。
if _, imported := applicationAliases[packageName.Name]; imported && (strings.HasSuffix(selector.Sel.Name, "Service") || strings.HasSuffix(selector.Sel.Name, "ServiceSet")) {
return true
}
}
}
return containsConcreteApplicationServicePointer(pointer.X, applicationAliases)
}
// array 表示切片或数组字段;递归避免以集合形式隐藏具体服务。
if array, ok := expression.(*ast.ArrayType); ok {
return containsConcreteApplicationServicePointer(array.Elt, applicationAliases)
}
// mapping 表示 map 字段;键和值都不能用于隐藏服务实例。
if mapping, ok := expression.(*ast.MapType); ok {
return containsConcreteApplicationServicePointer(mapping.Key, applicationAliases) || containsConcreteApplicationServicePointer(mapping.Value, applicationAliases)
}
return false
}
// checkStageTwoCompositionProjection 确保 composition 核心不反向依赖 Server,只有 runtime 子层可以投影 Server 依赖。
func checkStageTwoCompositionProjection(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
if !strings.HasPrefix(relativePath, "internal/composition/") || strings.HasPrefix(relativePath, "internal/composition/runtime/") {
return nil
}
// imported 是 composition 核心文件的导入项,核心层不得反向导入 Server。
for _, imported := range syntax.Imports {
// rawPath、unquoteErr 分别是导入路径的去引号文本及其解析错误。
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
if unquoteErr != nil || normalizeImportPath(rawPath) != "internal/server" {
continue
}
return []violation{{file: relativePath, line: fset.Position(imported.Pos()).Line, message: "阶段二 composition 核心不得依赖 Server;只能由 internal/composition/runtime 投影 server.Dependencies"}}
}
return nil
}
// checkStageTwoServerDeclarations 禁止 Server 继续声明服务集合、平台 Port 或反向生命周期 API。
func checkStageTwoServerDeclarations(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
// forbiddenTypes 是必须从 internal/server 消失的组合根和平台类型。
forbiddenTypes := map[string]string{
"ApplicationServices": "Server 不能拥有应用服务集合;请迁入 composition 并向 handler 注入最小应用 Port",
"ApplicationServiceDependencies": "Server 不能声明应用服务装配依赖;请迁入 composition",
"PlatformPort": "Server 不能持有 MTOP、长登录或二维码平台 Port;请迁入对应应用用例",
}
// forbiddenMethods 是必须从 Server 消失的反向访问器和 session callback。
forbiddenMethods := map[string]string{
"ApplicationServices": "Server 不得向外返还应用服务集合",
"LifecycleComponents": "Server 不得生成或返还应用 worker 生命周期组件",
"mtopClient": "Server 不得获取 MTOP 客户端",
"longLoginClient": "Server 不得获取长登录客户端",
"qrLoginService": "Server 不得获取二维码平台客户端",
"sessionRecoveryCallback": "Server 不得创建 session recovery callback",
"recoverExpiredMTOPSession": "Server 不得承载 MTOP session 恢复",
}
// violations 保存声明层违反阶段二边界的位置。
var violations []violation
// declaration 是当前 Server 文件的顶层声明,可能声明禁止的组合根类型或访问器。
for _, declaration := range syntax.Decls {
// typedDeclaration 是顶层声明的具体语法类型,用于分开处理类型和函数声明。
switch typedDeclaration := declaration.(type) {
case *ast.GenDecl:
if typedDeclaration.Tok != token.TYPE {
continue
}
// specification 是当前类型声明块中的单个类型定义。
for _, specification := range typedDeclaration.Specs {
// typeSpecification、ok 分别是当前语法规格是否为具名类型及其断言结果。
typeSpecification, ok := specification.(*ast.TypeSpec)
if !ok {
continue
}
// message、forbidden 分别是命中禁止类型时的修复提示及其匹配结果。
if message, forbidden := forbiddenTypes[typeSpecification.Name.Name]; forbidden {
violations = append(violations, violation{file: relativePath, line: fset.Position(typeSpecification.Pos()).Line, message: message})
}
}
case *ast.FuncDecl:
// message、forbidden 分别是命中禁止 Server 访问器时的修复提示及其匹配结果。
if message, forbidden := forbiddenMethods[typedDeclaration.Name.Name]; forbidden {
violations = append(violations, violation{file: relativePath, line: fset.Position(typedDeclaration.Pos()).Line, message: message})
}
}
}
return violations
}
// checkStageTwoServerConstruction 拒绝 Server 直接构造应用服务、runner、coordinator 或 adapter factory。
func checkStageTwoServerConstruction(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
// internalAliases 保存当前文件中指向 application 或 adapter 的导入别名,供构造调用精确判定。
internalAliases := internalConstructionImportAliases(syntax)
// violations 保存调用层违反阶段二边界的位置。
var violations []violation
ast.Inspect(syntax, func(node ast.Node) bool {
// call 是当前待检查的函数或方法调用。
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
// selector 表示当前调用的接收者与方法名称。
selector, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
// name 是当前被调用的方法或构造函数名称。
name := selector.Sel.Name
if name == "NewApplicationServices" || name == "LifecycleComponents" || name == "ApplicationServices" || name == "sessionRecoveryCallback" || name == "recoverExpiredMTOPSession" || (strings.HasPrefix(name, "New") && isInternalConstructionCall(selector.X, internalAliases)) {
violations = append(violations, violation{file: relativePath, line: fset.Position(call.Pos()).Line, message: fmt.Sprintf("Server 禁止调用 %s;应用服务、runner、coordinator 和 adapter factory 必须由 composition 构造", name)})
}
return true
})
return violations
}
// internalConstructionImportAliases 收集 application 与 adapter 导入的本地别名,避免误判标准库 New 调用。
func internalConstructionImportAliases(syntax *ast.File) map[string]struct{} {
// aliases 保存需要受阶段二构造门禁保护的本地导入名。
aliases := make(map[string]struct{})
// imported 是当前待解析别名的导入声明。
for _, imported := range syntax.Imports {
// rawPath、unquoteErr 分别是当前导入路径及其语法解析错误。
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
if unquoteErr != nil {
continue
}
// importPath 是去除模块前缀后的内部导入路径。
importPath := normalizeImportPath(rawPath)
if !strings.HasPrefix(importPath, "internal/application/") && !strings.HasPrefix(importPath, "internal/adapter") {
continue
}
// alias 是源码调用选择器使用的包名;显式别名优先于路径末段。
alias := filepath.Base(importPath)
if imported.Name != nil {
alias = imported.Name.Name
}
if alias != "_" && alias != "." {
aliases[alias] = struct{}{}
}
}
return aliases
}
// isInternalConstructionCall 判断构造调用是否来自应用/adapter 包或依赖 factory 链。
func isInternalConstructionCall(receiver ast.Expr, internalAliases map[string]struct{}) bool {
// identifier 是直接包名调用,例如 orderapp.NewRefreshJobRunner。
if identifier, ok := receiver.(*ast.Ident); ok {
// found 表示该直接接收者是否是 application 或 adapter 的本地导入别名。
_, found := internalAliases[identifier.Name]
return found
}
// selector 表示依赖 factory 链,例如 dependencies.ItemDependencies.NewItemBatchRepository。
_, isFactoryChain := receiver.(*ast.SelectorExpr)
return isFactoryChain
}
// checkStageTwoCmdCalls 拒绝 cmd/server 通过 Server API 或 factory 间接重新承担业务组合根职责。
func checkStageTwoCmdCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
// violations 保存入口层违反阶段二边界的位置。
var violations []violation
ast.Inspect(syntax, func(node ast.Node) bool {
// call 是当前待检查的函数或方法调用。
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
// selector 表示当前调用的接收者与名称。
selector, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
// name 是被调用的构造或生命周期访问器名称。
name := selector.Sel.Name
if name == "NewApplicationServices" || name == "LifecycleComponents" || name == "ApplicationServices" {
violations = append(violations, violation{file: relativePath, line: fset.Position(call.Pos()).Line, message: fmt.Sprintf("cmd/server 禁止通过 %s 使用 Server 组合根;必须调用 internal/composition", name)})
}
return true
})
return violations
}
// checkServerInfrastructureFields 禁止 HTTP Server 保存业务运行时或具体平台实现,避免 transport 成为组合根。
func checkServerInfrastructureFields(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
}
// forbiddenTypes 记录 Server 不得作为字段持有者的业务运行时和平台实现类型。
forbiddenTypes := map[string]string{
"account.Manager": "账号 Manager 必须由进程组合根和应用 Port 持有,Server 只能调用应用服务",
"automation.Center": "自动化 Center 必须由应用层持有,Server 不能保存业务 worker",
"notify.Notifier": "通知器必须通过通知应用 Port 使用,Server 不能保存基础设施实现",
"adapter.PlatformDependencies": "具体平台依赖必须在组合根封装为消费者定义的 Port",
"adapter.MTOPClient": "MTOP 客户端必须通过应用 Port 或不可变平台 Port 提供",
"adapter.LongLoginClient": "长登录客户端必须通过应用 Port 或不可变平台 Port 提供",
"adapter.QRLoginService": "二维码客户端必须通过应用 Port 或不可变平台 Port 提供",
}
// violations 保存 Server 结构体字段违反基础设施持有边界的扫描结果。
var violations []violation
// declaration 是当前文件中的类型声明,只有 Server 结构体需要本规则检查。
for _, declaration := range syntax.Decls {
// generalDeclaration 表示可能包含类型定义的声明。
generalDeclaration, ok := declaration.(*ast.GenDecl)
if !ok || generalDeclaration.Tok != token.TYPE {
continue
}
// specification 是当前声明中的一个类型定义。
for _, specification := range generalDeclaration.Specs {
// typeSpecification 表示具体类型名及其语法树。
typeSpecification, ok := specification.(*ast.TypeSpec)
if !ok || typeSpecification.Name.Name != "Server" {
continue
}
// structure 表示 Server 的字段集合;非结构体类型不适用本规则。
structure, ok := typeSpecification.Type.(*ast.StructType)
if !ok {
continue
}
// field 是当前待检查的 Server 字段。
for _, field := range structure.Fields.List {
// typeName 是去掉指针层后的限定类型名;未知表达式保持空字符串。
typeName := qualifiedTypeName(field.Type)
// message、forbidden 分别表示字段类型的禁止原因及其是否命中。
message, forbidden := forbiddenTypes[typeName]
if !forbidden {
continue
}
violations = append(violations, violation{file: normalizedPath, line: fset.Position(field.Pos()).Line, message: message})
}
}
}
return violations
}
// qualifiedTypeName 返回指针、选择器或标识符类型的稳定文本名,供结构体字段边界规则使用。
func qualifiedTypeName(expression ast.Expr) string {
// pointer 表示字段是否以指针形式声明;边界规则不区分值与指针持有。
if pointer, ok := expression.(*ast.StarExpr); ok {
return qualifiedTypeName(pointer.X)
}
// selector 表示包限定类型,例如 adapter.MTOPClient。
if selector, ok := expression.(*ast.SelectorExpr); ok {
// packageName、ok 分别表示选择器左侧是否为可解析的包标识符。
packageName, ok := selector.X.(*ast.Ident)
if ok {
return packageName.Name + "." + selector.Sel.Name
}
}
// identifier 表示当前字段是否为未限定类型;本规则当前不禁止未限定类型。
if identifier, ok := expression.(*ast.Ident); ok {
return identifier.Name
}
return ""
}
// checkServerCompositionCalls 禁止已迁出的应用 worker 组合逻辑回流到 Server transport 包。
func checkServerCompositionCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
// normalizedPath 是统一使用斜杠的仓库相对路径。
@@ -361,16 +829,16 @@ func checkHTTPResponseContracts(relativePath string, syntax *ast.File, fset *tok
return violations
}
// isControlledDynamicResponseType 判断已登记的动态键兼容响应,避免本阶段改变旧客户端 JSON 形状。
// isControlledDynamicResponseType 判断已登记的动态键兼容响应,避免在未满足 Sunset 条件前改变旧客户端 JSON 形状。
func isControlledDynamicResponseType(name string) bool {
// ok 表示响应类型是否已在阶段 9 的兼容登记表中备案。
// ok 表示响应类型是否已在带 Sunset 条件的兼容登记表中备案。
_, ok := controlledDynamicResponses[name]
return ok
}
// isForbiddenHiddenDependencyImport 禁止应用与 Server 通过反射、插件机制或动态加载隐藏必需依赖。
func isForbiddenHiddenDependencyImport(filePath, importedPath string) bool {
// productionLayer 表示阶段 9 需要封死隐式装配旁路的生产层。
// productionLayer 表示必须封死隐式装配旁路的生产层。
productionLayer := (strings.HasPrefix(filePath, "internal/application/") && !strings.HasSuffix(filePath, "_test.go")) ||
(strings.HasPrefix(filePath, "internal/server/") && !strings.HasSuffix(filePath, "_test.go"))
if !productionLayer {
@@ -384,11 +852,11 @@ func isForbiddenHiddenDependencyImport(filePath, importedPath string) bool {
return false
}
// checkCompatibilityGovernance 校验动态响应白名单、Sunset 版本与运行时遥测保持同步。
// checkCompatibilityGovernance 校验受控动态响应登记、Sunset 版本与运行时遥测保持同步。
func checkCompatibilityGovernance(root string) []violation {
// matrixPath 是记录外部调用方、删除条件和 Sunset 版本的兼容矩阵路径。
matrixPath := filepath.Join(root, "docs", "architecture", "api-compatibility-matrix.md")
// matrixBytes 是兼容矩阵原文,用于避免白名单脱离文档治理。
// matrixBytes 是兼容矩阵原文,用于避免受控兼容响应脱离文档治理。
matrixBytes, err := os.ReadFile(matrixPath)
if err != nil {
return []violation{{file: filepath.ToSlash(filepath.Join("docs", "architecture", "api-compatibility-matrix.md")), line: 1, message: fmt.Sprintf("无法读取兼容矩阵: %v", err)}}
+211 -1
View File
@@ -3,6 +3,8 @@ package main
import (
"go/parser"
"go/token"
"os"
"path/filepath"
"testing"
)
@@ -138,7 +140,7 @@ func TestApplicationImportBoundary(t *testing.T) {
}
}
// TestServerLowLevelBoundary 验证 Server 低层依赖不得通过临时白名单保留。
// TestServerLowLevelBoundary 验证 Server 低层依赖不得通过临时例外保留。
func TestServerLowLevelBoundary(t *testing.T) {
if !isForbiddenServerLowLevelImport("internal/server/cookie_handlers.go", "internal/db") {
t.Fatal("Server 低层依赖应被门禁拒绝")
@@ -244,6 +246,36 @@ func handler(server any) { server.ApplicationLifecycleComponents() }
}
}
// TestServerInfrastructureFieldBoundary 验证生产 Server 不能重新保存业务运行时或具体平台客户端。
func TestServerInfrastructureFieldBoundary(t *testing.T) {
// fset 是模拟 Server 源码的统一位置集合。
fset := token.NewFileSet()
// syntax、parseErr 分别是包含禁止字段的模拟 Server 文件及其解析错误。
syntax, parseErr := parser.ParseFile(fset, "server.go", []byte(`package server
type Server struct { Manager *account.Manager; Client adapter.MTOPClient; Port PlatformPort }
`), parser.ParseComments)
if parseErr != nil {
t.Fatal(parseErr)
}
// violations 是禁止字段必须触发的架构违规。
violations := checkServerInfrastructureFields("internal/server/server.go", syntax, fset)
if len(violations) != 2 {
t.Fatalf("violations=%+v", violations)
}
// cleanSyntax、cleanErr 分别是只持有消费者定义 Port 的合规 Server 源码及其解析错误。
cleanSyntax, cleanErr := parser.ParseFile(fset, "clean.go", []byte(`package server
type Server struct { Port PlatformPort }
`), parser.ParseComments)
if cleanErr != nil {
t.Fatal(cleanErr)
}
// cleanViolations 是合规 Server 应保持为空的扫描结果。
cleanViolations := checkServerInfrastructureFields("internal/server/clean.go", cleanSyntax, fset)
if len(cleanViolations) != 0 {
t.Fatalf("clean violations=%+v", cleanViolations)
}
}
// TestApplicationTypeLeakBoundary 验证应用 Port 类型扫描会拒绝基础设施和 Server 类型。
func TestApplicationTypeLeakBoundary(t *testing.T) {
// fset 是测试源代码的文件位置集合。
@@ -273,3 +305,181 @@ type Good struct { ID string }
t.Fatalf("clean violations=%+v", cleanViolations)
}
}
// TestStageTwoServerBoundary 验证阶段二会拒绝 Server 内残留的组合根、平台 Port 与基础设施导入。
func TestStageTwoServerBoundary(t *testing.T) {
// fset 是模拟 Server 源码的统一位置集合。
fset := token.NewFileSet()
// syntax、parseErr 分别是包含阶段二禁止依赖和声明的模拟 Server 源码及解析失败原因。
syntax, parseErr := parser.ParseFile(fset, "server.go", []byte(`package server
import "xianyu-go/internal/adapter"
type ApplicationServices struct{}
type PlatformPort interface{}
func (s *Server) ApplicationServices() *ApplicationServices { return nil }
func (s *Server) mtopClient() adapter.MTOPClient { return nil }
`), parser.ParseComments)
if parseErr != nil {
t.Fatal(parseErr)
}
// violations 是组合根和平台旁路必须产生的违规集合。
violations := checkStageTwoTransportBoundary("internal/server/server.go", syntax, fset)
if len(violations) != 5 {
t.Fatalf("violations=%+v", violations)
}
}
// TestStageTwoConstructionBoundary 验证构造门禁只拒绝应用/adapter 构造与 factory 链,不误伤标准库调用。
func TestStageTwoConstructionBoundary(t *testing.T) {
// fset 是模拟 Server 源码的统一位置集合。
fset := token.NewFileSet()
// syntax、parseErr 分别是包含标准库、应用构造和 factory 链的模拟 Server 源码及解析失败原因。
syntax, parseErr := parser.ParseFile(fset, "composition.go", []byte(`package server
import json "encoding/json"
import orderapp "xianyu-go/internal/application/orders"
func build() { json.NewEncoder(nil); orderapp.NewRefreshJobRunner(nil, nil, orderapp.RefreshJobRunnerOptions{}); dependencies.ItemDependencies.NewItemBatchRepository() }
`), parser.ParseComments)
if parseErr != nil {
t.Fatal(parseErr)
}
// violations 是应用构造与 factory 链必须产生的违规集合;json.NewEncoder 不应触发。
violations := checkStageTwoServerConstruction("internal/server/composition.go", syntax, fset)
if len(violations) != 2 {
t.Fatalf("violations=%+v", violations)
}
}
// TestStageTwoCmdBoundary 验证 cmd/server 不能通过 Server API 间接装配应用服务或反向取得生命周期组件。
func TestStageTwoCmdBoundary(t *testing.T) {
// fset 是模拟 cmd/server 源码的统一位置集合。
fset := token.NewFileSet()
// syntax、parseErr 分别是包含旧组合根 API 的模拟入口源码及解析失败原因。
syntax, parseErr := parser.ParseFile(fset, "main.go", []byte(`package main
func build() { server.NewApplicationServices(nil); applications.LifecycleComponents() }
`), parser.ParseComments)
if parseErr != nil {
t.Fatal(parseErr)
}
// violations 是旧 Server 组合根 API 必须产生的违规集合。
violations := checkStageTwoCmdCalls("cmd/server/main.go", syntax, fset)
if len(violations) != 2 {
t.Fatalf("violations=%+v", violations)
}
}
// TestStageTwoCompositionRootBoundary 验证空目录和未被 cmd/server 调用的伪组合层不能通过阶段二门禁。
func TestStageTwoCompositionRootBoundary(t *testing.T) {
// root 是独立临时仓库根目录,避免真实工作树状态影响结构性单元测试。
root := t.TempDir()
// missingViolations 是缺少 composition 目录时应产生的违规集合。
missingViolations := checkStageTwoCompositionRoot(root)
if len(missingViolations) != 1 {
t.Fatalf("missing violations=%+v", missingViolations)
}
// compositionDir 是满足阶段二目录形态的最小独立组合层目录。
compositionDir := filepath.Join(root, "internal", "composition")
// mkdirErr 表示创建临时组合层目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(compositionDir, 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// compositionSource 是组合层最小生产文件;只有测试文件不能替代生产组合根。
compositionSource := []byte("package composition\n")
// writeErr 表示写入临时组合层生产文件失败的文件系统原因。
if writeErr := os.WriteFile(filepath.Join(compositionDir, "composition.go"), compositionSource, 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// commandDir 是最小 cmd/server 入口目录。
commandDir := filepath.Join(root, "cmd", "server")
// mkdirErr 表示创建临时入口目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(commandDir, 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// commandSource 是显式引用组合层的最小入口源码。
commandSource := []byte("package main\nimport _ \"xianyu-go/internal/composition\"\n")
// writeErr 表示写入临时入口源码失败的文件系统原因。
if writeErr := os.WriteFile(filepath.Join(commandDir, "main.go"), commandSource, 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// cleanViolations 是满足独立组合层和入口调用关系后的违规集合。
cleanViolations := checkStageTwoCompositionRoot(root)
if len(cleanViolations) != 0 {
t.Fatalf("clean violations=%+v", cleanViolations)
}
}
// TestStageTwoApplicationPortBoundary 验证 HTTP Port 容器不能以具体应用服务指针伪装最小依赖。
func TestStageTwoApplicationPortBoundary(t *testing.T) {
// fset 是模拟 Server Port 源码的位置集合。
fset := token.NewFileSet()
// syntax、parseErr 分别是同时包含违规具体服务指针和合规消费者接口的模拟源码及解析错误。
syntax, parseErr := parser.ParseFile(fset, "application_ports.go", []byte(`package server
import accountapp "xianyu-go/internal/application/account"
type ApplicationPorts struct { Bad *accountapp.RuntimeService; Good AccountRuntimePort }
type ApplicationPortsInput struct { Nested []*accountapp.ProfileService }
type AccountRuntimePort interface{}
`), parser.ParseComments)
if parseErr != nil {
t.Fatal(parseErr)
}
// violations 是具体应用服务指针必须触发的违规集合。
violations := checkStageTwoApplicationPortDeclarations("internal/server/application_ports.go", syntax, fset)
if len(violations) != 2 {
t.Fatalf("violations=%+v", violations)
}
// cleanSyntax、cleanErr 分别是仅声明消费者接口的合规源码及解析错误。
cleanSyntax, cleanErr := parser.ParseFile(fset, "application_ports.go", []byte(`package server
type ApplicationPorts struct { Runtime AccountRuntimePort }
type ApplicationPortsInput struct { Runtime AccountRuntimePort }
type AccountRuntimePort interface{}
`), parser.ParseComments)
if cleanErr != nil {
t.Fatal(cleanErr)
}
// cleanViolations 是合规 Port 容器应保持为空的扫描结果。
cleanViolations := checkStageTwoApplicationPortDeclarations("internal/server/application_ports.go", cleanSyntax, fset)
if len(cleanViolations) != 0 {
t.Fatalf("clean violations=%+v", cleanViolations)
}
}
// TestStageTwoCompositionProjectionBoundary 验证 composition 核心不能反向导入 HTTP Server。
func TestStageTwoCompositionProjectionBoundary(t *testing.T) {
// fset 是模拟 composition 源码的位置集合。
fset := token.NewFileSet()
// syntax、parseErr 分别是错误依赖 Server 的 composition 核心源码及解析错误。
syntax, parseErr := parser.ParseFile(fset, "services.go", []byte(`package composition
import "xianyu-go/internal/server"
var _ server.Dependencies
`), parser.ParseComments)
if parseErr != nil {
t.Fatal(parseErr)
}
// violations 是组合核心反向依赖必须触发的违规集合。
violations := checkStageTwoCompositionProjection("internal/composition/services.go", syntax, fset)
if len(violations) != 1 {
t.Fatalf("violations=%+v", violations)
}
// cleanViolations 是 runtime 投影层的合法依赖应保持为空的扫描结果。
if cleanViolations := checkStageTwoCompositionProjection("internal/composition/runtime/server_dependencies.go", syntax, fset); len(cleanViolations) != 0 {
t.Fatalf("runtime projection violations=%+v", cleanViolations)
}
}
// TestStageTwoRealSourceGate 验证完成迁移后的真实仓库源码必须通过阶段二门禁。
func TestStageTwoRealSourceGate(t *testing.T) {
// root 是当前阶段二迁移后的真实仓库根目录。
root := repositoryRootForContractTest(t)
// violations、checkErr 分别是真实源码扫描结果和扫描失败原因。
violations, checkErr := checkRepository(root)
if checkErr != nil {
t.Fatal(checkErr)
}
if len(violations) != 0 {
// joined 是将全部违规位置拼接为便于定位的失败诊断文本。
joined := ""
// violation 是当前一条真实源码架构违规,按扫描顺序汇总。
for _, violation := range violations {
joined += violation.file + " " + violation.message + "\n"
}
t.Fatalf("完成迁移后的真实源码仍违反阶段二门禁:\n%s", joined)
}
}
+427
View File
@@ -0,0 +1,427 @@
package main
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
)
const (
// architectureStageBaseline 表示始终启用的依赖方向、API 契约和隐藏依赖基础门禁。
architectureStageBaseline = 1
// architectureStageServerComposition 在阶段二启用 Server 组合根与平台旁路门禁。
architectureStageServerComposition = 2
// architectureStageLifecycle 在阶段三启用后台任务 Context 与生命周期所有权门禁。
architectureStageLifecycle = 3
// architectureStageReact 在阶段四启用 React feature、契约与网络访问边界门禁。
architectureStageReact = 4
// architectureStageDatabase 在阶段五启用上层裸数据库与事务泄露门禁。
architectureStageDatabase = 5
// architectureStageClosure 在阶段六启用复杂度、超大文件与最终兼容收口门禁。
architectureStageClosure = 6
)
// architectureGateDefinition 描述一组预先建立的架构规则及其最早激活阶段。
type architectureGateDefinition struct {
// name 是稳定的门禁标识,供测试和失败诊断使用。
name string
// activationStage 是该门禁开始阻断合并的正式阶段编号。
activationStage int
// description 是该门禁保护的架构边界摘要。
description string
}
// architectureGateCatalog 是六阶段重构使用的完整门禁目录;进入阶段只改变激活范围,不临时发明规则。
var architectureGateCatalog = []architectureGateDefinition{
{name: "baseline-boundaries", activationStage: architectureStageBaseline, description: "依赖方向、API 契约、隐藏依赖与兼容登记"},
{name: "server-composition", activationStage: architectureStageServerComposition, description: "Server 组合根、平台旁路与生命周期反转"},
{name: "worker-lifecycle", activationStage: architectureStageLifecycle, description: "后台任务 Context、取消与静态所有权清单"},
{name: "react-feature-boundary", activationStage: architectureStageReact, description: "React feature、传输契约、网络与动态导入边界"},
{name: "database-boundary", activationStage: architectureStageDatabase, description: "上层裸数据库、事务与持久化模型泄露"},
{name: "quality-closure", activationStage: architectureStageClosure, description: "复杂度、超大文件、兼容登记与最终架构收口"},
}
// architectureStageEnabled 判断指定门禁是否已随当前阶段开启;前序阶段门禁不会再次关闭。
func architectureStageEnabled(activeStage, activationStage int) bool {
return activeStage >= activationStage
}
// readActiveArchitectureStage 从唯一总计划状态表读取当前阶段,拒绝缺失、重复或越界声明。
func readActiveArchitectureStage(root string) (int, error) {
// planPath 是唯一允许声明当前阶段的总计划文件。
planPath := filepath.Join(root, "docs", "architecture", "refactoring-master-plan.md")
// raw、readErr 分别是总计划原文及读取失败原因。
raw, readErr := os.ReadFile(planPath)
if readErr != nil {
return 0, fmt.Errorf("读取重构总计划失败: %w", readErr)
}
// currentPattern 匹配状态表中唯一标记为当前阶段的阶段编号。
currentPattern := regexp.MustCompile(`(?m)^\|\s*([1-6])\.[^|]*\|\s*当前阶段\s*\|`)
// matches 保存状态表中的全部当前阶段匹配,必须且只能存在一项。
matches := currentPattern.FindAllSubmatch(raw, -1)
if len(matches) == 0 {
// completedPattern 只允许在阶段六已经明确完成后保持全量门禁永久开启。
completedPattern := regexp.MustCompile(`(?m)^\|\s*6\.[^|]*\|\s*已完成\s*\|`)
if completedPattern.Match(raw) {
return architectureStageClosure, nil
}
}
if len(matches) != 1 {
return 0, fmt.Errorf("重构总计划必须且只能声明一个当前阶段,实际匹配 %d 项", len(matches))
}
// stage、parseErr 分别是当前阶段编号及数字解析失败原因。
stage, parseErr := strconv.Atoi(string(matches[0][1]))
if parseErr != nil || stage < architectureStageBaseline || stage > architectureStageClosure {
return 0, fmt.Errorf("无效的当前架构阶段 %q", matches[0][1])
}
return stage, nil
}
// checkActivatedRepositoryGates 执行当前阶段及全部前序阶段已经激活的仓库级规则。
func checkActivatedRepositoryGates(root string, activeStage int) []violation {
// violations 保存后续阶段规则在当前激活范围内发现的全部违规。
var violations []violation
if architectureStageEnabled(activeStage, architectureStageLifecycle) {
violations = append(violations, checkLifecycleArchitecture(root)...)
}
if architectureStageEnabled(activeStage, architectureStageReact) {
violations = append(violations, checkReactArchitecture(root)...)
}
if architectureStageEnabled(activeStage, architectureStageDatabase) {
violations = append(violations, checkDatabaseArchitecture(root)...)
}
if architectureStageEnabled(activeStage, architectureStageClosure) {
violations = append(violations, checkQualityArchitecture(root)...)
}
return violations
}
// checkLifecycleArchitecture 禁止后台组件使用脱离所有者的根 Context,并要求静态清单保留完整边界字段。
func checkLifecycleArchitecture(root string) []violation {
// violations 保存阶段三生命周期边界违规。
var violations []violation
// lifecycleRoots 是拥有后台 worker 或慢外部调用的生产包前缀。
lifecycleRoots := []string{"internal/account/", "internal/automation/", "internal/browser/", "internal/engine/", "internal/notify/", "internal/renewal/"}
violations = append(violations, scanGoProductionFiles(root, func(relativePath string, source []byte) []violation {
// inLifecyclePackage 表示当前文件是否属于需要显式继承所有者 Context 的生产包。
inLifecyclePackage := false
// lifecycleRoot 是当前待匹配的后台组件包前缀。
for _, lifecycleRoot := range lifecycleRoots {
if strings.HasPrefix(relativePath, lifecycleRoot) {
inLifecyclePackage = true
break
}
}
if !inLifecyclePackage {
return nil
}
// findings 保存当前文件中会脱离所有者取消链的根 Context 调用。
var findings []violation
// tokenText 是当前禁止在后台组件中出现的根 Context 构造文本。
for _, tokenText := range []string{"context.Background()", "context.TODO()"} {
// offset 是当前根 Context 调用在源码中的字节位置。
offset := strings.Index(string(source), tokenText)
if offset >= 0 {
findings = append(findings, violation{file: relativePath, line: sourceLineAt(source, offset), message: "后台组件禁止使用根 Context;必须继承 owner Context 或使用有界关闭 Context"})
}
}
return findings
})...)
// inventoryPath 是必须描述 owner、Context、Cancel 与 Wait/Join 的生命周期清单。
inventoryPath := filepath.Join(root, "docs", "architecture", "lifecycle-inventory.md")
// inventory、readErr 分别是生命周期清单原文及读取失败原因。
inventory, readErr := os.ReadFile(inventoryPath)
if readErr != nil {
return append(violations, violation{file: "docs/architecture/lifecycle-inventory.md", line: 1, message: fmt.Sprintf("无法读取生命周期清单: %v", readErr)})
}
// requiredTerm 是生命周期清单不可删除的所有权与收束语义。
for _, requiredTerm := range []string{"所有者", "Context 来源", "停止/关闭", "等待/观测", "Wait/Join", "锁顺序"} {
if !strings.Contains(string(inventory), requiredTerm) {
violations = append(violations, violation{file: "docs/architecture/lifecycle-inventory.md", line: 1, message: fmt.Sprintf("生命周期清单缺少必填边界 %q", requiredTerm)})
}
}
return violations
}
// checkReactArchitecture 检查 feature 物理边界、契约直连、网络旁路、动态导入和严格类型选项。
func checkReactArchitecture(root string) []violation {
// violations 保存阶段四前端架构违规。
var violations []violation
// frontendRoot 是 React/Vite 源码根目录。
frontendRoot := filepath.Join(root, "frontend")
// forbiddenFiles 是阶段四必须物理删除或迁入 feature 的集中入口。
forbiddenFiles := []string{"services/amapLocation.ts", "shared/api-contract/index.ts"}
// forbiddenFile 是当前待确认已删除的前端集中入口。
for _, forbiddenFile := range forbiddenFiles {
// statErr 表示当前集中入口是否已经完成物理迁移或删除。
if _, statErr := os.Stat(filepath.Join(frontendRoot, filepath.FromSlash(forbiddenFile))); statErr == nil {
violations = append(violations, violation{file: "frontend/" + forbiddenFile, line: 1, message: "阶段四禁止根级服务或大型契约 barrel;必须迁入所属 feature 或领域契约模块"})
}
}
// modulePattern 提取静态 import、re-export 和动态 import 的模块路径。
modulePattern := regexp.MustCompile(`(?m)(?:from\s+|import\s*\()\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)
if relativePath != "shared/http/client.ts" && (strings.Contains(sourceText, "fetch(") || regexp.MustCompile(`\baxios\b`).MatchString(sourceText)) {
violations = append(violations, violation{file: "frontend/" + relativePath, line: 1, message: "前端生产代码不得绕过 shared/http/client 直接请求网络"})
}
if relativePath != "app/shell/AuthenticatedShell.tsx" && strings.Contains(sourceText, "import(") {
violations = append(violations, violation{file: "frontend/" + relativePath, line: 1, message: "动态 import 只能用于路由级页面加载,禁止隐藏 feature 依赖"})
}
// matches 是当前源码中全部模块路径声明。
matches := modulePattern.FindAllStringSubmatch(sourceText, -1)
// match 是当前待检查的模块路径匹配结果。
for _, match := range matches {
// specifier 是 import/export 声明引用的模块路径。
specifier := match[1]
if strings.HasSuffix(specifier, "shared/api-contract") {
violations = append(violations, violation{file: "frontend/" + relativePath, line: sourceLineAt(source, strings.Index(sourceText, match[0])), message: "feature 必须直接导入领域契约模块,禁止依赖 shared/api-contract barrel"})
}
violations = append(violations, checkCrossFeatureImport(relativePath, specifier)...)
}
return nil
})
if walkErr != nil {
violations = append(violations, violation{file: "frontend", line: 1, message: fmt.Sprintf("扫描前端架构失败: %v", walkErr)})
}
// tsconfigPath 是必须启用未使用符号检查的前端 TypeScript 配置。
tsconfigPath := filepath.Join(frontendRoot, "tsconfig.json")
// tsconfigBytes、readErr 分别是 TypeScript 配置原文及读取失败原因。
tsconfigBytes, readErr := os.ReadFile(tsconfigPath)
if readErr != nil {
return append(violations, violation{file: "frontend/tsconfig.json", line: 1, message: fmt.Sprintf("无法读取 TypeScript 配置: %v", readErr)})
}
// tsconfig 是用于读取 compilerOptions 的最小结构化配置。
var tsconfig struct {
CompilerOptions map[string]any `json:"compilerOptions"`
}
// parseErr 表示 TypeScript JSON 配置无法结构化解析的原因。
if parseErr := json.Unmarshal(tsconfigBytes, &tsconfig); parseErr != nil {
return append(violations, violation{file: "frontend/tsconfig.json", line: 1, message: fmt.Sprintf("无法解析 TypeScript 配置: %v", parseErr)})
}
// optionName 是当前必须开启的 TypeScript 未使用符号检查选项。
for _, optionName := range []string{"noUnusedLocals", "noUnusedParameters"} {
// enabled、ok 分别是配置值及其是否为布尔类型。
if enabled, ok := tsconfig.CompilerOptions[optionName].(bool); !ok || !enabled {
violations = append(violations, violation{file: "frontend/tsconfig.json", line: 1, message: fmt.Sprintf("阶段四必须启用 compilerOptions.%s", optionName)})
}
}
return violations
}
// checkCrossFeatureImport 拒绝 feature 直接导入另一个 feature 的内部实现。
func checkCrossFeatureImport(sourcePath, specifier string) []violation {
// sourceFeature 是当前源码所属的直属 feature 名称。
sourceFeature := featureName(sourcePath)
if sourceFeature == "" || !strings.HasPrefix(specifier, ".") {
return nil
}
// resolved 是相对导入解析到 frontend 根下的稳定路径。
resolved := filepath.ToSlash(filepath.Clean(filepath.Join(filepath.Dir(sourcePath), specifier)))
// targetFeature 是导入目标所属的直属 feature 名称。
targetFeature := featureName(resolved)
if targetFeature != "" && targetFeature != sourceFeature {
return []violation{{file: "frontend/" + sourcePath, line: 1, message: fmt.Sprintf("feature %s 禁止导入 feature %s 的内部实现", sourceFeature, targetFeature)}}
}
return nil
}
// featureName 返回 app/features 路径下的直属 feature 名称。
func featureName(path string) string {
// parts 是使用斜杠切分后的源码路径片段。
parts := strings.Split(filepath.ToSlash(path), "/")
if len(parts) >= 3 && parts[0] == "app" && parts[1] == "features" {
return parts[2]
}
return ""
}
// checkDatabaseArchitecture 禁止应用、Server 和业务运行时泄露裸 SQL 连接、事务或 Store.DB。
func checkDatabaseArchitecture(root string) []violation {
// upperRoots 是阶段五不得操作裸数据库的上层生产包。
upperRoots := []string{"internal/account/", "internal/application/", "internal/automation/", "internal/chat/", "internal/engine/", "internal/notify/", "internal/server/"}
// rawDatabasePattern 匹配裸 SQL 类型、事务入口和 Store.DB 旁路。
rawDatabasePattern := regexp.MustCompile(`\*sql\.(?:DB|Tx|Row|Rows|Stmt)\b|\.BeginTx\s*\(|\.DB\b`)
return scanGoProductionFiles(root, func(relativePath string, source []byte) []violation {
// isUpperLayer 表示当前文件是否属于禁止裸数据库访问的生产层。
isUpperLayer := false
// upperRoot 是当前待匹配的上层包前缀。
for _, upperRoot := range upperRoots {
if strings.HasPrefix(relativePath, upperRoot) {
isUpperLayer = true
break
}
}
if !isUpperLayer {
return nil
}
// match 是当前文件首次命中的裸数据库访问位置。
match := rawDatabasePattern.FindIndex(source)
if match == nil {
return nil
}
return []violation{{file: relativePath, line: sourceLineAt(source, match[0]), message: "上层生产代码禁止暴露 sql.DB/sql.Tx、BeginTx 或 Store.DB;必须使用窄 repository 或应用 Unit of Work"}}
})
}
// checkQualityArchitecture 对非冻结生产源码执行超大文件、超长函数和高分支复杂度收口。
func checkQualityArchitecture(root string) []violation {
// violations 保存阶段六质量与可维护性违规。
var violations []violation
// frozenPaths 是冻结 CAPTCHA 规范明确保护、禁止借质量收口修改的精确文件集合。
frozenPaths := map[string]struct{}{
"internal/browser/slider.go": {},
"internal/browser/token_captcha.go": {},
"internal/browser/token_captcha_fallback.go": {},
}
violations = append(violations, scanGoProductionFiles(root, func(relativePath string, source []byte) []violation {
// frozen 表示当前文件是否受 CAPTCHA 冻结规范保护,禁止因质量阈值修改。
if _, frozen := frozenPaths[relativePath]; frozen || isGeneratedSource(source) {
return nil
}
// findings 保存当前生产 Go 文件的尺寸和函数复杂度违规。
var findings []violation
// lineCount 是当前生产文件的物理行数。
lineCount := 1 + strings.Count(string(source), "\n")
if lineCount > 800 {
findings = append(findings, violation{file: relativePath, line: 1, message: fmt.Sprintf("生产 Go 文件超过 800 行(当前 %d 行),必须按业务职责拆分", lineCount)})
}
// fset 是当前文件函数位置和跨度的源码位置集合。
fset := token.NewFileSet()
// syntax、parseErr 分别是当前文件 AST 及解析失败原因。
syntax, parseErr := parser.ParseFile(fset, relativePath, source, 0)
if parseErr != nil {
return append(findings, violation{file: relativePath, line: 1, message: fmt.Sprintf("复杂度扫描解析失败: %v", parseErr)})
}
// declaration 是当前待检查的顶层函数或方法声明。
for _, declaration := range syntax.Decls {
// function、ok 分别是当前声明是否为函数及断言结果。
function, ok := declaration.(*ast.FuncDecl)
if !ok || function.Body == nil {
continue
}
// startLine 是函数声明起始行号。
startLine := fset.Position(function.Pos()).Line
// endLine 是函数声明结束行号,用于计算单函数物理跨度。
endLine := fset.Position(function.End()).Line
// branches 是函数内条件、循环、分支 case 与 select 的近似复杂度计数。
branches := 1
ast.Inspect(function.Body, func(node ast.Node) bool {
switch node.(type) {
case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.CaseClause, *ast.CommClause:
branches++
}
return true
})
if endLine-startLine+1 > 180 || branches > 40 {
findings = append(findings, violation{file: relativePath, line: startLine, message: fmt.Sprintf("函数 %s 过大或分支过多(%d 行,复杂度计数 %d),必须按业务责任拆分", function.Name.Name, endLine-startLine+1, branches)})
}
}
return findings
})...)
return violations
}
// scanGoProductionFiles 遍历全部非测试 Go 生产源码,并把每个文件交给指定规则检查。
func scanGoProductionFiles(root string, inspect func(relativePath string, source []byte) []violation) []violation {
// violations 保存遍历、读取与调用方规则产生的全部违规。
var violations []violation
// walkErr 是生产 Go 源码遍历失败原因。
walkErr := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() {
if entry.Name() == ".git" || entry.Name() == "node_modules" || entry.Name() == "coverage" || entry.Name() == "static" {
return filepath.SkipDir
}
return nil
}
if filepath.Ext(path) != ".go" || strings.HasSuffix(path, "_test.go") {
return nil
}
// relativePath 是当前 Go 文件相对于仓库根目录的稳定斜杠路径。
relativePath, relativeErr := filepath.Rel(root, path)
if relativeErr != nil {
return relativeErr
}
relativePath = filepath.ToSlash(relativePath)
// source、readErr 分别是当前生产 Go 源码及读取失败原因。
source, readErr := os.ReadFile(path)
if readErr != nil {
return readErr
}
violations = append(violations, inspect(relativePath, source)...)
return nil
})
if walkErr != nil {
violations = append(violations, violation{file: ".", line: 1, message: fmt.Sprintf("遍历生产 Go 源码失败: %v", walkErr)})
}
return violations
}
// isFrontendProductionPath 判断路径是否为需要架构扫描的 TypeScript/TSX 生产源码。
func isFrontendProductionPath(path string) bool {
// extension 是当前前端源码扩展名。
extension := filepath.Ext(path)
if extension != ".ts" && extension != ".tsx" {
return false
}
// base 是当前源码文件名,用于排除测试和规格文件。
base := filepath.Base(path)
return !strings.Contains(base, ".test.") && !strings.Contains(base, ".spec.")
}
// sourceLineAt 将源码字节偏移转换为一开始的行号,负偏移安全回退到首行。
func sourceLineAt(source []byte, offset int) int {
if offset <= 0 {
return 1
}
if offset > len(source) {
offset = len(source)
}
return 1 + strings.Count(string(source[:offset]), "\n")
}
// isGeneratedSource 判断 Go 文件是否由工具生成,生成源码不接受人工复杂度重构。
func isGeneratedSource(source []byte) bool {
// firstLines 是生成标记通常出现的文件头区域。
firstLines := string(source)
if len(firstLines) > 512 {
firstLines = firstLines[:512]
}
return strings.Contains(firstLines, "Code generated") && strings.Contains(firstLines, "DO NOT EDIT")
}
@@ -0,0 +1,190 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
// TestArchitectureGateCatalogActivatesMonotonically 验证所有阶段门禁均已预注册且只会随阶段递增开启。
func TestArchitectureGateCatalogActivatesMonotonically(t *testing.T) {
// expectedStages 是六阶段计划中必须存在的门禁激活顺序。
expectedStages := []int{architectureStageBaseline, architectureStageServerComposition, architectureStageLifecycle, architectureStageReact, architectureStageDatabase, architectureStageClosure}
if len(architectureGateCatalog) != len(expectedStages) {
t.Fatalf("门禁目录数量=%d,期望=%d", len(architectureGateCatalog), len(expectedStages))
}
// index 是当前门禁目录位置;expectedStage 是该位置必须对应的激活阶段。
for index, expectedStage := range expectedStages {
// gate 是当前顺序位置的完整门禁定义。
gate := architectureGateCatalog[index]
if gate.activationStage != expectedStage || gate.name == "" || gate.description == "" {
t.Fatalf("门禁目录项=%+v,期望阶段=%d", gate, expectedStage)
}
if !architectureStageEnabled(expectedStage, gate.activationStage) || architectureStageEnabled(expectedStage-1, gate.activationStage) {
t.Fatalf("门禁 %s 未遵守阶段激活边界", gate.name)
}
}
}
// TestReadActiveArchitectureStage 验证总计划缺失或重复当前阶段时门禁直接失败。
func TestReadActiveArchitectureStage(t *testing.T) {
// root 是存放临时总计划的独立目录。
root := t.TempDir()
// planPath 是门禁读取的唯一状态文件位置。
planPath := filepath.Join(root, "docs", "architecture", "refactoring-master-plan.md")
// mkdirErr 表示创建临时总计划目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Dir(planPath), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// validPlan 是只声明阶段四为当前阶段的最小合法状态表。
validPlan := []byte("| 阶段 | 状态 | 说明 |\n| --- | --- | --- |\n| 4. React | 当前阶段 | x |\n")
// writeErr 表示写入合法临时总计划失败的文件系统原因。
if writeErr := os.WriteFile(planPath, validPlan, 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// stage、readErr 分别是合法状态表解析出的阶段号及错误。
stage, readErr := readActiveArchitectureStage(root)
if readErr != nil || stage != architectureStageReact {
t.Fatalf("stage=%d err=%v", stage, readErr)
}
// duplicatePlan 是包含两个当前阶段标记的非法状态表。
duplicatePlan := append(validPlan, []byte("| 5. DB | 当前阶段 | y |\n")...)
// writeErr 表示写入重复阶段样例失败的文件系统原因。
if writeErr := os.WriteFile(planPath, duplicatePlan, 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// duplicateErr 表示重复当前阶段是否被状态解析器明确拒绝。
if _, duplicateErr := readActiveArchitectureStage(root); duplicateErr == nil {
t.Fatal("重复当前阶段未被拒绝")
}
// completedPlan 是六阶段全部完成后必须继续保持全量门禁的最终状态表。
completedPlan := []byte("| 阶段 | 状态 | 说明 |\n| --- | --- | --- |\n| 6. Closure | 已完成 | z |\n")
// writeErr 表示写入最终完成状态样例失败的文件系统原因。
if writeErr := os.WriteFile(planPath, completedPlan, 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// completedStage、completedErr 分别是最终状态解析结果及错误。
completedStage, completedErr := readActiveArchitectureStage(root)
if completedErr != nil || completedStage != architectureStageClosure {
t.Fatalf("completed stage=%d err=%v", completedStage, completedErr)
}
}
// TestLifecycleArchitectureGate 验证生命周期门禁会拒绝脱离 owner 的根 Context,并要求静态清单字段完整。
func TestLifecycleArchitectureGate(t *testing.T) {
// root 是包含最小生命周期违规样例的临时仓库。
root := t.TempDir()
// workerPath 是模拟后台 worker 源码位置。
workerPath := filepath.Join(root, "internal", "engine", "worker.go")
// mkdirErr 表示创建临时 worker 目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Dir(workerPath), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// writeErr 表示写入根 Context 违规样例失败的文件系统原因。
if writeErr := os.WriteFile(workerPath, []byte("package engine\nimport \"context\"\nvar _ = context.Background()\n"), 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// inventoryPath 是模拟生命周期清单位置。
inventoryPath := filepath.Join(root, "docs", "architecture", "lifecycle-inventory.md")
// mkdirErr 表示创建临时生命周期清单目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Dir(inventoryPath), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// inventory 是包含所有强制生命周期字段的最小清单文本。
inventory := []byte("所有者 Context 来源 停止/关闭 等待/观测 Wait/Join 锁顺序")
// writeErr 表示写入临时生命周期清单失败的文件系统原因。
if writeErr := os.WriteFile(inventoryPath, inventory, 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// violations 是生命周期门禁对根 Context 的阻断结果。
violations := checkLifecycleArchitecture(root)
if len(violations) != 1 || !strings.Contains(violations[0].message, "根 Context") {
t.Fatalf("violations=%+v", violations)
}
}
// TestReactArchitectureGate 验证 React 阶段门禁会拒绝集中契约、根级地图服务和未启用严格类型选项。
func TestReactArchitectureGate(t *testing.T) {
// root 是包含最小前端边界违规样例的临时仓库。
root := t.TempDir()
// frontendRoot 是临时 React 源码根目录。
frontendRoot := filepath.Join(root, "frontend")
// mkdirErr 表示创建根级 services 目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Join(frontendRoot, "services"), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// writeErr 表示写入根级地图服务违规样例失败的文件系统原因。
if writeErr := os.WriteFile(filepath.Join(frontendRoot, "services", "amapLocation.ts"), []byte("export const x = 1;\n"), 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// mkdirErr 表示创建集中契约目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Join(frontendRoot, "shared", "api-contract"), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// writeErr 表示写入大型契约 barrel 违规样例失败的文件系统原因。
if writeErr := os.WriteFile(filepath.Join(frontendRoot, "shared", "api-contract", "index.ts"), []byte("export {};\n"), 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// mkdirErr 表示创建临时 items feature 目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Join(frontendRoot, "app", "features", "items"), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// writeErr 表示写入契约和网络旁路违规样例失败的文件系统原因。
if writeErr := os.WriteFile(filepath.Join(frontendRoot, "app", "features", "items", "bad.ts"), []byte("import { x } from '../../../shared/api-contract';\nvoid fetch('/x');\n"), 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// writeErr 表示写入缺少严格选项的 TypeScript 配置失败的文件系统原因。
if writeErr := os.WriteFile(filepath.Join(frontendRoot, "tsconfig.json"), []byte("{\"compilerOptions\":{}}\n"), 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// violations 是 React 阶段门禁发现的集中入口、网络旁路和类型配置违规。
violations := checkReactArchitecture(root)
if len(violations) < 5 {
t.Fatalf("violations=%+v", violations)
}
}
// TestDatabaseArchitectureGate 验证数据库阶段门禁会拒绝上层裸事务与 Store.DB 访问。
func TestDatabaseArchitectureGate(t *testing.T) {
// root 是包含最小裸数据库违规样例的临时仓库。
root := t.TempDir()
// servicePath 是模拟上层应用服务源码位置。
servicePath := filepath.Join(root, "internal", "application", "orders", "service.go")
// mkdirErr 表示创建临时应用服务目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Dir(servicePath), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// writeErr 表示写入裸数据库违规样例失败的文件系统原因。
if writeErr := os.WriteFile(servicePath, []byte("package orders\nimport \"database/sql\"\nfunc run(db *sql.DB) { db.BeginTx(nil, nil) }\n"), 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// violations 是数据库阶段门禁发现的裸数据库访问结果。
violations := checkDatabaseArchitecture(root)
if len(violations) != 1 || !strings.Contains(violations[0].message, "上层生产代码") {
t.Fatalf("violations=%+v", violations)
}
}
// TestQualityArchitectureGate 验证质量阶段门禁会拒绝超过阈值的非冻结生产文件。
func TestQualityArchitectureGate(t *testing.T) {
// root 是包含超大生产源码样例的临时仓库。
root := t.TempDir()
// sourcePath 是模拟超大 Go 文件位置。
sourcePath := filepath.Join(root, "internal", "application", "items", "large.go")
// mkdirErr 表示创建临时生产源码目录失败的文件系统原因。
if mkdirErr := os.MkdirAll(filepath.Dir(sourcePath), 0o755); mkdirErr != nil {
t.Fatal(mkdirErr)
}
// source 是超过 800 行但仍保持合法 Go 语法的生产源码。
source := []byte("package items\n" + strings.Repeat("// 业务说明\n", 801))
// writeErr 表示写入超大生产文件样例失败的文件系统原因。
if writeErr := os.WriteFile(sourcePath, source, 0o600); writeErr != nil {
t.Fatal(writeErr)
}
// violations 是质量阶段门禁发现的超大文件结果。
violations := checkQualityArchitecture(root)
if len(violations) != 1 || !strings.Contains(violations[0].message, "超过 800 行") {
t.Fatalf("violations=%+v", violations)
}
}