阶段六:收口Engine凭证与Token生命周期

This commit is contained in:
Christ committed 2026-08-14 22:03:46 +08:00
1 parent 84ad707abe
commit 176ecb7b59
7 files changed
+346 -304

No files matched your search

File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -164,7 +164,8 @@ app shell / routes
- 已完成阶段 6 第一个 PR 切片“Engine 账号 facade 与运行状态边界”:将连接状态、失败计数、离线告警和业务任务生命周期分别提取为独立锁组件;`Account` 保留 facade,`Stop` 对并发调用保持幂等并等待已登记任务;新增生命周期并发回归测试,未改变 WebSocket、凭证、自动化和冻结风控逻辑;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交;
- 已完成阶段 6 第二个 PR 切片“Engine WebSocket 连接循环边界”:`registerConnection` 在凭证锁内统一快照复核与 WebSocket 注册,`runConnectionSession` 统一心跳、接收、Token 轮换 goroutine 的创建/取消/等待;`Account` 继续负责凭证错误、风控和重连结果解释;新增会话收束测试,未改变冻结风控行为;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交;
- 已完成阶段 6 第三个 PR 切片“Engine WebSocket 记录与消息分发边界”:将 WS 记录 worker、消息去重、防抖和并发信号量分别收口到独立组件;`Account` 保留兼容 facade,系统事件背压、聊天洪峰限流、消息顺序、自动化事件优先级和 Stop 等待语义保持不变;全量 Go 测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交;
- 阶段 6 下一 PR 切片为“Engine 凭证状态与 Token 生命周期边界”:集中 Cookie 快照、Token 缓存、刷新/清理和设备指纹的一致性边界,保留风控恢复、刷新锁和冻结规范行为,不拆分 Automation;
- 已完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界”:将 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态收口到独立 `credentialState`;运行状态锁改为显式 `runtimeMu`,避免匿名组件锁冲突;保留风控恢复、刷新锁、Cookie/Token 绑定和 WebSocket 注册前快照复核语义;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交;
- 阶段 6 下一 PR 切片为“Automation 事件事实与规则匹配边界”:先分离 WebSocket 事件事实提取、规则匹配和动作计划生成,禁止规则匹配隐式执行外部动作,保留自动化事件优先级与结果状态语义;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -578,3 +579,4 @@ npm --prefix frontend run build
| 2026-08-14 | 完成阶段 6 第一个 PR 切片“Engine 账号 facade 与运行状态边界” | 将连接状态、失败计数、离线告警和业务任务生命周期分别提取为独立锁组件;`Account` 保留 facade,`Stop` 对并发调用保持幂等并等待已登记任务;新增生命周期并发回归测试,未改变 WebSocket、凭证、自动化和冻结风控逻辑;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Engine WebSocket 连接循环边界 |
| 2026-08-14 | 完成阶段 6 第二个 PR 切片“Engine WebSocket 连接循环边界” | `registerConnection` 在凭证锁内统一快照复核与 WebSocket 注册,`runConnectionSession` 统一心跳、接收、Token 轮换 goroutine 的创建/取消/等待;`Account` 继续负责凭证错误、风控和重连结果解释;新增会话收束测试,未改变冻结风控行为;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Engine WebSocket 记录与消息分发边界 |
| 2026-08-14 | 完成阶段 6 第三个 PR 切片“Engine WebSocket 记录与消息分发边界” | 新增 `messageDispatcher` 与 `wsRecorder`,分别管理消息去重/防抖/并发投递和 WebSocket 诊断记录队列/worker;`Account` 仅保留 facade 与生命周期接线,动态 Handler、系统事件背压、聊天洪峰限流和 Stop 等待语义保持兼容;Engine 全量回归与并发测试、后续门禁通过并合并为一个可回滚提交 | 阶段 6:Engine 凭证状态与 Token 生命周期边界 |
| 2026-08-14 | 完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界” | 新增 `credentialState`,集中 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态;运行状态组件锁改名为 `runtimeMu`,保持 `Account` facade 字段访问兼容;Cookie 更新、Token 清理、风控恢复和 WS 注册前凭证快照复核语义保持不变;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 事件事实与规则匹配边界 |
+40 -53
View File
@@ -176,9 +176,10 @@ const (
// Account 单账号运行时。
type Account struct {
CookieID string
CookieStr string
UserID string // unb(myid)
// CookieID 是账号在数据库中的稳定标识。
CookieID string
// credentialState 独立保护 Cookie、Token、设备指纹和刷新状态。
credentialState
// accountRuntimeState 独立保护连接状态、失败计数和离线告警状态。
accountRuntimeState
@@ -194,22 +195,6 @@ type Account struct {
handler Handler
logger *slog.Logger
// 运行时状态(受 mu 保护)
mu sync.Mutex
refreshMu sync.Mutex
currentToken string
deviceID string
lastTokenRefresh time.Time
lastCaptchaFailure time.Time
lastTokenStatus string
tokenFetchFailures int
credentialFP string // 当前内存扁平 Cookie + 权威 Jar 的完整状态指纹
tokenCredentialFP string // currentToken 获取完成时绑定的完整凭证状态
tokenAcquiredAt time.Time
tokenExpiresAt time.Time
tokenRefreshAt time.Time
tokenFingerprint string // 仅用于诊断,不保存原始 Token
reply *ReplyService
// recorder 管理 WebSocket 报文记录 worker 的队列和等待。
recorder *wsRecorder
@@ -301,23 +286,25 @@ func New(cfg Config) *Account {
}
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),
lifecycle: accountLifecycle{accepting: true},
accountRuntimeState: accountRuntimeState{
runtimeState: RuntimeStarting,
runtimeMessage: "正在启动账号服务",
runtimeUpdatedAt: time.Now(),
},
recorder: newWSRecorder(cfg.Store, cfg.CookieID, logger),
credentialFP: credentialStateFingerprint(cfg.CookieStr, ""),
recorder: newWSRecorder(cfg.Store, cfg.CookieID, logger),
credentialState: credentialState{
CookieStr: cfg.CookieStr,
UserID: myid,
deviceID: protocol.GenerateDeviceID(myid),
credentialFP: credentialStateFingerprint(cfg.CookieStr, ""),
},
}
if cfg.Store != nil {
a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger)
@@ -477,7 +464,7 @@ func (a *Account) Run(parent context.Context) error {
}
continue
}
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
a.conn = conn
a.connStartedAt = time.Now()
a.connFailures = 0
@@ -488,7 +475,7 @@ func (a *Account) Run(parent context.Context) error {
a.offlineNotified = false
a.offlineSince = time.Time{}
a.lastOfflineReason = ""
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
a.notifyTransportReady(ctx)
if shouldRecovered {
@@ -672,8 +659,8 @@ func (a *Account) handleMaxFailures(ctx context.Context) error {
// markAuthExpired 标记进入 auth_expired 状态。仅在首次(未告警过)返回 true,
// 连接恢复后由 Run 的 online 分支复位 authExpiredAlerted,避免重复告警刷屏。
func (a *Account) markAuthExpired() bool {
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Lock()
defer a.runtimeMu.Unlock()
if a.authExpiredAlerted {
return false
}
@@ -698,15 +685,15 @@ func (a *Account) notifyRecoveringOffline(ctx context.Context, reason string) {
}
func (a *Account) markOfflineNotified(reason string) bool {
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
if a.offlineNotified {
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
return false
}
a.offlineNotified = true
a.offlineSince = time.Now()
a.lastOfflineReason = reason
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
return true
}
@@ -727,8 +714,8 @@ func (a *Account) alertEvent(ctx context.Context, eventType, level, title, body
}
func (a *Account) resetFailures() {
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Lock()
defer a.runtimeMu.Unlock()
a.connFailures = 0
}
@@ -1037,9 +1024,9 @@ func (a *Account) notifyCredentialUpdated(ctx context.Context) {
// retryDelay 按错误类型计算退避,并加入 0-30% 抖动。
// 多账号同时断线时,纯固定退避会让所有账号在同一秒重连,容易形成重连风暴。
func (a *Account) retryDelay(errMsg string) time.Duration {
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
f := a.connFailures
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
if f < 1 {
f = 1
}
@@ -1057,9 +1044,9 @@ func (a *Account) retryDelay(errMsg string) time.Duration {
}
func (a *Account) networkRetryDelay() time.Duration {
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
f := a.networkFailures
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
if f < 1 {
f = 1
}
@@ -1110,8 +1097,8 @@ func isEstablishedNetworkError(err error) bool {
}
func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool {
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Lock()
defer a.runtimeMu.Unlock()
if connectedDuration >= ShortConnectionThreshold {
a.shortDisconnects = nil
return false
@@ -1238,9 +1225,9 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s
a.tokenFetchFailures = 0
a.lastTokenStatus = tokenRefreshSuccess
a.mu.Unlock()
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
a.lastMsgReceived = time.Time{}
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
return res.AccessToken, cookieStr, nil
}
@@ -1538,7 +1525,7 @@ func (a *Account) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
func (a *Account) RuntimeStatus() RuntimeStatus {
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
// state 是当前运行状态枚举快照。
state := a.runtimeState
// message 是当前运行状态说明快照。
@@ -1549,7 +1536,7 @@ func (a *Account) RuntimeStatus() RuntimeStatus {
failures := a.connFailures
// updatedAt 是状态最近更新时间快照。
updatedAt := a.runtimeUpdatedAt
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
a.mu.Lock()
remaining := int64(0)
@@ -1577,9 +1564,9 @@ func (a *Account) RuntimeStatus() RuntimeStatus {
// recordMessageReceived 更新最近收到消息时间,供 messageDispatcher 使用。
func (a *Account) recordMessageReceived(receivedAt time.Time) {
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
a.lastMsgReceived = receivedAt
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
}
func (a *Account) tokenRetryDelay() time.Duration {
@@ -1604,8 +1591,8 @@ func (a *Account) notifyTransportReady(ctx context.Context) {
}
func (a *Account) setRuntimeState(state, message string) {
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Lock()
defer a.runtimeMu.Unlock()
a.runtimeState = state
a.runtimeMessage = message
a.runtimeUpdatedAt = time.Now()
@@ -1613,9 +1600,9 @@ func (a *Account) setRuntimeState(state, message string) {
func (a *Account) setRuntimeError(ctx context.Context, err error) {
msg := strings.ToLower(errString(err))
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
prev := a.runtimeState
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.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, "闲鱼要求安全验证,请重新扫码并完成验证")
@@ -1676,10 +1663,10 @@ func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL stri
}
func (a *Account) currentSenderState() (WSConn, string, error) {
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
// conn 是当前连接快照;后续读取账号身份字段使用 Account 自身的凭证锁。
conn := a.conn
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
if conn == nil {
return nil, "", fmt.Errorf("%w: 账号 %s 当前没有可用 WebSocket 连接", automation.ErrMessageNotSent, a.CookieID)
}
@@ -1730,8 +1717,8 @@ func (a *Account) FetchChatConversations(ctx context.Context, cursor int64, limi
// AutomationReady 报告自动化消息是否可以立即使用当前 WS 连接发送。
func (a *Account) AutomationReady() bool {
a.accountRuntimeState.mu.Lock()
defer a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Lock()
defer a.runtimeMu.Unlock()
return a.conn != nil && a.runtimeState == RuntimeOnline
}
+2 -2
View File
@@ -83,10 +83,10 @@ func (a *Account) runConnectionSession(ctx context.Context, conn WSConn, refresh
default:
}
// connectedDuration 是从运行状态组件读取的连接持续时间快照。
a.accountRuntimeState.mu.Lock()
a.runtimeMu.Lock()
startedAt := a.connStartedAt
a.conn = nil
a.accountRuntimeState.mu.Unlock()
a.runtimeMu.Unlock()
connectedDuration := time.Since(startedAt)
return connectionSessionResult{
ReceiveErr: receiveErr,
+4 -4
View File
@@ -15,10 +15,10 @@ func TestRunConnectionSessionOwnsHeartbeatAndReceiveCleanup(t *testing.T) {
// conn 是可通过关闭信号结束接收循环的测试连接。
conn := &fakeWSConn{recvBlock: true, closeCh: make(chan struct{}), heartbeatDone: heartbeatDone}
// accountRuntimeState 记录本次会话的连接和建立时间,模拟注册成功后的状态。
account.accountRuntimeState.mu.Lock()
account.runtimeMu.Lock()
account.conn = conn
account.connStartedAt = time.Now().Add(-time.Second)
account.accountRuntimeState.mu.Unlock()
account.runtimeMu.Unlock()
// ctx 是控制会话 goroutine 退出的上下文。
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -43,10 +43,10 @@ func TestRunConnectionSessionOwnsHeartbeatAndReceiveCleanup(t *testing.T) {
if result.Rotated {
t.Fatal("取消会话不应被识别为 Token 主动轮换")
}
account.accountRuntimeState.mu.Lock()
account.runtimeMu.Lock()
// currentConn 是会话组件清理后的连接状态快照。
currentConn := account.conn
account.accountRuntimeState.mu.Unlock()
account.runtimeMu.Unlock()
if currentConn != nil {
t.Fatal("会话结束后连接状态未清理")
}
+46
View File
@@ -0,0 +1,46 @@
package engine
import (
"sync"
"time"
)
// credentialState 保存账号 Cookie、Token、设备指纹和刷新诊断状态。
// mu 保护本组件全部字段;持锁时不得执行数据库、网络或通知 I/O。
// refreshMu 串行化完整的凭证刷新事务,允许在锁内执行必要的凭证 I/O,
// 但调用方不得在持有它时再次获取同一锁。
type credentialState struct {
// mu 保护 Cookie、Token、设备指纹和刷新诊断字段。
mu sync.Mutex
// refreshMu 串行化 Cookie 读取、Token 刷新和缓存清理事务。
refreshMu sync.Mutex
// CookieStr 是当前运行时使用的扁平 Cookie 快照。
CookieStr string
// UserID 是从 Cookie 的 unb 字段解析出的闲鱼用户标识。
UserID string
// currentToken 是最近一次获取的连接级访问 Token。
currentToken string
// deviceID 是页面生命周期内复用的设备标识。
deviceID string
// lastTokenRefresh 是最近一次开始 Token 刷新的时间。
lastTokenRefresh time.Time
// lastCaptchaFailure 是最近一次 Token 风控验证失败时间。
lastCaptchaFailure time.Time
// lastTokenStatus 是最近一次 Token 刷新状态。
lastTokenStatus string
// tokenFetchFailures 是当前连接周期内 Token 获取失败次数。
tokenFetchFailures int
// credentialFP 是当前 Cookie 与权威 Cookie Jar 的完整状态指纹。
credentialFP string
// tokenCredentialFP 是当前 Token 获取时绑定的凭证状态指纹。
tokenCredentialFP string
// tokenAcquiredAt 是最近一次成功获取 Token 的时间。
tokenAcquiredAt time.Time
// tokenExpiresAt 是服务端声明的 Token 过期时间。
tokenExpiresAt time.Time
// tokenRefreshAt 是本地提前轮换 Token 的时间。
tokenRefreshAt time.Time
// tokenFingerprint 是 Token 的不可逆诊断指纹,不保存 Token 原文。
tokenFingerprint string
}
+3 -2
View File
@@ -6,11 +6,12 @@ import (
)
// accountRuntimeState 保存账号连接状态及其诊断计数。
// mu 只保护本组件字段;调用方不得持有该锁执行数据库、网络或通知 I/O。
// runtimeMu 只保护本组件字段;调用方不得持有该锁执行数据库、网络或通知 I/O。
// accountRuntimeState 是账号连接运行状态组件。
type accountRuntimeState struct {
mu sync.Mutex
// runtimeMu 保护连接、失败计数和离线告警字段。
runtimeMu sync.Mutex
// connFailures 是连续连接或认证失败次数。
connFailures int