阶段三:完成生命周期、Engine 和 Automation 重新验收
This commit is contained in:
1 parent
3cbe73b560
commit
4227e3dd56
20 files changed
+398
-127
No files matched your search
@@ -40,12 +40,12 @@ shared,feature adapter 直接转换领域 DTO 为 feature-owned UI model。
|
||||
| --- | --- | --- |
|
||||
| 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 直连仍未收口。 |
|
||||
| 3. 生命周期、Engine 和 Automation 重新验收 | 已完成 | 已完成后台任务 owner/Context/Cancel/Wait 收口、同步凭证更新的调用 Context 传递、浏览器组合根生命周期接入和 AST 生命周期门禁;最终提交与完整证据见 `refactoring-progress.md`。 |
|
||||
| 4. React Feature 化和异步状态修复 | 当前阶段 | ApiError、定位和批量状态代码是输入;DTO barrel、根级地图服务和 DTO 直连仍未收口。 |
|
||||
| 5. DB 与事务治理重新验收 | 待执行 | 不得提前。 |
|
||||
| 6. 全量架构、兼容退场和注释收口 | 待执行 | 门禁规则已在基础验证层预建;本阶段只激活最终质量规则、清零违规并完成兼容和注释退场。 |
|
||||
|
||||
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。阶段二已完成,阶段三是唯一允许继续执行的阶段;阶段四及之后不得提前执行。
|
||||
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。阶段三已完成,阶段四是唯一允许继续执行的阶段;阶段五及之后不得提前执行。
|
||||
|
||||
## 阶段一:稳定性、安全和启动生命周期
|
||||
|
||||
@@ -124,7 +124,7 @@ git diff --check
|
||||
Server 的应用依赖由消费者定义的不可变 Port 容器承载,构造期缺失任一必需 Port 即失败。完整原始验收输出、
|
||||
冻结 CAPTCHA 差异检查和最终提交绑定只记录在 `refactoring-progress.md`。
|
||||
|
||||
## 阶段三:生命周期、Engine 和 Automation 重新验收(当前阶段)
|
||||
## 阶段三:生命周期、Engine 和 Automation 重新验收(已完成)
|
||||
|
||||
明确每个 worker 的 owner、Context、Cancel、Wait/Join;cmd 独占协调器;Server Stop 只收束 HTTP;
|
||||
覆盖启动失败、取消、超时、重复关闭、晚到结果和关闭顺序;可在本阶段修复 Engine/Automation 状态问题,
|
||||
@@ -140,7 +140,7 @@ go run ./tools/architecturecheck
|
||||
|
||||
最终提交:阶段三:完成生命周期、Engine 和 Automation 重新验收。
|
||||
|
||||
## 阶段四:React Feature 化和异步状态修复
|
||||
## 阶段四:React Feature 化和异步状态修复(当前阶段)
|
||||
|
||||
这是一个完整前端阶段,不拆 HTTP 错误、契约、地图、轮询或构建交付:
|
||||
- ApiError 保留 status、code、message、request_id、details、payload;JSON/FormData 共用错误解析。
|
||||
|
||||
@@ -77,8 +77,64 @@ $ git diff --check
|
||||
- 冻结 CAPTCHA:受保护的七个实现与测试文件在最终差异中均未出现,冻结规范未修改。
|
||||
- 生成物:`frontend/coverage/` 是未跟踪的测试产物,不纳入提交。
|
||||
|
||||
## 阶段三:生命周期、Engine 和 Automation 重新验收
|
||||
|
||||
- 最终提交绑定:本文件随最终提交 `阶段三:完成生命周期、Engine 和 Automation 重新验收` 一并进入 `HEAD`。
|
||||
- 交付范围:所有账户、调度、续期、通知和浏览器生命周期入口拒绝缺失的 owner Context;历史无 Context 入口
|
||||
仅以显式有限预算兼容。账号任务登记现在返回唯一 release 函数,确保 bootstrap Context 计时器在任务完成时
|
||||
取消,并且 Stop 仍按 owner Context 取消、Wait/Join 已登记 worker。
|
||||
- 凭证更新:请求内 Cookie 收口改为同步 `UpdateCookieContext`,由 adapter 将调用 Context 传入;取消请求不能
|
||||
修改运行时 Cookie 或 Token 缓存,旧无 Context 回调仍只使用 10 秒兼容预算。
|
||||
- 组合根与门禁:browser 初始化改为由 lifecycle coordinator 传入 Context;architecturecheck 使用 AST 检查后台
|
||||
包的根 Context,只有 `WithTimeout` 或 `WithDeadline` 的有限收口预算可使用根 Context。冻结 CAPTCHA 实现依据
|
||||
冻结规范排除,不是白名单。
|
||||
|
||||
### 强制验收原始输出
|
||||
|
||||
```text
|
||||
$ go test ./... -count=1
|
||||
所有测试包通过;其中 internal/engine 39.521s、internal/server 26.224s、internal/xianyu/mtop 28.959s。
|
||||
|
||||
$ go test -race ./internal/server ./internal/engine ./internal/automation ./internal/renewal
|
||||
ok xianyu-go/internal/server 249.126s
|
||||
ok xianyu-go/internal/engine 294.724s
|
||||
ok xianyu-go/internal/automation (cached)
|
||||
ok xianyu-go/internal/renewal (cached)
|
||||
|
||||
$ RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
|
||||
ok xianyu-go/internal/browser 33.969s
|
||||
|
||||
$ go vet ./...
|
||||
(无输出,退出码 0)
|
||||
|
||||
$ make lint
|
||||
golangci-lint run ./...
|
||||
0 issues.
|
||||
|
||||
$ make comments
|
||||
go run ./tools/commentlint -mode check -root .
|
||||
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||
node frontend/scripts/check-comments.mjs --mode check --root frontend
|
||||
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||
|
||||
$ go run ./tools/architecturecheck
|
||||
architecturecheck: 通过
|
||||
|
||||
$ git diff --check
|
||||
(无输出,退出码 0)
|
||||
```
|
||||
|
||||
### 验收边界
|
||||
|
||||
- 覆盖率:本阶段强制命令不包含覆盖率命令,未声明 Go 或前端覆盖率百分比。
|
||||
- 浏览器:已使用 `RUN_BROWSER_INTEGRATION=1` 执行 `internal/browser` 集成测试。
|
||||
- 外部服务:未运行 MySQL、PostgreSQL、`cmd/dbverify` 或真实账号/平台调用;本阶段未改变数据库方言或平台协议。
|
||||
- 冻结 CAPTCHA:受保护的 slider、token CAPTCHA 实现和测试文件均未出现在最终差异;冻结规范未修改。
|
||||
- 生成物:`frontend/coverage/` 是未跟踪的测试产物,不纳入提交。
|
||||
|
||||
## 下一阶段入口
|
||||
|
||||
当前阶段为阶段三:生命周期、Engine 和 Automation 重新验收。先以 `lifecycle-inventory.md` 对照每个后台
|
||||
worker 的 owner、Context、Cancel、Wait/Join 和锁顺序;阶段三门禁已经随状态切换启用。不得提前进入 React、
|
||||
数据库或最终收口阶段,也不得修改冻结 CAPTCHA。
|
||||
当前阶段为阶段四:React Feature 化和异步状态修复。阶段四开始前先运行 architecturecheck,激活已有 React
|
||||
feature、传输契约、网络旁路、动态 import 和严格 TypeScript 门禁;在同一阶段完成 ApiError、领域契约拆分、
|
||||
items 地图迁移、定位取消/超时、批量轮询与嵌入产物重建。不得提前进入数据库或最终收口阶段,也不得修改冻结
|
||||
CAPTCHA。
|
||||
@@ -21,6 +21,9 @@ import (
|
||||
// ErrRestartIncomplete 表示账号重启在旧实例收束或新实例启动前被取消或失败,调用方可据此安排重试与状态展示。
|
||||
var ErrRestartIncomplete = errors.New("账号重启未完成")
|
||||
|
||||
// legacyManagerShutdownTimeout 是兼容无 Context 停止入口时允许等待账号 worker 收束的最长预算。
|
||||
const legacyManagerShutdownTimeout = 10 * time.Second
|
||||
|
||||
// Manager 管理所有账号运行时。
|
||||
type Manager struct {
|
||||
store *db.Store
|
||||
@@ -66,7 +69,7 @@ func NewManager(store *db.Store, handler engine.Handler, logger *slog.Logger) *M
|
||||
// StartAll 启动All。
|
||||
func (m *Manager) StartAll(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("启动全部账号需要生命周期 Context")
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.runCtx = ctx
|
||||
@@ -95,7 +98,7 @@ StartAll 只把启用账号交给运行时 supervisor。
|
||||
// Start 启动单个账号(若已在运行则跳过;若上次实例已退出则清理后重启)。
|
||||
func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("启动账号需要生命周期 Context")
|
||||
}
|
||||
m.mu.Lock()
|
||||
if m.stoppingAll {
|
||||
@@ -180,13 +183,16 @@ func (m *Manager) EndStopping(cookieID string) {
|
||||
|
||||
// Stop 停止单个账号,并兼容不需要错误返回值的旧调用方。
|
||||
func (m *Manager) Stop(cookieID string) {
|
||||
_ = m.StopContext(context.Background(), cookieID)
|
||||
// stopCtx、stopCancel 为兼容入口创建受限关闭预算,避免无 Context 调用无限等待账号 goroutine。
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), legacyManagerShutdownTimeout)
|
||||
defer stopCancel()
|
||||
_ = m.StopContext(stopCtx, cookieID)
|
||||
}
|
||||
|
||||
// StopContext 在 ctx 约束内停止单个账号;超时后保留运行实例记录,避免误报已清理。
|
||||
func (m *Manager) StopContext(ctx context.Context, cookieID string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("停止账号需要关闭 Context")
|
||||
}
|
||||
m.mu.Lock()
|
||||
// ma、ok 用于本次流程后续判断的ma、ok
|
||||
@@ -281,7 +287,7 @@ func (m *Manager) RuntimeStatuses() map[string]engine.RuntimeStatus {
|
||||
// 取消发生在停止前时不改变现有实例;停止后的取消会返回 ErrRestartIncomplete,调用方不得将其视为重启成功。
|
||||
func (m *Manager) Restart(ctx context.Context, cookieID string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return fmt.Errorf("%w: 重启账号需要生命周期 Context", ErrRestartIncomplete)
|
||||
}
|
||||
// contextErr 是进入有副作用的停止阶段前检测到的取消或超时原因。
|
||||
if contextErr := ctx.Err(); contextErr != nil {
|
||||
@@ -315,13 +321,16 @@ func (m *Manager) Restart(ctx context.Context, cookieID string) error {
|
||||
// 先在锁内收集 cookieID 列表再解锁逐个停,避免持锁等待 goroutine 退出。
|
||||
// StopAll 停止All。
|
||||
func (m *Manager) StopAll() {
|
||||
_ = m.StopAllContext(context.Background())
|
||||
// stopCtx、stopCancel 为兼容入口创建受限关闭预算,避免进程退出时无限等待账号 worker。
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), legacyManagerShutdownTimeout)
|
||||
defer stopCancel()
|
||||
_ = m.StopAllContext(stopCtx)
|
||||
}
|
||||
|
||||
// StopAllContext 在同一个关闭上下文内停止所有账号,遇到超时立即返回并保留未完成实例。
|
||||
func (m *Manager) StopAllContext(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("停止全部账号需要关闭 Context")
|
||||
}
|
||||
m.mu.Lock()
|
||||
// stoppingAll 在收集账号前建立全局 fencing,防止并发 Start 把新实例遗漏在本次关闭之外。
|
||||
|
||||
@@ -13,6 +13,13 @@ type AccountRuntimePort struct {
|
||||
manager *accountmanager.Manager
|
||||
}
|
||||
|
||||
// contextualCookieUpdater 表示可将调用方 Context 贯穿到运行时 Cookie 收口的最小可选能力。
|
||||
// 它由 adapter 消费,避免为所有自动化发送器扩大公共 MessageSender 契约。
|
||||
type contextualCookieUpdater interface {
|
||||
// UpdateCookieContext 在调用方取消或超时时停止等待凭证刷新门和数据库操作。
|
||||
UpdateCookieContext(context.Context, string) error
|
||||
}
|
||||
|
||||
// NewAccountRuntimePort 创建账号运行时适配器;nil Manager 表示当前进程未启用账号运行实例。
|
||||
func NewAccountRuntimePort(manager *accountmanager.Manager) accountapp.RuntimePort {
|
||||
if manager == nil {
|
||||
@@ -48,6 +55,11 @@ func (p AccountRuntimePort) UpdateCookie(ctx context.Context, accountID, value s
|
||||
if !ok || sender == nil {
|
||||
return nil
|
||||
}
|
||||
// updater、supportsContext 保存运行时是否支持调用方取消的同步 Cookie 收口能力。
|
||||
if updater, supportsContext := sender.(contextualCookieUpdater); supportsContext {
|
||||
return updater.UpdateCookieContext(ctx, value)
|
||||
}
|
||||
// 旧发送器尚未暴露 Context 入口时保留其受限兼容实现;该调用不会创建后台任务。
|
||||
sender.UpdateCookie(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ const defaultReviewRequestScanInterval = time.Minute
|
||||
// defaultDeferredTaskScanInterval 是持久化延迟动作的轮询周期,保证秒级动作不会被分钟级业务扫描额外延后。
|
||||
const defaultDeferredTaskScanInterval = time.Second
|
||||
|
||||
// legacySchedulerWaitTimeout 是兼容无 Context 等待入口的最长收束预算。
|
||||
const legacySchedulerWaitTimeout = 10 * time.Second
|
||||
|
||||
// Scheduler 执行计划任务类自动化。
|
||||
// 计划任务只负责“发现应该触发的任务”,具体动作仍交给 Center,避免形成第二套执行链。
|
||||
// Scheduler 用于本次流程后续判断的Scheduler
|
||||
@@ -82,14 +85,17 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
|
||||
// Wait 等待调度器完成,并兼容不需要超时的旧调用方。
|
||||
func (s *Scheduler) Wait() {
|
||||
_ = s.WaitContext(context.Background())
|
||||
// waitCtx、waitCancel 为兼容入口提供受限等待预算,避免调度器异常时永久阻塞调用方。
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), legacySchedulerWaitTimeout)
|
||||
defer waitCancel()
|
||||
_ = s.WaitContext(waitCtx)
|
||||
}
|
||||
|
||||
// WaitContext 在 ctx 约束内等待调度器完成,避免关闭流程无限阻塞。
|
||||
func (s *Scheduler) WaitContext(ctx context.Context) error {
|
||||
if s != nil && s.done != nil {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("等待自动化调度器需要关闭 Context")
|
||||
}
|
||||
select {
|
||||
case <-s.done:
|
||||
|
||||
@@ -34,6 +34,8 @@ const (
|
||||
goofishDot = ".goofish.com"
|
||||
goofishHomeURL = "https://www.goofish.com/"
|
||||
goofishIMURL = "https://www.goofish.com/im"
|
||||
// legacyLifecycleOperationTimeout 为旧的无 Context 浏览器入口提供有界初始化与关闭预算。
|
||||
legacyLifecycleOperationTimeout = 45 * time.Second
|
||||
)
|
||||
|
||||
// chromiumLaunchArgs 统一 Chromium 启动参数。
|
||||
@@ -263,7 +265,7 @@ func NewManager(logger *slog.Logger) *Manager {
|
||||
// ctx 仅用于在进入状态机前传播调用方取消语义,不会启动无法回收的等待 goroutine。
|
||||
func (m *Manager) beginOperation(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("浏览器操作需要调用方 Context")
|
||||
}
|
||||
// err 表示调用方 Context 已取消,管理器不会为已取消调用登记活动任务。
|
||||
if err := ctx.Err(); err != nil {
|
||||
@@ -356,12 +358,18 @@ func (m *Manager) init() error {
|
||||
return m.initErr
|
||||
}
|
||||
|
||||
// Initialize starts Playwright and publishes the bundled Chromium's native
|
||||
// browser identity before any non-browser client sends requests.
|
||||
// Initialize 封装Initialize业务协调。
|
||||
// Initialize 为兼容旧调用方在受限 Context 内启动 Playwright。
|
||||
func (m *Manager) Initialize() error {
|
||||
// err 表示管理器已进入关闭流程,不能继续初始化 Playwright。
|
||||
if err := m.beginOperation(context.Background()); err != nil {
|
||||
// initializeCtx、initializeCancel 为旧入口提供有限初始化预算,避免浏览器初始化脱离进程关闭链。
|
||||
initializeCtx, initializeCancel := context.WithTimeout(context.Background(), legacyLifecycleOperationTimeout)
|
||||
defer initializeCancel()
|
||||
return m.InitializeContext(initializeCtx)
|
||||
}
|
||||
|
||||
// InitializeContext 在调用方生命周期 Context 内启动 Playwright 并发布浏览器运行时指纹。
|
||||
func (m *Manager) InitializeContext(ctx context.Context) error {
|
||||
// err 表示管理器已进入关闭流程、Context 无效或不能继续初始化 Playwright。
|
||||
if err := m.beginOperation(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.endOperation()
|
||||
@@ -633,7 +641,10 @@ func (m *Manager) applyHeadlessFingerprint(page playwright.Page) error {
|
||||
|
||||
// Close 释放所有浏览器与 Playwright;它会等待活动实例退出且不会遗留关闭 goroutine。
|
||||
func (m *Manager) Close() error {
|
||||
return m.CloseContext(context.Background())
|
||||
// closeCtx、closeCancel 为兼容入口提供有限关闭预算,避免同步 Playwright 释放永久阻塞调用方。
|
||||
closeCtx, closeCancel := context.WithTimeout(context.Background(), legacyLifecycleOperationTimeout)
|
||||
defer closeCancel()
|
||||
return m.CloseContext(closeCtx)
|
||||
}
|
||||
|
||||
// CloseContext 拒绝新调用并等待已有浏览器调用结束后同步释放资源。
|
||||
@@ -641,7 +652,7 @@ func (m *Manager) Close() error {
|
||||
// 实现不通过后台 goroutine 包装 Close,因此超时不会留下无法观察的关闭任务。
|
||||
func (m *Manager) CloseContext(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("关闭浏览器需要调用方 Context")
|
||||
}
|
||||
// err 表示调用方在关闭开始前已经取消等待,管理器保持可重试状态。
|
||||
if err := ctx.Err(); err != nil {
|
||||
|
||||
@@ -64,7 +64,7 @@ func BuildRuntime(options RuntimeOptions, infrastructure RuntimeInfrastructure)
|
||||
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 {
|
||||
if addErr := lifecycleCoordinator.Add(lifecycle.NamedComponent{Name: "browser", Component: lifecycle.FuncComponent{StartFunc: browserManager.InitializeContext, CloseFunc: browserManager.CloseContext}}); addErr != nil {
|
||||
return Runtime{}, fmt.Errorf("登记浏览器生命周期组件失败: %w", addErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,7 +344,6 @@ func New(cfg Config) *Account {
|
||||
Reply: a.reply,
|
||||
Logger: logger,
|
||||
BeginTask: a.lifecycle.beginTask,
|
||||
FinishTask: a.lifecycle.finishTask,
|
||||
RecordMessage: a.recordMessageReceived,
|
||||
})
|
||||
// connection 保存绑定当前账号 facade 的连接编排组件;它只在构造完成后才可被 Run 调用。
|
||||
@@ -449,8 +448,8 @@ func (a *Account) StopContext(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// beginTask 封装begin任务业务协调。
|
||||
func (a *Account) beginTask() (context.Context, bool) {
|
||||
// beginTask 封装账户所属任务的 Context、释放函数和生命周期接纳结果。
|
||||
func (a *Account) beginTask() (context.Context, func(), bool) {
|
||||
return a.lifecycle.beginTask()
|
||||
}
|
||||
|
||||
|
||||
@@ -1093,6 +1093,38 @@ func TestUpdateCookie_AcceptsAuthoritativeEmptySnapshot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookieContextRejectsCanceledCall 验证请求取消后不会继续收口运行时 Cookie 或清理 Token。
|
||||
func TestUpdateCookieContextRejectsCanceledCall(t *testing.T) {
|
||||
// acc、store、cleanup 用于本次流程后续判断的账号、数据库和资源释放函数。
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
// original 保存取消前的运行时 Cookie,作为拒绝副作用的基线。
|
||||
original := acc.currentCookieStr()
|
||||
// saveErr 保存预置旧 Token 缓存失败的原因;取消同步不得清理此缓存。
|
||||
saveErr := store.Tokens.Save(context.Background(), acc.CookieID, "device", "old-token", time.Now().Add(time.Hour).Unix())
|
||||
if saveErr != nil {
|
||||
t.Fatal(saveErr)
|
||||
}
|
||||
// ctx、cancel 保存已取消的调用上下文,模拟 HTTP 请求或应用任务提前结束。
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
// err 保存凭证协调器响应取消后的同步错误。
|
||||
err := acc.UpdateCookieContext(ctx, "unb=123; _m_h5_tk=late-update;")
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("取消的 Cookie 同步错误=%v,期望 context.Canceled", err)
|
||||
}
|
||||
// got 保存取消后的运行时 Cookie,必须保持为同步前的快照。
|
||||
got := acc.currentCookieStr()
|
||||
if got != original {
|
||||
t.Fatalf("取消的 Cookie 同步不应改写内存凭证: got %q want %q", got, original)
|
||||
}
|
||||
// token、tokenErr 保存取消后读取的 Token 缓存及其查询错误。
|
||||
token, tokenErr := store.Tokens.Get(context.Background(), acc.CookieID)
|
||||
if tokenErr != nil || token.AccessToken != "old-token" {
|
||||
t.Fatalf("取消的 Cookie 同步不应触碰 Token 缓存: token=%+v err=%v", token, tokenErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadCookieFromDBDetectsMetadataOnlyCredentialRotation 封装TestReload登录凭证FromDBDetectsMetadataOnlyCredentialRotation业务协调。
|
||||
func TestReloadCookieFromDBDetectsMetadataOnlyCredentialRotation(t *testing.T) {
|
||||
// acc、store、cleanup 用于本次流程后续判断的acc、store、cleanup
|
||||
|
||||
@@ -2,9 +2,14 @@ package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// bootstrapTaskTimeout 是账号尚未 Run 时同步初始化任务的最大存活时间;它不能替代正式运行生命周期。
|
||||
const bootstrapTaskTimeout = time.Minute
|
||||
|
||||
// accountLifecycle 管理单账号运行上下文和业务任务生命周期。
|
||||
// mu 保护 stopFn、stopped、runtimeCtx、accepting、任务计数和停止完成信号;
|
||||
// 持有 mu 时只做内存操作,不执行 I/O。Stop 先禁止新任务、再取消上下文,最后等待已有任务。
|
||||
@@ -50,7 +55,7 @@ func (l *accountLifecycle) start(ctx context.Context, cancel context.CancelFunc)
|
||||
// stopContext 原子地禁止新任务并取出取消函数;并发停止调用会受 ctx 限制地等待首次清理完成。
|
||||
func (l *accountLifecycle) stopContext(ctx context.Context) (context.CancelFunc, bool, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return nil, false, errors.New("停止账号需要关闭 Context")
|
||||
}
|
||||
l.mu.Lock()
|
||||
if l.stopped {
|
||||
@@ -80,22 +85,40 @@ func (l *accountLifecycle) stopContext(ctx context.Context) (context.CancelFunc,
|
||||
}
|
||||
|
||||
// beginTask 在生命周期锁内登记业务任务,避免 Stop 与 WaitGroup.Add 竞争。
|
||||
func (l *accountLifecycle) beginTask() (context.Context, bool) {
|
||||
// 返回的 finish 必须由获准任务恰好调用一次;它同时释放 bootstrap Context 的计时器。
|
||||
func (l *accountLifecycle) beginTask() (context.Context, func(), bool) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if !l.accepting {
|
||||
return nil, false
|
||||
l.mu.Unlock()
|
||||
return nil, nil, false
|
||||
}
|
||||
// ctx 是新业务任务继承的账号运行上下文。
|
||||
ctx := l.runtimeCtx
|
||||
// cancel 是仅在尚未进入 Run 的兼容任务中停止有限 Context 定时器的函数。
|
||||
cancel := func() {}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
// bootstrapCtx 是仅供尚未进入 Run 的同步初始化与确定性测试使用的有限任务 Context。
|
||||
bootstrapCtx, bootstrapCancel := context.WithTimeout(context.Background(), bootstrapTaskTimeout)
|
||||
ctx = bootstrapCtx
|
||||
cancel = bootstrapCancel
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, false
|
||||
l.mu.Unlock()
|
||||
cancel()
|
||||
return nil, nil, false
|
||||
}
|
||||
l.activeTasks++
|
||||
return ctx, true
|
||||
l.mu.Unlock()
|
||||
// once 保证重复 defer 或错误路径不会重复递减任务计数或关闭 stopDone。
|
||||
var once sync.Once
|
||||
// finish 结束当前任务的生命周期登记,并释放仅供该任务使用的 bootstrap 计时器。
|
||||
finish := func() {
|
||||
once.Do(func() {
|
||||
cancel()
|
||||
l.finishTask()
|
||||
})
|
||||
}
|
||||
return ctx, finish, true
|
||||
}
|
||||
|
||||
// finishTask 标记一个已登记的业务任务退出。
|
||||
@@ -115,7 +138,7 @@ func (l *accountLifecycle) finishTask() {
|
||||
// stopDone 由最后一个任务关闭,因而超时返回不遗留等待协程;调用方可用新的上下文再次等待同一信号。
|
||||
func (l *accountLifecycle) waitContext(ctx context.Context) bool {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return false
|
||||
}
|
||||
l.mu.Lock()
|
||||
// done 是 Stop 为当前收束周期创建、由最后一个已登记任务关闭的共享信号。
|
||||
|
||||
@@ -15,8 +15,8 @@ func TestAccountStopWaitsForTaskAndConcurrentStop(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
account.lifecycle.start(ctx, cancel)
|
||||
// taskCtx 是已登记任务拿到的上下文;ok 表示任务成功进入生命周期。
|
||||
taskCtx, ok := account.beginTask()
|
||||
// taskCtx、finish、ok 分别是已登记任务的上下文、释放函数与生命周期接纳结果。
|
||||
taskCtx, finish, ok := account.beginTask()
|
||||
if !ok || taskCtx == nil {
|
||||
t.Fatal("业务任务应在 Stop 前成功登记")
|
||||
}
|
||||
@@ -39,7 +39,7 @@ func TestAccountStopWaitsForTaskAndConcurrentStop(t *testing.T) {
|
||||
t.Fatal("并发 Stop 在已登记任务完成前提前返回")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
account.lifecycle.finishTask()
|
||||
finish()
|
||||
select {
|
||||
case <-firstDone:
|
||||
case <-time.After(time.Second):
|
||||
@@ -50,9 +50,9 @@ func TestAccountStopWaitsForTaskAndConcurrentStop(t *testing.T) {
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("并发 Stop 未等待第一次 Stop 完成")
|
||||
}
|
||||
// stoppedCtx 是 Stop 后尝试登记任务得到的上下文;stoppedOK 必须为 false。
|
||||
stoppedCtx, stoppedOK := account.beginTask()
|
||||
if stoppedOK || stoppedCtx != nil {
|
||||
// stoppedCtx、stoppedFinish、stoppedOK 分别是停止后任务的上下文、释放函数与接纳结果。
|
||||
stoppedCtx, stoppedFinish, stoppedOK := account.beginTask()
|
||||
if stoppedOK || stoppedCtx != nil || stoppedFinish != nil {
|
||||
t.Fatal("Stop 后不应再接受业务任务")
|
||||
}
|
||||
}
|
||||
@@ -65,8 +65,9 @@ func TestAccountStopContextBoundsTaskWait(t *testing.T) {
|
||||
runCtx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
account.lifecycle.start(runCtx, cancel)
|
||||
// ok 表示测试业务任务是否成功登记。
|
||||
if _, ok := account.beginTask(); !ok {
|
||||
// taskCtx、finish、ok 分别是测试业务任务的上下文、释放函数与接纳结果。
|
||||
taskCtx, finish, ok := account.beginTask()
|
||||
if !ok || taskCtx == nil || finish == nil {
|
||||
t.Fatal("业务任务应成功登记")
|
||||
}
|
||||
// stopCtx 是刻意很短的停止上下文,用于验证有界等待。
|
||||
@@ -93,7 +94,7 @@ func TestAccountStopContextBoundsTaskWait(t *testing.T) {
|
||||
t.Fatal("第一次 Stop 超时后,重试不应在任务完成前返回")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
account.lifecycle.finishTask()
|
||||
finish()
|
||||
select {
|
||||
// retryErr 表示第一次超时后再次停止账号的等待结果。
|
||||
case retryErr := <-retryDone:
|
||||
@@ -115,9 +116,9 @@ func TestAccountLifecycleWaitContextCanRetryAfterTimeout(t *testing.T) {
|
||||
if !lifecycle.start(runCtx, cancel) {
|
||||
t.Fatal("生命周期应允许首次启动")
|
||||
}
|
||||
// taskCtx 是登记任务继承的运行上下文;accepted 表示任务已成功进入停止收束范围。
|
||||
taskCtx, accepted := lifecycle.beginTask()
|
||||
if !accepted || taskCtx == nil {
|
||||
// taskCtx、finish、accepted 分别是登记任务的上下文、释放函数与停止收束接纳结果。
|
||||
taskCtx, finish, accepted := lifecycle.beginTask()
|
||||
if !accepted || taskCtx == nil || finish == nil {
|
||||
t.Fatal("业务任务应成功登记")
|
||||
}
|
||||
// shouldStop 表示本次调用创建了停止收束信号;stopErr 表示停止切换错误。
|
||||
@@ -141,7 +142,7 @@ func TestAccountLifecycleWaitContextCanRetryAfterTimeout(t *testing.T) {
|
||||
t.Fatal("任务未完成时,重试等待不应提前返回")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
lifecycle.finishTask()
|
||||
finish()
|
||||
select {
|
||||
// completed 表示第二次等待在任务收束后得到正常完成结果。
|
||||
case completed := <-waited:
|
||||
@@ -168,9 +169,9 @@ func TestAccountLifecycleRejectsLateStart(t *testing.T) {
|
||||
if lifecycle.start(runCtx, cancel) {
|
||||
t.Fatal("Stop 先于 Run 时不应重新启动生命周期")
|
||||
}
|
||||
// taskCtx 是停止后尝试登记业务任务得到的上下文,必须被拒绝。
|
||||
taskCtx, accepted := lifecycle.beginTask()
|
||||
if accepted || taskCtx != nil {
|
||||
// taskCtx、finish、accepted 分别是停止后任务的上下文、释放函数与接纳结果。
|
||||
taskCtx, finish, accepted := lifecycle.beginTask()
|
||||
if accepted || taskCtx != nil || finish != nil {
|
||||
t.Fatalf("停止后的生命周期不应接收任务:ctx=%v accepted=%v", taskCtx, accepted)
|
||||
}
|
||||
}
|
||||
@@ -139,9 +139,28 @@ func (a *Account) replaceCredentialState(cookieStr, credentialFP string) {
|
||||
a.credentials.replaceCredentialState(cookieStr, credentialFP)
|
||||
}
|
||||
|
||||
// UpdateCookie 是外部刷新 Cookie 同步的稳定导出入口,并委托给凭证协调器。
|
||||
// runtimeCookieUpdateTimeout 是旧无 Context Cookie 同步入口的最长数据库与刷新门等待预算。
|
||||
const runtimeCookieUpdateTimeout = 10 * time.Second
|
||||
|
||||
// UpdateCookie 是外部刷新 Cookie 同步的兼容入口。新调用方应使用 UpdateCookieContext
|
||||
// 传入请求或应用任务的 Context;该入口只为尚未迁移的内部回调提供受限预算。
|
||||
func (a *Account) UpdateCookie(cookieStr string) {
|
||||
a.credentials.updateCookie(cookieStr)
|
||||
// updateCtx、updateCancel 为历史无 Context 调用创建有限同步预算,避免等待刷新门时无限阻塞。
|
||||
updateCtx, updateCancel := context.WithTimeout(context.Background(), runtimeCookieUpdateTimeout)
|
||||
defer updateCancel()
|
||||
// updateErr 保存受限兼容同步在取消、数据库读取或刷新门等待时的失败原因。
|
||||
if updateErr := a.UpdateCookieContext(updateCtx, cookieStr); updateErr != nil {
|
||||
a.logger.Warn("同步运行时 Cookie 失败", "err", updateErr)
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateCookieContext 用调用方 Context 同步已持久化的 Cookie、内存凭证快照与 Token 缓存。
|
||||
// 它不创建后台 worker;调用返回前完成全部状态收口,因此不受账号 Run 停止 fencing 影响。
|
||||
func (a *Account) UpdateCookieContext(ctx context.Context, cookieStr string) error {
|
||||
if ctx == nil {
|
||||
return errors.New("同步运行时 Cookie 需要调用 Context")
|
||||
}
|
||||
return a.credentials.updateCookie(ctx, cookieStr)
|
||||
}
|
||||
|
||||
// tryLoginStatusCheck 调用 mtop.taobao.idlemessage.pc.loginuser.get 做轻量登录态确认。
|
||||
@@ -499,7 +518,7 @@ func (c *credentialCoordinator) persistRenewFlatCookie(ctx context.Context, newC
|
||||
func (c *credentialCoordinator) watchPendingAPIRenew(parent context.Context, result *renew.Result) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供生命周期任务登记。
|
||||
a := c.account
|
||||
a.pendingRenewal.watch(parent, a.beginTask, a.lifecycle.finishTask, result, a.persistPendingRenewCookies, a.logger)
|
||||
a.pendingRenewal.watch(parent, a.beginTask, result, a.persistPendingRenewCookies, a.logger)
|
||||
}
|
||||
|
||||
// persistPendingRenewCookies 封装persistPendingRenewCookies业务协调。
|
||||
@@ -1099,18 +1118,17 @@ func (c *credentialCoordinator) replaceCredentialState(cookieStr, credentialFP s
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。
|
||||
func (c *credentialCoordinator) updateCookie(cookieStr string) {
|
||||
// updateCookie 用外部刷新得到的新 Cookie 更新运行时状态,并在调用方 Context 到期时停止等待。
|
||||
func (c *credentialCoordinator) updateCookie(ctx context.Context, cookieStr string) error {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供权威 Cookie repository 与刷新门。
|
||||
a := c.account
|
||||
if strings.TrimSpace(cookieStr) == "" && (a.store == nil || a.store.Cookies == nil) {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
// releaseRefreshGate 释放运行时 Cookie 同步占用的通道令牌。
|
||||
releaseRefreshGate, gateErr := a.acquireRefreshGate(context.Background())
|
||||
releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx)
|
||||
if gateErr != nil {
|
||||
a.logger.Warn("同步运行时 Cookie 时刷新通道被取消", "err", gateErr)
|
||||
return
|
||||
return fmt.Errorf("获取运行时 Cookie 同步门: %w", gateErr)
|
||||
}
|
||||
defer releaseRefreshGate()
|
||||
// credentialUnlock 用于本次流程后续判断的credentialUnlock
|
||||
@@ -1125,16 +1143,15 @@ func (c *credentialCoordinator) updateCookie(cookieStr string) {
|
||||
// metadataJSON 用于本次流程后续判断的metadataJSON
|
||||
metadataJSON := ""
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(context.Background(), a.CookieID) // runtimeData 只包含同步运行时 Cookie 所需的 Cookie 与 metadata。
|
||||
// runtimeData、err 分别是账号运行时的权威 Cookie 快照及读取失败;查询继承调用方取消。
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID)
|
||||
if err != nil {
|
||||
a.logger.Warn("同步运行时 Cookie 前读取数据库失败", "err", err)
|
||||
return
|
||||
return fmt.Errorf("读取运行时 Cookie: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(runtimeData.Value) == "" {
|
||||
if // complete 用于本次流程后续判断的complete
|
||||
_, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete {
|
||||
a.logger.Warn("同步运行时 Cookie 时数据库值为空且无权威 Jar")
|
||||
return
|
||||
return errors.New("同步运行时 Cookie 时数据库值为空且无权威 Jar")
|
||||
}
|
||||
}
|
||||
cookieStr = runtimeData.Value
|
||||
@@ -1147,10 +1164,11 @@ func (c *credentialCoordinator) updateCookie(cookieStr string) {
|
||||
changed := credentialFP != a.credentialFP
|
||||
a.mu.Unlock()
|
||||
if !changed {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
a.replaceCredentialState(cookieStr, credentialFP)
|
||||
// Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie
|
||||
// 会在下一次自然重连前被重新读取并用于获取新的 accessToken。
|
||||
a.clearTokenCache(context.Background())
|
||||
a.clearTokenCache(ctx)
|
||||
return nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -58,8 +59,7 @@ func newRefreshGate() chan struct{} {
|
||||
// 因此停止账号不会被另一个尚未完成的续期流程无限阻塞。
|
||||
func (s *credentialState) acquireRefreshGate(ctx context.Context) (func(), error) {
|
||||
if ctx == nil {
|
||||
// ctx 使用 Background 保持历史未传取消信号调用方的可用性。
|
||||
ctx = context.Background()
|
||||
return nil, errors.New("获取账号刷新门需要生命周期 Context")
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.refreshGate == nil {
|
||||
|
||||
@@ -34,10 +34,8 @@ type messageDispatcher struct {
|
||||
reply *ReplyService
|
||||
// logger 记录消息分发和防抖错误。
|
||||
logger *slog.Logger
|
||||
// beginTask 登记账号生命周期任务。
|
||||
beginTask func() (context.Context, bool)
|
||||
// finishTask 完成账号生命周期任务登记。
|
||||
finishTask func()
|
||||
// beginTask 登记账号生命周期任务,并返回该任务唯一的释放函数。
|
||||
beginTask func() (context.Context, func(), bool)
|
||||
// recordMessage 更新账号最近收消息时间。
|
||||
recordMessage func(time.Time)
|
||||
}
|
||||
@@ -54,10 +52,8 @@ type messageDispatcherConfig struct {
|
||||
Reply *ReplyService
|
||||
// Logger 记录分发过程中的错误和诊断信息。
|
||||
Logger *slog.Logger
|
||||
// BeginTask 登记账号生命周期任务。
|
||||
BeginTask func() (context.Context, bool)
|
||||
// FinishTask 完成账号生命周期任务登记。
|
||||
FinishTask func()
|
||||
// BeginTask 登记账号生命周期任务,并返回该任务唯一的释放函数。
|
||||
BeginTask func() (context.Context, func(), bool)
|
||||
// RecordMessage 更新最近收到消息时间。
|
||||
RecordMessage func(time.Time)
|
||||
}
|
||||
@@ -77,12 +73,12 @@ func newMessageDispatcher(config messageDispatcherConfig) messageDispatcher {
|
||||
// beginTask 用于本次流程后续判断的begin任务
|
||||
beginTask := config.BeginTask
|
||||
if beginTask == nil {
|
||||
beginTask = func() (context.Context, bool) { return context.Background(), true }
|
||||
}
|
||||
// finishTask 用于本次流程后续判断的finish任务
|
||||
finishTask := config.FinishTask
|
||||
if finishTask == nil {
|
||||
finishTask = func() {}
|
||||
// 缺少生命周期登记器时使用受限同步兼容预算,测试构造不能产生长期游离任务。
|
||||
beginTask = func() (context.Context, func(), bool) {
|
||||
// fallbackCtx 是没有账号 owner 时仅供一次消息分发使用的有限 Context。
|
||||
fallbackCtx, fallbackCancel := context.WithTimeout(context.Background(), bootstrapTaskTimeout)
|
||||
return fallbackCtx, fallbackCancel, true
|
||||
}
|
||||
}
|
||||
// recordMessage 用于本次流程后续判断的record消息
|
||||
recordMessage := config.RecordMessage
|
||||
@@ -104,15 +100,14 @@ func newMessageDispatcher(config messageDispatcherConfig) messageDispatcher {
|
||||
reply: config.Reply,
|
||||
logger: logger,
|
||||
beginTask: beginTask,
|
||||
finishTask: finishTask,
|
||||
recordMessage: recordMessage,
|
||||
}
|
||||
}
|
||||
|
||||
// dispatch 接收一条解密消息并安排系统事件或聊天消息处理。
|
||||
func (d *messageDispatcher) dispatch(decrypted map[string]any) {
|
||||
// ctx、ok 用于本次流程后续判断的ctx、ok
|
||||
ctx, ok := d.beginTask()
|
||||
// ctx、finish、ok 分别是当前消息任务的上下文、释放函数与生命周期接纳结果。
|
||||
ctx, finish, ok := d.beginTask()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -125,11 +120,11 @@ func (d *messageDispatcher) dispatch(decrypted map[string]any) {
|
||||
select {
|
||||
case d.sem <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
d.finishTask()
|
||||
finish()
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer d.finishTask()
|
||||
defer finish()
|
||||
defer func() { <-d.sem }()
|
||||
d.handleMessageContext(ctx, decrypted)
|
||||
}()
|
||||
@@ -139,12 +134,12 @@ func (d *messageDispatcher) dispatch(decrypted map[string]any) {
|
||||
select {
|
||||
case d.sem <- struct{}{}:
|
||||
default:
|
||||
d.finishTask()
|
||||
finish()
|
||||
d.logger.Warn("消息处理并发达上限,丢弃消息", "limit", MessageSemaphoreSize)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer d.finishTask()
|
||||
defer finish()
|
||||
defer func() { <-d.sem }()
|
||||
d.handleMessageContext(ctx, decrypted)
|
||||
}()
|
||||
@@ -152,7 +147,13 @@ func (d *messageDispatcher) dispatch(decrypted map[string]any) {
|
||||
|
||||
// handleMessage 分类并投递消息,供 Account facade 和测试调用。
|
||||
func (d *messageDispatcher) handleMessage(decrypted map[string]any) {
|
||||
d.handleMessageContext(context.Background(), decrypted)
|
||||
// ctx、finish、accepted 分别是同步分发任务的上下文、释放函数及生命周期接纳结果。
|
||||
ctx, finish, accepted := d.beginTask()
|
||||
if !accepted {
|
||||
return
|
||||
}
|
||||
defer finish()
|
||||
d.handleMessageContext(ctx, decrypted)
|
||||
}
|
||||
|
||||
// handleMessageContext 将系统事件和聊天消息分别交给对应业务链。
|
||||
@@ -285,12 +286,12 @@ func (d *messageDispatcher) scheduleDebouncedReply(chat ChatMessage) {
|
||||
// lastMessage 用于本次流程后续判断的last消息
|
||||
lastMessage := current.lastMsg
|
||||
d.debounceMu.Unlock()
|
||||
// ctx、ok 用于本次流程后续判断的ctx、ok
|
||||
ctx, ok := d.beginTask()
|
||||
// ctx、finish、ok 分别是防抖回复任务的上下文、释放函数及生命周期接纳结果。
|
||||
ctx, finish, ok := d.beginTask()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
defer d.finishTask()
|
||||
defer finish()
|
||||
if d.reply != nil {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := d.reply.Handle(ctx, lastMessage); err != nil {
|
||||
|
||||
@@ -59,7 +59,7 @@ func (c *pendingRenewalCoordinator) waitContext(ctx context.Context) bool {
|
||||
return true
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return false
|
||||
}
|
||||
c.mu.Lock()
|
||||
// done 保存当前任务轮次的共享完成信号;nil 表示没有任何待收束的迟到续期任务。
|
||||
@@ -79,8 +79,7 @@ func (c *pendingRenewalCoordinator) waitContext(ctx context.Context) bool {
|
||||
// watch 登记并异步等待一条迟到续期响应,所有持久化工作继承账号生命周期 Context。
|
||||
func (c *pendingRenewalCoordinator) watch(
|
||||
parent context.Context,
|
||||
beginTask func() (context.Context, bool),
|
||||
finishTask func(),
|
||||
beginTask func() (context.Context, func(), bool),
|
||||
result *renew.Result,
|
||||
persist func(context.Context, *renew.Result) error,
|
||||
logger *slog.Logger,
|
||||
@@ -88,8 +87,8 @@ func (c *pendingRenewalCoordinator) watch(
|
||||
if c == nil || result == nil || !result.HasPending() {
|
||||
return
|
||||
}
|
||||
// taskCtx 是账号生命周期任务上下文,Stop 会先取消它再等待 Join。
|
||||
taskCtx, accepted := beginTask()
|
||||
// taskCtx、finish、accepted 分别是账号生命周期任务上下文、释放函数与接纳结果。
|
||||
taskCtx, finish, accepted := beginTask()
|
||||
if !accepted {
|
||||
return
|
||||
}
|
||||
@@ -102,7 +101,7 @@ func (c *pendingRenewalCoordinator) watch(
|
||||
c.beginTask()
|
||||
go func() {
|
||||
defer c.finishTask()
|
||||
defer finishTask()
|
||||
defer finish()
|
||||
// ctx、cancel 保存迟到响应等待的限时上下文及其取消函数。
|
||||
ctx, cancel := context.WithTimeout(taskCtx, 35*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -138,7 +138,7 @@ func (r *wsRecorder) waitContext(ctx context.Context) bool {
|
||||
return true
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return false
|
||||
}
|
||||
// done 表示 recorder worker 已经退出,供当前等待调用选择上下文超时或正常完成。
|
||||
done := r.done
|
||||
|
||||
@@ -42,6 +42,8 @@ const (
|
||||
EventTokenRenewal = "token_renewal"
|
||||
EventDeliveryResult = "delivery_result"
|
||||
EventSystemError = "system_error"
|
||||
// legacyNotifierOperationTimeout 是兼容无 Context 通知与等待入口的最长数据库或网络预算。
|
||||
legacyNotifierOperationTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// NotificationEvent 是一条可被渠道订阅过滤的通知事件。
|
||||
@@ -112,7 +114,10 @@ func (n *Notifier) Start(ctx context.Context) {
|
||||
|
||||
// Wait 等待 outbox worker 随生命周期 context 退出,并兼容旧调用方。
|
||||
func (n *Notifier) Wait() {
|
||||
_ = n.WaitContext(context.Background())
|
||||
// waitCtx、waitCancel 为兼容入口提供受限等待预算,避免异常 outbox worker 永久阻塞调用方。
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), legacyNotifierOperationTimeout)
|
||||
defer waitCancel()
|
||||
_ = n.WaitContext(waitCtx)
|
||||
}
|
||||
|
||||
// WaitContext 在 ctx 约束内等待 outbox worker 退出。
|
||||
@@ -124,7 +129,7 @@ func (n *Notifier) WaitContext(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("等待通知 worker 需要关闭 Context")
|
||||
}
|
||||
select {
|
||||
case <-n.done:
|
||||
@@ -138,7 +143,10 @@ func (n *Notifier) WaitContext(ctx context.Context) error {
|
||||
// accountID 为 cookie_id。向该账号所有已启用渠道发送发货通知。
|
||||
// NotifyDelivery 封装Notify发货业务协调。
|
||||
func (n *Notifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) {
|
||||
n.NotifyEvent(context.Background(), NotificationEvent{
|
||||
// notificationCtx、notificationCancel 为兼容入口限制 outbox 入队预算,避免订单链路产生无主数据库操作。
|
||||
notificationCtx, notificationCancel := context.WithTimeout(context.Background(), legacyNotifierOperationTimeout)
|
||||
defer notificationCancel()
|
||||
n.NotifyEvent(notificationCtx, NotificationEvent{
|
||||
AccountID: accountID,
|
||||
Type: EventDeliveryResult,
|
||||
Level: "info",
|
||||
@@ -186,7 +194,10 @@ func (n *Notifier) NotifyAccountAlert(accountID, level, title, body string) {
|
||||
|
||||
// NotifyAccountEvent 发送指定类型的账号通知。
|
||||
func (n *Notifier) NotifyAccountEvent(accountID, eventType, level, title, body string) {
|
||||
n.NotifyEvent(context.Background(), NotificationEvent{
|
||||
// notificationCtx、notificationCancel 为兼容入口限制 outbox 入队预算,避免账号告警脱离调用生命周期。
|
||||
notificationCtx, notificationCancel := context.WithTimeout(context.Background(), legacyNotifierOperationTimeout)
|
||||
defer notificationCancel()
|
||||
n.NotifyEvent(notificationCtx, NotificationEvent{
|
||||
AccountID: accountID,
|
||||
Type: eventType,
|
||||
Level: level,
|
||||
@@ -205,6 +216,10 @@ func (n *Notifier) notifyEvent(ctx context.Context, ev NotificationEvent, idempo
|
||||
if n == nil || n.repository == nil {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
n.logger.Warn("忽略缺少生命周期 Context 的通知入队请求")
|
||||
return
|
||||
}
|
||||
if ev.Time.IsZero() {
|
||||
ev.Time = time.Now()
|
||||
}
|
||||
@@ -360,8 +375,11 @@ func (n *Notifier) SendToChannel(channelID int64, body string) error {
|
||||
if n == nil || n.repository == nil {
|
||||
return fmt.Errorf("通知器未初始化")
|
||||
}
|
||||
// ch、err 用于本次流程后续判断的ch、err
|
||||
ch, err := n.repository.GetChannel(context.Background(), channelID)
|
||||
// queryCtx、queryCancel 为手动测试发送创建有界渠道查询预算,避免 HTTP 请求取消后继续无界访问数据库。
|
||||
queryCtx, queryCancel := context.WithTimeout(context.Background(), legacyNotifierOperationTimeout)
|
||||
defer queryCancel()
|
||||
// ch、err 分别是渠道配置及其查询错误。
|
||||
ch, err := n.repository.GetChannel(queryCtx, channelID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询渠道失败: %w", err)
|
||||
}
|
||||
@@ -1002,8 +1020,11 @@ func (n *Notifier) postJSON(url string, payload any) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, url, bytes.NewReader(body))
|
||||
// requestCtx、requestCancel 为单次渠道 HTTP 请求创建有界取消路径。
|
||||
requestCtx, requestCancel := context.WithTimeout(context.Background(), legacyNotifierOperationTimeout)
|
||||
defer requestCancel()
|
||||
// req、err 分别是携带取消语义的渠道 HTTP 请求及其构造错误。
|
||||
req, err := http.NewRequestWithContext(requestCtx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ const (
|
||||
sessionExpiredCooldown = 300 * time.Second
|
||||
passwordLoginCooldown = 300 * time.Second
|
||||
passwordErrorCooldown = 5 * time.Hour
|
||||
// legacySchedulerWaitTimeout 是兼容无 Context 停止与等待入口的最长收束预算。
|
||||
legacySchedulerWaitTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// loginRenewEnabledSetting 用于本次流程后续判断的登录Renew启用状态设置
|
||||
@@ -111,7 +113,7 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return
|
||||
}
|
||||
s.runOnce.Do(func() {
|
||||
// runCtx、cancel 将父生命周期转换为调度器私有的可主动停止上下文。
|
||||
@@ -155,7 +157,7 @@ func (s *Scheduler) StopContext(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("停止续期调度器需要关闭 Context")
|
||||
}
|
||||
s.mu.Lock()
|
||||
// cancel 是调度器运行上下文的取消函数快照,避免持锁执行取消回调。
|
||||
@@ -183,12 +185,18 @@ func (s *Scheduler) StopContext(ctx context.Context) error {
|
||||
|
||||
// Stop 主动停止调度器并无限期等待,兼容旧调用方的无错误返回签名。
|
||||
func (s *Scheduler) Stop() {
|
||||
_ = s.StopContext(context.Background())
|
||||
// stopCtx、stopCancel 为兼容入口提供受限停止预算,避免迟到 watcher 无限阻塞调用方。
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), legacySchedulerWaitTimeout)
|
||||
defer stopCancel()
|
||||
_ = s.StopContext(stopCtx)
|
||||
}
|
||||
|
||||
// Wait 等待定时循环和迟到响应 watcher 完成。
|
||||
func (s *Scheduler) Wait() {
|
||||
_ = s.WaitContext(context.Background())
|
||||
// waitCtx、waitCancel 为兼容入口提供受限等待预算,避免后台续期任务失联后永久阻塞。
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), legacySchedulerWaitTimeout)
|
||||
defer waitCancel()
|
||||
_ = s.WaitContext(waitCtx)
|
||||
}
|
||||
|
||||
// WaitContext 在 ctx 约束内等待定时循环和 watcher 完成。
|
||||
@@ -197,7 +205,7 @@ func (s *Scheduler) WaitContext(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
return errors.New("等待续期调度器需要关闭 Context")
|
||||
}
|
||||
select {
|
||||
case <-s.done:
|
||||
|
||||
@@ -111,6 +111,11 @@ func checkLifecycleArchitecture(root string) []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 {
|
||||
// frozen 表示受冻结 CAPTCHA 规范保护的实现;阶段三不得以生命周期迁移修改其调用链。
|
||||
// frozen 表示当前文件是否受冻结 CAPTCHA 规范保护,阶段三不允许修改其调用链。
|
||||
if frozen := isFrozenCaptchaLifecyclePath(relativePath); frozen {
|
||||
return nil
|
||||
}
|
||||
// inLifecyclePackage 表示当前文件是否属于需要显式继承所有者 Context 的生产包。
|
||||
inLifecyclePackage := false
|
||||
// lifecycleRoot 是当前待匹配的后台组件包前缀。
|
||||
@@ -123,17 +128,14 @@ func checkLifecycleArchitecture(root string) []violation {
|
||||
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"})
|
||||
}
|
||||
// fset 是将 AST 位置转换为稳定源码行号的文件集合。
|
||||
fset := token.NewFileSet()
|
||||
// syntax、parseErr 分别是当前后台源码 AST 及其解析错误。
|
||||
syntax, parseErr := parser.ParseFile(fset, relativePath, source, 0)
|
||||
if parseErr != nil {
|
||||
return []violation{{file: relativePath, line: 1, message: fmt.Sprintf("生命周期门禁无法解析生产源码: %v", parseErr)}}
|
||||
}
|
||||
return findings
|
||||
return checkUnboundedRootContexts(relativePath, syntax, fset)
|
||||
})...)
|
||||
// inventoryPath 是必须描述 owner、Context、Cancel 与 Wait/Join 的生命周期清单。
|
||||
inventoryPath := filepath.Join(root, "docs", "architecture", "lifecycle-inventory.md")
|
||||
@@ -151,6 +153,79 @@ func checkLifecycleArchitecture(root string) []violation {
|
||||
return violations
|
||||
}
|
||||
|
||||
// isFrozenCaptchaLifecyclePath 判断文件是否属于冻结 CAPTCHA 实现;它们只能由冻结规范授权修改。
|
||||
func isFrozenCaptchaLifecyclePath(relativePath string) bool {
|
||||
// frozenPaths 是规范直接保护的生产实现文件,不包含可自由重构的 browser 生命周期组件。
|
||||
frozenPaths := map[string]struct{}{
|
||||
"internal/browser/slider.go": {},
|
||||
"internal/browser/token_captcha.go": {},
|
||||
"internal/browser/token_captcha_fallback.go": {},
|
||||
}
|
||||
// frozen 表示当前路径是否命中冻结 CAPTCHA 的直接保护范围。
|
||||
_, frozen := frozenPaths[relativePath]
|
||||
return frozen
|
||||
}
|
||||
|
||||
// checkUnboundedRootContexts 拒绝后台源码把 Background 或 TODO 直接传入异步、I/O 或关闭链。
|
||||
// 唯一允许的根 Context 形态是 context.WithTimeout/WithDeadline 创建的显式有限收口预算。
|
||||
func checkUnboundedRootContexts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// boundedRoots 保存已经作为有限超时或截止时间父 Context 的根 Context 调用位置。
|
||||
boundedRoots := make(map[token.Pos]struct{})
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call、ok 分别是当前节点是否为函数调用及其断言结果。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok || !isBoundedContextConstructor(call) || len(call.Args) == 0 {
|
||||
return true
|
||||
}
|
||||
// rootCall、rootContext 分别是有限 Context 构造函数的父 Context 调用及其是否为根 Context。
|
||||
rootCall, rootContext := call.Args[0].(*ast.CallExpr)
|
||||
if rootContext && isRootContextCall(rootCall) {
|
||||
boundedRoots[rootCall.Pos()] = struct{}{}
|
||||
}
|
||||
return true
|
||||
})
|
||||
// violations 保存未继承 owner 且未声明有限预算的根 Context 位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call、ok 分别是当前节点是否为函数调用及其断言结果。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok || !isRootContextCall(call) {
|
||||
return true
|
||||
}
|
||||
// bounded 表示当前根 Context 已作为 WithTimeout 或 WithDeadline 的有限父 Context。
|
||||
if _, bounded := boundedRoots[call.Pos()]; bounded {
|
||||
return true
|
||||
}
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(call.Pos()).Line, message: "后台组件根 Context 必须继承 owner;仅显式 WithTimeout/WithDeadline 的有限收口预算可使用 Background"})
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// isRootContextCall 判断调用是否为标准库的 Background 或 TODO 根 Context 构造。
|
||||
func isRootContextCall(call *ast.CallExpr) bool {
|
||||
// selector、ok 分别是调用函数的包选择器及其断言结果。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
// packageName、ok 分别是选择器所属包标识符及其断言结果。
|
||||
packageName, ok := selector.X.(*ast.Ident)
|
||||
return ok && packageName.Name == "context" && (selector.Sel.Name == "Background" || selector.Sel.Name == "TODO")
|
||||
}
|
||||
|
||||
// isBoundedContextConstructor 判断调用是否显式创建可证明带截止时间的 Context。
|
||||
func isBoundedContextConstructor(call *ast.CallExpr) bool {
|
||||
// selector、ok 分别是调用函数的包选择器及其断言结果。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
// packageName、ok 分别是选择器所属包标识符及其断言结果。
|
||||
packageName, ok := selector.X.(*ast.Ident)
|
||||
return ok && packageName.Name == "context" && (selector.Sel.Name == "WithTimeout" || selector.Sel.Name == "WithDeadline")
|
||||
}
|
||||
|
||||
// checkReactArchitecture 检查 feature 物理边界、契约直连、网络旁路、动态导入和严格类型选项。
|
||||
func checkReactArchitecture(root string) []violation {
|
||||
// violations 保存阶段四前端架构违规。
|
||||
|
||||
@@ -82,7 +82,7 @@ func TestLifecycleArchitectureGate(t *testing.T) {
|
||||
t.Fatal(mkdirErr)
|
||||
}
|
||||
// writeErr 表示写入根 Context 违规样例失败的文件系统原因。
|
||||
if writeErr := os.WriteFile(workerPath, []byte("package engine\nimport \"context\"\nvar _ = context.Background()\n"), 0o600); writeErr != nil {
|
||||
if writeErr := os.WriteFile(workerPath, []byte("package engine\nimport (\"context\"; \"time\")\nvar _ = context.Background()\nvar _ = context.WithTimeout(context.Background(), time.Second)\n"), 0o600); writeErr != nil {
|
||||
t.Fatal(writeErr)
|
||||
}
|
||||
// inventoryPath 是模拟生命周期清单位置。
|
||||
|
||||
Reference in new issue
Block a user