阶段六:提取Engine状态与生命周期边界

This commit is contained in:
Christ committed 2026-08-14 21:09:45 +08:00
1 parent 10ba79c292
commit d38f8d7aaa
9 files changed
+675 -505

No files matched your search

File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -161,7 +161,8 @@ app shell / routes
- 已完成阶段 4 第六个 PR 切片“Server 事务与生命周期边界收口”:新增 Server 统一 Unit of Work,订单更新与导入不再直接管理事务;新增后台任务生命周期登记入口,HTTP 优雅关闭与批量发布恢复扫描器统一纳入等待流程;修复服务不可用时 handler 先做资源归属校验导致状态码变化的问题;新增事务提交/回滚测试并通过全量门禁,合并为一个可回滚提交;
- 已完成阶段 4 第七个 PR 切片“Server 直接依赖清理与应用服务装配收口”:统一装配订单、发布、登录、通信和分析应用服务;默认回复、账号设置、AI 设置、通知绑定、管理员查询及订单分析查询均迁移到 repository 或应用服务边界;handler 不再直接访问 `Store.DB`,新增装配一致性测试并通过全量门禁,合并为一个可回滚提交;
- 已完成阶段 5 PR 切片“应用构造依赖验证与生命周期接口”:`Server.New` 在构造阶段校验 `Store/Manager`,聊天服务通过 option 注入并移除生产运行时 setter;新增幂等 `Start/Wait/Stop`,`Stop` 统一等待 HTTP、后台扫描器和批量 worker;`cmd/server` 迁移到显式生命周期入口;新增构造失败、重复启动/停止和 worker 等待测试,并通过全量门禁,合并为一个可回滚提交;
- 阶段 6 下一 PR 切片为“Engine 账号 facade 与运行状态边界”:围绕 `engine.Account` 的状态字段、锁职责和 Stop 等待语义建立窄 facade,不提前拆分 WebSocket、凭证和自动化策略组件;
- 已完成阶段 6 第一个 PR 切片“Engine 账号 facade 与运行状态边界”:将连接状态、失败计数、离线告警和业务任务生命周期分别提取为独立锁组件;`Account` 保留 facade,`Stop` 对并发调用保持幂等并等待已登记任务;新增生命周期并发回归测试,未改变 WebSocket、凭证、自动化和冻结风控逻辑;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交;
- 阶段 6 下一 PR 切片为“Engine WebSocket 连接循环边界”:将连接建立、心跳、接收和 Token 轮换的生命周期编排收口到窄组件,保留凭证锁、重连结果和冻结风控行为,不提前拆分凭证或自动化策略;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -572,3 +573,4 @@ npm --prefix frontend run build
| 2026-08-14 | 完成阶段 4 第六个 PR 切片“Server 事务与生命周期边界收口” | 新增 Server 统一 Unit of Work,订单更新与导入不再直接管理事务;新增后台任务生命周期登记入口,HTTP 优雅关闭与批量发布恢复扫描器统一纳入等待流程;修复服务不可用时 handler 先做资源归属校验导致状态码变化的问题;事务测试、Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:Server 直接依赖清理与应用服务装配收口 |
| 2026-08-14 | 完成阶段 4 第七个 PR 切片“Server 直接依赖清理与应用服务装配收口” | 统一装配订单、发布、登录、通信和分析应用服务;默认回复、账号设置、AI 设置、通知绑定、管理员查询及订单分析查询迁移到 repository 或应用服务边界;handler 不再直接访问 `Store.DB`;装配测试、Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 5:应用构造依赖验证与生命周期接口 |
| 2026-08-14 | 完成阶段 5 PR 切片“应用构造依赖验证与生命周期接口” | `Server.New` 在构造阶段校验 `Store/Manager`,聊天服务改用 option 注入并移除生产运行时 setter;新增幂等 `Start/Wait/Stop`,`Stop` 统一等待 HTTP、后台扫描器和批量 worker;`cmd/server` 迁移到显式生命周期入口;构造失败、重复启动/停止和 worker 等待测试、全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Engine 账号 facade 与运行状态边界 |
| 2026-08-14 | 完成阶段 6 第一个 PR 切片“Engine 账号 facade 与运行状态边界” | 将连接状态、失败计数、离线告警和业务任务生命周期分别提取为独立锁组件;`Account` 保留 facade,`Stop` 对并发调用保持幂等并等待已登记任务;新增生命周期并发回归测试,未改变 WebSocket、凭证、自动化和冻结风控逻辑;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Engine WebSocket 连接循环边界 |
+88 -117
View File
@@ -180,6 +180,11 @@ type Account struct {
CookieStr string
UserID string // unb(myid)
// accountRuntimeState 独立保护连接状态、失败计数和离线告警状态。
accountRuntimeState
// lifecycle 独立保护业务任务接入、取消和等待语义。
lifecycle accountLifecycle
store *db.Store
mtop mtop.Client
renewer cookieRenewer
@@ -192,24 +197,9 @@ type Account struct {
refreshMu sync.Mutex
currentToken string
deviceID string
connFailures int
networkFailures int
shortDisconnects []time.Time
lastMsgReceived time.Time
lastTokenRefresh time.Time
lastCaptchaFailure time.Time
lastTokenStatus string
runtimeState string
runtimeMessage string
runtimeUpdatedAt time.Time
stopFn context.CancelFunc
stopped bool
conn WSConn
connStartedAt time.Time // 本次 WS 连接建立时间,用于短连接检测
authExpiredAlerted bool // 已发过 auth_expired 告警,连接恢复后复位(避免刷屏)
offlineNotified bool
offlineSince time.Time
lastOfflineReason string
tokenFetchFailures int
credentialFP string // 当前内存扁平 Cookie + 权威 Jar 的完整状态指纹
tokenCredentialFP string // currentToken 获取完成时绑定的完整凭证状态
@@ -229,13 +219,6 @@ type Account struct {
// 消息处理信号量
sem chan struct{}
// 业务任务生命周期。Stop 先禁止新增任务并取消 runtimeCtx,再等待已进入
// 自动化/回复链的任务退出。
taskMu sync.Mutex
taskWG sync.WaitGroup
runtimeCtx context.Context
accepting bool
reply *ReplyService
wsRecordOnce sync.Once
@@ -327,24 +310,26 @@ func New(cfg Config) *Account {
wsDialer = defaultDialer{}
}
a := &Account{
CookieID: cfg.CookieID,
CookieStr: cfg.CookieStr,
UserID: myid,
store: cfg.Store,
mtop: mtopClient,
renewer: renewer,
wsDialer: wsDialer,
handler: cfg.Handler,
logger: logger.With("account", cfg.CookieID),
deviceID: protocol.GenerateDeviceID(myid),
processed: make(map[string]time.Time),
debounceTimers: make(map[string]*debounceEntry),
sem: make(chan struct{}, MessageSemaphoreSize),
accepting: true,
runtimeState: RuntimeStarting,
runtimeMessage: "正在启动账号服务",
runtimeUpdatedAt: time.Now(),
credentialFP: credentialStateFingerprint(cfg.CookieStr, ""),
CookieID: cfg.CookieID,
CookieStr: cfg.CookieStr,
UserID: myid,
store: cfg.Store,
mtop: mtopClient,
renewer: renewer,
wsDialer: wsDialer,
handler: cfg.Handler,
logger: logger.With("account", cfg.CookieID),
deviceID: protocol.GenerateDeviceID(myid),
processed: make(map[string]time.Time),
debounceTimers: make(map[string]*debounceEntry),
sem: make(chan struct{}, MessageSemaphoreSize),
lifecycle: accountLifecycle{accepting: true},
accountRuntimeState: accountRuntimeState{
runtimeState: RuntimeStarting,
runtimeMessage: "正在启动账号服务",
runtimeUpdatedAt: time.Now(),
},
credentialFP: credentialStateFingerprint(cfg.CookieStr, ""),
}
if cfg.Store != nil {
a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger)
@@ -364,13 +349,7 @@ func (a *Account) Run(parent context.Context) error {
a.wsRecordWG.Wait()
a.pendingRenewWG.Wait()
}()
a.mu.Lock()
a.stopFn = cancel
a.mu.Unlock()
a.taskMu.Lock()
a.runtimeCtx = ctx
a.accepting = true
a.taskMu.Unlock()
a.lifecycle.start(ctx, cancel)
if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) {
a.logger.Info("账号在启动续期前已禁用")
return nil
@@ -505,7 +484,7 @@ func (a *Account) Run(parent context.Context) error {
}
continue
}
a.mu.Lock()
a.accountRuntimeState.mu.Lock()
a.conn = conn
a.connStartedAt = time.Now()
a.connFailures = 0
@@ -516,7 +495,7 @@ func (a *Account) Run(parent context.Context) error {
a.offlineNotified = false
a.offlineSince = time.Time{}
a.lastOfflineReason = ""
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
a.notifyTransportReady(ctx)
if shouldRecovered {
@@ -575,10 +554,10 @@ func (a *Account) Run(parent context.Context) error {
// 连接结束:只有认证类失败才清 token。已经建立后的网络断线继续
// 使用内存 token 与数据库缓存,避免无意义调用 Token API。
a.mu.Lock()
a.accountRuntimeState.mu.Lock()
startedAt := a.connStartedAt
a.conn = nil
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
connectedDuration := time.Since(startedAt)
select {
case <-rotateCh:
@@ -736,21 +715,13 @@ func (a *Account) clearConnectionToken(ctx context.Context) {
// Stop 优雅停止。
func (a *Account) Stop() {
a.mu.Lock()
if a.stopped {
a.mu.Unlock()
// cancel 是当前 Run 上下文的取消函数;shouldStop 表示当前调用是否负责首次清理。
cancel, shouldStop := a.lifecycle.stop()
if !shouldStop {
return
}
a.stopped = true
a.runtimeState = RuntimeStopped
a.runtimeMessage = "账号服务已停止"
a.runtimeUpdatedAt = time.Now()
cancel := a.stopFn
a.mu.Unlock()
a.taskMu.Lock()
a.accepting = false
a.taskMu.Unlock()
defer a.lifecycle.finishStop()
a.setRuntimeState(RuntimeStopped, "账号服务已停止")
if cancel != nil {
cancel()
}
@@ -764,33 +735,13 @@ func (a *Account) Stop() {
a.debounceTimers = make(map[string]*debounceEntry)
a.debounceMu.Unlock()
done := make(chan struct{})
go func() {
a.taskWG.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(10 * time.Second):
if !a.lifecycle.wait(10 * time.Second) {
a.logger.Warn("等待账号业务任务退出超时")
}
}
func (a *Account) beginTask() (context.Context, bool) {
a.taskMu.Lock()
defer a.taskMu.Unlock()
if !a.accepting {
return nil, false
}
ctx := a.runtimeCtx
if ctx == nil {
ctx = context.Background()
}
if ctx.Err() != nil {
return nil, false
}
a.taskWG.Add(1)
return ctx, true
return a.lifecycle.beginTask()
}
// handleMaxFailures 是历史兼容恢复入口;只尝试 Go 协议续期,不执行密码登录。
@@ -837,8 +788,8 @@ func (a *Account) handleMaxFailures(ctx context.Context) error {
// markAuthExpired 标记进入 auth_expired 状态。仅在首次(未告警过)返回 true,
// 连接恢复后由 Run 的 online 分支复位 authExpiredAlerted,避免重复告警刷屏。
func (a *Account) markAuthExpired() bool {
a.mu.Lock()
defer a.mu.Unlock()
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
if a.authExpiredAlerted {
return false
}
@@ -863,15 +814,15 @@ func (a *Account) notifyRecoveringOffline(ctx context.Context, reason string) {
}
func (a *Account) markOfflineNotified(reason string) bool {
a.mu.Lock()
a.accountRuntimeState.mu.Lock()
if a.offlineNotified {
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
return false
}
a.offlineNotified = true
a.offlineSince = time.Now()
a.lastOfflineReason = reason
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
return true
}
@@ -892,8 +843,8 @@ func (a *Account) alertEvent(ctx context.Context, eventType, level, title, body
}
func (a *Account) resetFailures() {
a.mu.Lock()
defer a.mu.Unlock()
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
a.connFailures = 0
}
@@ -1202,9 +1153,9 @@ func (a *Account) notifyCredentialUpdated(ctx context.Context) {
// retryDelay 按错误类型计算退避,并加入 0-30% 抖动。
// 多账号同时断线时,纯固定退避会让所有账号在同一秒重连,容易形成重连风暴。
func (a *Account) retryDelay(errMsg string) time.Duration {
a.mu.Lock()
a.accountRuntimeState.mu.Lock()
f := a.connFailures
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
if f < 1 {
f = 1
}
@@ -1222,9 +1173,9 @@ func (a *Account) retryDelay(errMsg string) time.Duration {
}
func (a *Account) networkRetryDelay() time.Duration {
a.mu.Lock()
a.accountRuntimeState.mu.Lock()
f := a.networkFailures
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
if f < 1 {
f = 1
}
@@ -1275,8 +1226,8 @@ func isEstablishedNetworkError(err error) bool {
}
func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool {
a.mu.Lock()
defer a.mu.Unlock()
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
if connectedDuration >= ShortConnectionThreshold {
a.shortDisconnects = nil
return false
@@ -1399,11 +1350,13 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s
a.mu.Lock()
a.credentialFP = credentialFP
a.tokenCredentialFP = credentialFP
a.lastMsgReceived = time.Time{}
a.lastCaptchaFailure = time.Time{}
a.tokenFetchFailures = 0
a.lastTokenStatus = tokenRefreshSuccess
a.mu.Unlock()
a.accountRuntimeState.mu.Lock()
a.lastMsgReceived = time.Time{}
a.accountRuntimeState.mu.Unlock()
return res.AccessToken, cookieStr, nil
}
@@ -1701,8 +1654,20 @@ func (a *Account) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
func (a *Account) RuntimeStatus() RuntimeStatus {
a.accountRuntimeState.mu.Lock()
// state 是当前运行状态枚举快照。
state := a.runtimeState
// message 是当前运行状态说明快照。
message := a.runtimeMessage
// connected 是当前连接存在且状态为 online 的快照。
connected := a.conn != nil && a.runtimeState == RuntimeOnline
// failures 是连续连接失败次数快照。
failures := a.connFailures
// updatedAt 是状态最近更新时间快照。
updatedAt := a.runtimeUpdatedAt
a.accountRuntimeState.mu.Unlock()
a.mu.Lock()
defer a.mu.Unlock()
remaining := int64(0)
if !a.tokenExpiresAt.IsZero() {
remaining = int64(time.Until(a.tokenExpiresAt).Seconds())
@@ -1710,18 +1675,20 @@ func (a *Account) RuntimeStatus() RuntimeStatus {
remaining = 0
}
}
return RuntimeStatus{
State: a.runtimeState,
Message: a.runtimeMessage,
Connected: a.conn != nil && a.runtimeState == RuntimeOnline,
Failures: a.connFailures,
UpdatedAt: a.runtimeUpdatedAt,
status := RuntimeStatus{
State: state,
Message: message,
Connected: connected,
Failures: failures,
UpdatedAt: updatedAt,
TokenAcquiredAt: a.tokenAcquiredAt,
TokenExpiresAt: a.tokenExpiresAt,
TokenRefreshAt: a.tokenRefreshAt,
TokenRemainingSeconds: remaining,
TokenRefreshStatus: a.lastTokenStatus,
}
a.mu.Unlock()
return status
}
func (a *Account) tokenRetryDelay() time.Duration {
@@ -1746,8 +1713,8 @@ func (a *Account) notifyTransportReady(ctx context.Context) {
}
func (a *Account) setRuntimeState(state, message string) {
a.mu.Lock()
defer a.mu.Unlock()
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
a.runtimeState = state
a.runtimeMessage = message
a.runtimeUpdatedAt = time.Now()
@@ -1755,9 +1722,9 @@ func (a *Account) setRuntimeState(state, message string) {
func (a *Account) setRuntimeError(ctx context.Context, err error) {
msg := strings.ToLower(errString(err))
a.mu.Lock()
a.accountRuntimeState.mu.Lock()
prev := a.runtimeState
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
switch {
case strings.Contains(msg, "验证"), strings.Contains(msg, "captcha"), strings.Contains(msg, "risk"), strings.Contains(msg, "rgv587"), strings.Contains(msg, "fail_sys_user_validate"):
a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证")
@@ -1818,11 +1785,15 @@ func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL stri
}
func (a *Account) currentSenderState() (WSConn, string, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.conn == nil {
a.accountRuntimeState.mu.Lock()
// conn 是当前连接快照;后续读取账号身份字段使用 Account 自身的凭证锁。
conn := a.conn
a.accountRuntimeState.mu.Unlock()
if conn == nil {
return nil, "", fmt.Errorf("%w: 账号 %s 当前没有可用 WebSocket 连接", automation.ErrMessageNotSent, a.CookieID)
}
a.mu.Lock()
defer a.mu.Unlock()
myID := strings.TrimSpace(a.UserID)
if myID == "" {
myID = protocol.TransCookies(a.CookieStr)["unb"]
@@ -1830,7 +1801,7 @@ func (a *Account) currentSenderState() (WSConn, string, error) {
if myID == "" {
return nil, "", fmt.Errorf("%w: 账号 %s 缺少 unb,无法发送消息", automation.ErrMessageNotSent, a.CookieID)
}
return a.conn, myID, nil
return conn, myID, nil
}
// FetchChatHistory reuses the account's registered IM connection. Keeping this
@@ -1868,8 +1839,8 @@ func (a *Account) FetchChatConversations(ctx context.Context, cursor int64, limi
// AutomationReady 报告自动化消息是否可以立即使用当前 WS 连接发送。
func (a *Account) AutomationReady() bool {
a.mu.Lock()
defer a.mu.Unlock()
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
return a.conn != nil && a.runtimeState == RuntimeOnline
}
+1 -1
View File
@@ -189,7 +189,7 @@ func TestStop_IdempotentAndClearsTimers(t *testing.T) {
func TestStop_CancelFunc_WhenNil(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
if acc.stopFn != nil {
if acc.lifecycle.stopFn != nil {
t.Fatal("未启动 Run 时 stopFn 应为 nil")
}
// 不应 panic。
+116
View File
@@ -0,0 +1,116 @@
package engine
import (
"context"
"sync"
"time"
)
// accountLifecycle 管理单账号运行上下文和业务任务生命周期。
// mu 保护 stopFn、stopped、runtimeCtx、accepting 以及 taskWG.Add 与停止切换的顺序;
// 持有 mu 时只做内存操作,不执行 I/O。Stop 先禁止新任务、再取消上下文,最后等待已有任务。
// accountLifecycle 是账号业务任务生命周期组件。
type accountLifecycle struct {
mu sync.Mutex
// stopFn 取消当前 Run 创建的账号运行上下文。
stopFn context.CancelFunc
// stopped 表示 Stop 是否已经完成第一次状态切换。
stopped bool
// runtimeCtx 是当前业务任务共享的账号运行上下文。
runtimeCtx context.Context
// accepting 表示是否仍允许新的消息或自动化任务进入。
accepting bool
// taskWG 等待所有已经通过 beginTask 的业务任务退出。
taskWG sync.WaitGroup
// stopDone 在第一次 Stop 的清理完成后关闭,保证并发 Stop 调用也等待完整收束。
stopDone chan struct{}
}
// start 注册一次 Run 的上下文和取消函数,并重新开放业务任务入口。
func (l *accountLifecycle) start(ctx context.Context, cancel context.CancelFunc) {
l.mu.Lock()
l.stopFn = cancel
l.runtimeCtx = ctx
l.accepting = true
l.mu.Unlock()
}
// stop 原子地禁止新任务并取出运行上下文取消函数。
func (l *accountLifecycle) stop() (context.CancelFunc, bool) {
l.mu.Lock()
if l.stopped {
// done 是第一次 Stop 完成全部清理后关闭的信号。
done := l.stopDone
l.mu.Unlock()
if done != nil {
<-done
}
return nil, false
}
l.stopped = true
l.accepting = false
l.stopDone = make(chan struct{})
// cancel 是当前账号 Run 上下文的取消函数。
cancel := l.stopFn
l.mu.Unlock()
return cancel, true
}
// finishStop 标记第一次 Stop 的清理已完成,并唤醒并发 Stop 调用者。
func (l *accountLifecycle) finishStop() {
l.mu.Lock()
defer l.mu.Unlock()
if l.stopDone != nil {
close(l.stopDone)
l.stopDone = nil
}
}
// beginTask 在生命周期锁内登记业务任务,避免 Stop 与 WaitGroup.Add 竞争。
func (l *accountLifecycle) beginTask() (context.Context, bool) {
l.mu.Lock()
defer l.mu.Unlock()
if !l.accepting {
return nil, false
}
// ctx 是新业务任务继承的账号运行上下文。
ctx := l.runtimeCtx
if ctx == nil {
ctx = context.Background()
}
if ctx.Err() != nil {
return nil, false
}
l.taskWG.Add(1)
return ctx, true
}
// finishTask 标记一个已登记的业务任务退出。
func (l *accountLifecycle) finishTask() {
l.taskWG.Done()
}
// wait 等待所有已登记业务任务结束;timeout 小于等于零表示无限等待。
func (l *accountLifecycle) wait(timeout time.Duration) bool {
// done 是所有已登记任务完成后关闭的等待信号。
done := make(chan struct{})
go func() {
l.taskWG.Wait()
close(done)
}()
if timeout <= 0 {
<-done
return true
}
// timer 是有限等待模式使用的超时定时器。
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-done:
return true
case <-timer.C:
return false
}
}
+57
View File
@@ -0,0 +1,57 @@
package engine
import (
"context"
"testing"
"time"
)
// TestAccountStopWaitsForTaskAndConcurrentStop 验证 Stop 禁止新任务、等待已有任务,并让并发 Stop 等待同一收束结果。
func TestAccountStopWaitsForTaskAndConcurrentStop(t *testing.T) {
// account 是未连接但已允许任务登记的测试账号 facade。
account := New(Config{CookieID: "lifecycle-test", CookieStr: "unb=1"})
// ctx 是测试业务任务使用的账号生命周期上下文。
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
account.lifecycle.start(ctx, cancel)
// taskCtx 是已登记任务拿到的上下文;ok 表示任务成功进入生命周期。
taskCtx, ok := account.beginTask()
if !ok || taskCtx == nil {
t.Fatal("业务任务应在 Stop 前成功登记")
}
// firstDone 和 secondDone 分别表示两个并发 Stop 调用已经完整返回。
firstDone := make(chan struct{})
// secondDone 是第二个并发 Stop 调用完整返回时关闭的信号。
secondDone := make(chan struct{})
go func() {
account.Stop()
close(firstDone)
}()
go func() {
account.Stop()
close(secondDone)
}()
select {
case <-firstDone:
t.Fatal("Stop 在已登记任务完成前提前返回")
case <-secondDone:
t.Fatal("并发 Stop 在已登记任务完成前提前返回")
case <-time.After(50 * time.Millisecond):
}
account.lifecycle.finishTask()
select {
case <-firstDone:
case <-time.After(time.Second):
t.Fatal("第一次 Stop 未在任务完成后返回")
}
select {
case <-secondDone:
case <-time.After(time.Second):
t.Fatal("并发 Stop 未等待第一次 Stop 完成")
}
// stoppedCtx 是 Stop 后尝试登记任务得到的上下文;stoppedOK 必须为 false。
stoppedCtx, stoppedOK := account.beginTask()
if stoppedOK || stoppedCtx != nil {
t.Fatal("Stop 后不应再接受业务任务")
}
}
+7 -7
View File
@@ -17,9 +17,9 @@ func (a *Account) dispatch(decrypted map[string]any) {
if !ok {
return
}
a.mu.Lock()
a.accountRuntimeState.mu.Lock()
a.lastMsgReceived = time.Now()
a.mu.Unlock()
a.accountRuntimeState.mu.Unlock()
// 系统业务事件不能丢弃:并发满时让 WS 读取产生背压,等待处理槽位。
// 普通聊天仍采用非阻塞限流,避免聊天洪峰拖垮连接。
@@ -28,11 +28,11 @@ func (a *Account) dispatch(decrypted map[string]any) {
select {
case a.sem <- struct{}{}:
case <-ctx.Done():
a.taskWG.Done()
a.lifecycle.finishTask()
return
}
go func() {
defer a.taskWG.Done()
defer a.lifecycle.finishTask()
defer func() { <-a.sem }()
a.handleMessageContext(ctx, decrypted)
}()
@@ -42,12 +42,12 @@ func (a *Account) dispatch(decrypted map[string]any) {
select {
case a.sem <- struct{}{}:
default:
a.taskWG.Done()
a.lifecycle.finishTask()
a.logger.Warn("消息处理并发达上限,丢弃消息", "limit", MessageSemaphoreSize)
return
}
go func() {
defer a.taskWG.Done()
defer a.lifecycle.finishTask()
defer func() { <-a.sem }()
a.handleMessageContext(ctx, decrypted)
}()
@@ -168,7 +168,7 @@ func (a *Account) scheduleDebouncedReply(chat ChatMessage) {
if !ok {
return
}
defer a.taskWG.Done()
defer a.lifecycle.finishTask()
if a.reply != nil {
if err := a.reply.Handle(ctx, lastMsg); err != nil {
+1 -6
View File
@@ -355,12 +355,7 @@ func TestStopCancelsInFlightReplyHandler(t *testing.T) {
acc.reply = nil
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
acc.mu.Lock()
acc.stopFn = cancel
acc.mu.Unlock()
acc.taskMu.Lock()
acc.runtimeCtx = ctx
acc.taskMu.Unlock()
acc.lifecycle.start(ctx, cancel)
acc.scheduleDebouncedReply(ChatMessage{ChatID: "cancel-chat", SenderUserID: "buyer", Text: "hi"})
select {
case <-handler.started:
+41
View File
@@ -0,0 +1,41 @@
package engine
import (
"sync"
"time"
)
// accountRuntimeState 保存账号连接状态及其诊断计数。
// mu 只保护本组件字段;调用方不得持有该锁执行数据库、网络或通知 I/O。
// accountRuntimeState 是账号连接运行状态组件。
type accountRuntimeState struct {
mu sync.Mutex
// connFailures 是连续连接或认证失败次数。
connFailures int
// networkFailures 是网络断线累计次数。
networkFailures int
// shortDisconnects 保存短连接断开的时间窗口。
shortDisconnects []time.Time
// lastMsgReceived 是最近收到平台消息的时间。
lastMsgReceived time.Time
// runtimeState 是当前账号运行状态枚举。
runtimeState string
// runtimeMessage 是当前运行状态给用户展示的说明。
runtimeMessage string
// runtimeUpdatedAt 是最近一次状态变更时间。
runtimeUpdatedAt time.Time
// conn 是当前已注册的 WebSocket 连接。
conn WSConn
// connStartedAt 是当前 WebSocket 连接建立时间。
connStartedAt time.Time
// authExpiredAlerted 表示当前凭证失效是否已经发送过告警。
authExpiredAlerted bool
// offlineNotified 表示当前离线周期是否已经发送过离线通知。
offlineNotified bool
// offlineSince 是当前离线周期的起始时间。
offlineSince time.Time
// lastOfflineReason 是当前离线周期最后一次记录的原因。
lastOfflineReason string
}