feat: 对齐闲鱼续期流程并完善业务管理

对齐官方 WebSocket 批量握手、注册、心跳、ACK、同步恢复及运行时设备标识生命周期。

保留 Cookie 完整属性,接入静默续期和保存登录信息设置,并在凭证更新后重建账号连接。

完善订单与商品同步、卡券和通知渠道交互,更新前端品牌、时间展示及嵌入资源。

补充 Go 与前端回归测试,确保完整检查和生产构建通过。
This commit is contained in:
Christ committed 2026-07-22 12:51:52 +08:00
1 parent 3cc1d4094d
commit d77c317452
69 files changed
+3169 -819

No files matched your search

+176 -137
View File
@@ -18,6 +18,7 @@ import (
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/protocol"
"xianyu-go/internal/xianyu/renew"
@@ -87,7 +88,6 @@ type tokenCaptchaHandler interface {
const (
tokenRefreshStarted = "started"
tokenRefreshSuccess = "success"
tokenRefreshSuccessFromCache = "success_from_cache"
tokenRefreshFailedCaptcha = "failed_captcha"
tokenRefreshFailedCaptchaError = "failed_captcha_exception"
tokenRefreshFailedTimeout = "failed_timeout"
@@ -141,7 +141,7 @@ type Account struct {
store *db.Store
mtop mtop.Client
renewer cookieRenewer
wsDialer wsDialer
wsDialer WSDialer
handler Handler
logger *slog.Logger
@@ -200,6 +200,7 @@ type debounceEntry struct {
// WSConn 是 Account 对 ws 连接的最小契约。*ws.Conn 实现该接口;
// 测试可注入 fakeWSConn 以隔离真实 WS 握手与网络。
type WSConn interface {
Register(ctx context.Context, deviceID, accessToken string) error
HeartbeatLoop(ctx context.Context, interval time.Duration) error
ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error
Close() error
@@ -207,15 +208,15 @@ type WSConn interface {
SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error
}
// wsDialer 抽象 ws.Dial,便于测试替身。
type wsDialer interface {
// WSDialer 抽象 WebSocket 打开阶段,便于测试隔离真实网络。
type WSDialer interface {
Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error)
}
type defaultDialer struct{}
func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error) {
return ws.Dial(ctx, cfg, logger)
return ws.Open(ctx, cfg, logger)
}
type cookieRenewer interface {
@@ -243,6 +244,8 @@ type Config struct {
MTop mtop.Client
// Renewer 可选:注入 Cookie 接口续期服务以便测试 mock。nil 时使用默认实现。
Renewer cookieRenewer
// WSDialer 可选:用于测试隔离原生 WebSocket 握手。
WSDialer WSDialer
}
// New 构造单账号运行时(未启动)。
@@ -262,6 +265,10 @@ func New(cfg Config) *Account {
}
cookies := protocol.TransCookies(cfg.CookieStr)
myid := cookies["unb"]
wsDialer := cfg.WSDialer
if wsDialer == nil {
wsDialer = defaultDialer{}
}
a := &Account{
CookieID: cfg.CookieID,
CookieStr: cfg.CookieStr,
@@ -269,7 +276,7 @@ func New(cfg Config) *Account {
store: cfg.Store,
mtop: mtopClient,
renewer: renewer,
wsDialer: defaultDialer{},
wsDialer: wsDialer,
handler: cfg.Handler,
logger: logger.With("account", cfg.CookieID),
deviceID: protocol.GenerateDeviceID(myid),
@@ -281,14 +288,6 @@ func New(cfg Config) *Account {
runtimeMessage: "正在启动账号服务",
runtimeUpdatedAt: time.Now(),
}
if cfg.Store != nil && cfg.Store.Tokens != nil {
deviceID, err := cfg.Store.Tokens.GetOrCreateDeviceID(context.Background(), cfg.CookieID, a.deviceID)
if err != nil {
logger.Error("读取或保存账号 device ID 失败", "account", cfg.CookieID, "err", err)
} else {
a.deviceID = deviceID
}
}
if cfg.Store != nil {
a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger)
}
@@ -308,6 +307,11 @@ func (a *Account) Run(parent context.Context) error {
a.runtimeCtx = ctx
a.accepting = true
a.taskMu.Unlock()
// 对应官网页面初始化时执行一次 auto-login plugin。成功更新 Cookie 时,
// adoptRecoveredCookie 会旋转本次引擎身份,等价于页面 reload 后新建引擎。
if a.renewer != nil {
_ = a.tryAPIRenew(ctx)
}
for {
if ctx.Err() != nil {
@@ -322,8 +326,25 @@ func (a *Account) Run(parent context.Context) error {
// 每次新建 IM 连接前吸收数据库中的最新 Cookie。健康连接不会被续期任务
// 主动打断;Cookie 变化只会使本次重连放弃旧 token 并重新派生。
a.reloadCookieFromDB(ctx)
token, cookieStr, err := a.acquireRuntimeToken(ctx)
// 官网先完成原生 WebSocket 握手,再从 authTokenCallback 获取本次
// 连接专用 token,最后发送 /reg。
conn, err := a.wsDialer.Dial(ctx, ws.Config{Recorder: a.wsRecorder()}, a.logger)
if err != nil {
a.logger.Error("WS 握手失败", "err", err)
if retryErr := a.handleWSConnectFailure(ctx, err, &invalidTokenRetried); retryErr != nil {
return retryErr
}
continue
}
connectedAt := time.Now()
// The official web client calls
// mtop.taobao.idlemessage.pc.login.token from authTokenCallback for every
// loginV2/reConnect attempt. Do the same here: an access token belongs to
// one connection attempt and must never be reused for a later /reg.
token, cookieStr, err := a.acquireFreshConnectionToken(ctx)
if err != nil {
_ = conn.Close()
a.logger.Error("获取 token 失败", "err", err)
a.mu.Lock()
status := a.lastTokenStatus
@@ -374,23 +395,7 @@ func (a *Account) Run(parent context.Context) error {
a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务")
a.logger.Info("token 刷新成功")
// 2) 连接 WS + 注册。
var recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
if a.store != nil && a.store.WSMessages != nil {
recorder = func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{
CookieID: a.CookieID,
Direction: direction,
RawText: rawText,
ParsedJSON: parsedJSON,
MessageKind: "",
ParseStatus: parseStatus,
Error: errMsg,
}); err != nil {
a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
}
}
}
// 2) 使用刚获得的 token 注册已经打开的 WS。
a.mu.Lock()
deviceID := a.deviceID
a.mu.Unlock()
@@ -400,50 +405,17 @@ func (a *Account) Run(parent context.Context) error {
}
if !a.cookieSnapshotMatchesDB(ctx, cookieStr) {
credentialUnlock()
_ = conn.Close()
a.reloadCookieFromDB(ctx)
continue
}
attemptStartedAt := time.Now()
conn, err := a.wsDialer.Dial(ctx, ws.Config{
CookieStr: cookieStr,
DeviceID: deviceID,
AccessToken: token,
Recorder: recorder,
}, a.logger)
err = conn.Register(ctx, deviceID, token)
credentialUnlock()
if err != nil {
a.logger.Error("WS 连接失败", "err", err)
if ws.IsInvalidTokenError(err) && !invalidTokenRetried {
invalidTokenRetried = true
a.clearCurrentToken()
a.clearTokenCache(ctx)
a.setRuntimeState(RuntimeConnecting, "消息凭证被拒绝,正在重新获取一次新凭证")
continue
}
if ws.IsConnectLimitError(err) {
a.setRuntimeState(RuntimeReconnecting, "消息服务连接数受限,正在限速重试")
if sleepCtx(ctx, withRetryJitter(30*time.Second)) != nil {
return ctx.Err()
}
continue
}
a.mu.Lock()
a.connFailures++
failures := a.connFailures
a.mu.Unlock()
if ws.IsInvalidTokenError(err) || ws.IsAuthenticationError(err) {
a.clearCurrentToken()
a.clearTokenCache(ctx)
}
a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试")
if failures >= MaxConnectionFailures {
if err := a.handleMaxFailures(ctx); err != nil {
return err
}
continue
}
if sleepCtx(ctx, a.retryDelay("ws_dial")) != nil {
return ctx.Err()
_ = conn.Close()
a.logger.Error("WS 注册失败", "err", err)
if retryErr := a.handleWSConnectFailure(ctx, err, &invalidTokenRetried); retryErr != nil {
return retryErr
}
continue
}
@@ -494,11 +466,13 @@ func (a *Account) Run(parent context.Context) error {
// 正常 close 的 async-for 会直接进入下一轮,不计任何失败。
if recvErr == nil {
a.clearConnectionToken(ctx)
a.setRuntimeState(RuntimeReconnecting, "消息连接已结束,正在重新连接")
continue
}
if isEstablishedNetworkError(recvErr) {
a.clearConnectionToken(ctx)
a.mu.Lock()
a.networkFailures++
networkFailures := a.networkFailures
@@ -530,7 +504,7 @@ func (a *Account) Run(parent context.Context) error {
a.connFailures++
failures := a.connFailures
a.mu.Unlock()
if time.Since(attemptStartedAt) < 15*time.Second {
if time.Since(connectedAt) < 15*time.Second {
a.clearTokenCache(ctx)
}
a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,稍后自动重连")
@@ -548,6 +522,67 @@ func (a *Account) Run(parent context.Context) error {
}
}
func (a *Account) wsRecorder() func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
if a.store == nil || a.store.WSMessages == nil {
return nil
}
return func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{
CookieID: a.CookieID,
Direction: direction,
RawText: rawText,
ParsedJSON: parsedJSON,
MessageKind: "",
ParseStatus: parseStatus,
Error: errMsg,
}); err != nil {
a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
}
}
}
func (a *Account) handleWSConnectFailure(ctx context.Context, err error, invalidTokenRetried *bool) error {
if ws.IsInvalidTokenError(err) && !*invalidTokenRetried {
*invalidTokenRetried = true
a.clearCurrentToken()
a.clearTokenCache(ctx)
a.setRuntimeState(RuntimeConnecting, "消息凭证被拒绝,正在重新获取一次新凭证")
return nil
}
if ws.IsConnectLimitError(err) {
a.setRuntimeState(RuntimeReconnecting, "消息服务连接数受限,正在限速重试")
return sleepCtx(ctx, withRetryJitter(30*time.Second))
}
a.mu.Lock()
a.connFailures++
failures := a.connFailures
a.mu.Unlock()
if ws.IsInvalidTokenError(err) || ws.IsAuthenticationError(err) {
a.clearCurrentToken()
a.clearTokenCache(ctx)
}
a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试")
if failures >= MaxConnectionFailures {
return a.handleMaxFailures(ctx)
}
return sleepCtx(ctx, a.retryDelay("ws_connect"))
}
// acquireFreshConnectionToken mirrors the official web message client:
// authTokenCallback obtains a fresh login.token result before every WebSocket
// loginV2/reConnect and the returned accessToken is used only for that /reg.
func (a *Account) acquireFreshConnectionToken(ctx context.Context) (string, string, error) {
return a.refreshToken(ctx)
}
// clearConnectionToken ends the lifetime of the token used by the previous
// WebSocket attempt. The page-runtime device ID remains stable until a Cookie
// update maps to an official page reload.
func (a *Account) clearConnectionToken(ctx context.Context) {
a.clearCurrentToken()
a.clearTokenCache(ctx)
}
// Stop 优雅停止。
func (a *Account) Stop() {
a.mu.Lock()
@@ -768,6 +803,7 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool {
}
updated := false
if res.NewCookies != "" && res.NewCookies != cookieStr {
a.persistRenewCookieSnapshot(ctx, cookieStr, res.NewCookies, res.SetCookies)
updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期")
}
if res.Success {
@@ -785,6 +821,25 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool {
return false
}
func (a *Account) persistRenewCookieSnapshot(ctx context.Context, oldCookies, newCookies string, setCookies []string) {
if a.store == nil || a.store.Cookies == nil {
return
}
detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
if err != nil || detail == nil {
return
}
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
if len(snapshot) == 0 {
snapshot = cookierefresh.SnapshotFromCookieString(oldCookies, ".goofish.com")
}
snapshot = cookierefresh.ApplySetCookies(snapshot, renew.SilentHasLoginURL, setCookies, time.Now())
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()); err != nil {
a.logger.Warn("保存接口续期 Cookie 快照失败", "err", err)
}
}
// adoptRecoveredCookie 统一接收“轻量检查/接口续期/浏览器恢复”拿到的新 Cookie。
// Cookie 变更意味着旧 accessToken 与 session 绑定关系失效,必须清 token 缓存,
// 让下一轮 acquireToken 使用新 Cookie 重新派生凭证。
@@ -799,6 +854,7 @@ func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source s
return false
}
a.replaceCookieStr(newCookies)
a.rotateDeviceID(newCookies)
a.clearCurrentToken()
if a.store != nil && a.store.Cookies != nil {
if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, newCookies); err != nil {
@@ -906,8 +962,8 @@ func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool {
}
// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。
// 成功时把 token + device_id 缓存到 DB(saveTokenCache),供进程重启复用与
// 稳态重连时跳过 mtop(acquireToken 命中缓存即直接返回)。
// 成功时记录 token 的服务端过期时间并保持 device_id 持久化,但连接流程
// 不会复用该 token;下一次 loginV2/reConnect 仍会重新调用本方法。
func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
return a.refreshTokenWithMinGap(ctx, false)
}
@@ -1008,8 +1064,20 @@ func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr strin
}
a.replaceCookieStr(res.UpdatedCookies)
if a.store != nil && a.store.Cookies != nil {
if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, res.UpdatedCookies); err != nil {
a.logger.Error("token 响应后保存 cookie 失败", "cookie_id", a.CookieID, "err", err)
detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
if detailErr == nil && detail != nil {
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
if len(snapshot) == 0 {
snapshot = cookierefresh.SnapshotFromCookieString(cookieStr, ".goofish.com")
}
snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies)
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
detailErr = a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix())
} else {
detailErr = a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, res.UpdatedCookies)
}
if detailErr != nil {
a.logger.Error("token 响应后保存 cookie 失败", "cookie_id", a.CookieID, "err", detailErr)
}
}
return res.UpdatedCookies
@@ -1062,39 +1130,23 @@ func (a *Account) tokenCaptchaCooldownRemaining() time.Duration {
return remaining
}
// acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控
// 与瞬时失败影响),否则调 refreshToken 重新派生并落库缓存。
//
// 设计:稳态重连时复用未过期缓存 token,避免每次重连都打 mtop(降低风控触发)。
// 缓存 token 若已被服务端失效,dial 后会短连接断开 → clearTokenCache → 下轮重新派生,自愈。
// acquireToken is kept for internal callers and tests, but intentionally does
// not reuse the persisted accessToken. Official web reconnects always invoke
// the login.token API before /reg.
func (a *Account) acquireToken(ctx context.Context) (string, string, error) {
return a.acquireTokenWithMinGap(ctx, false)
}
// acquireRuntimeToken 对齐参考主循环:网络重连时只要内存 token 仍存在就直接
// 复用;只有认证分支明确清空它后,才重新检查数据库缓存或调用 Token API。
// acquireRuntimeToken is retained as a compatibility wrapper for focused
// tests and older internal callers. It follows the same fresh-token rule.
func (a *Account) acquireRuntimeToken(ctx context.Context) (string, string, error) {
a.mu.Lock()
token := a.currentToken
cookieStr := a.CookieStr
a.mu.Unlock()
if strings.TrimSpace(token) != "" {
return token, cookieStr, nil
}
return a.acquireToken(ctx)
return a.acquireFreshConnectionToken(ctx)
}
func (a *Account) acquireTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
if token, ok := a.cachedTokenIfFresh(ctx); ok {
a.mu.Lock()
a.currentToken = token
a.lastTokenRefresh = time.Now()
a.lastTokenStatus = tokenRefreshSuccessFromCache
cookieStr := a.CookieStr
a.mu.Unlock()
a.logger.Info("使用缓存的 accessToken,跳过 mtop 刷新")
return token, cookieStr, nil
}
// Invalidate any access token left by an older process/attempt before asking
// MTOP for the token that will be bound to this connection.
a.clearTokenCache(ctx)
return a.refreshToken(ctx)
}
@@ -1130,39 +1182,9 @@ func tokenFailureIsNonCounted(status string) bool {
}
}
// cachedTokenIfFresh 返回未过期的缓存 accessToken。无缓存 / 已过期返回 ok=false。
func (a *Account) cachedTokenIfFresh(ctx context.Context) (string, bool) {
if a.store == nil || a.store.Tokens == nil {
return "", false
}
tk, err := a.store.Tokens.Get(ctx, a.CookieID)
if err != nil {
return "", false
}
a.mu.Lock()
cookieStr := a.CookieStr
a.mu.Unlock()
expectedFingerprint := credentialCookieFingerprint(cookieStr)
if tk.AccessToken == "" || tk.ExpireAt <= time.Now().Unix() ||
tk.CookieFingerprint == "" || tk.CookieFingerprint != expectedFingerprint {
// 参考实现发现过期缓存后立即删除整行,再进入标准 token 请求。
if tk.AccessToken != "" {
a.clearTokenCache(ctx)
}
return "", false
}
// 命中缓存时同步复用其 device_id,保证 token 与 /reg.did 一致。
if tk.DeviceID != "" {
a.mu.Lock()
a.deviceID = tk.DeviceID
a.mu.Unlock()
}
return tk.AccessToken, true
}
// saveTokenCache uses the expiry returned by the token API. A response without
// a usable accessTokenExpiredTime remains valid for the current process only;
// it is deliberately not assigned a guessed multi-hour lifetime.
// saveTokenCache records the server expiry and current page-runtime identity.
// It is diagnostic state only: acquireToken never reads the accessToken back
// for a later WebSocket registration.
func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, cookieStr string) {
if a.store == nil || a.store.Tokens == nil || accessToken == "" {
return
@@ -1206,6 +1228,7 @@ func (a *Account) reloadCookieFromDB(ctx context.Context) bool {
}
a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID)
a.replaceCookieStr(d.Value)
a.rotateDeviceID(d.Value)
a.clearCurrentToken()
a.clearTokenCache(ctx)
a.mu.Lock()
@@ -1322,6 +1345,16 @@ func (a *Account) replaceCookieStr(cookieStr string) {
}
}
func (a *Account) rotateDeviceID(cookieStr string) {
userID := protocol.TransCookies(cookieStr)["unb"]
a.mu.Lock()
if userID == "" {
userID = a.UserID
}
a.deviceID = protocol.GenerateDeviceID(userID)
a.mu.Unlock()
}
// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。
func (a *Account) UpdateCookie(cookieStr string) {
if strings.TrimSpace(cookieStr) == "" {
@@ -1346,9 +1379,15 @@ func (a *Account) UpdateCookie(cookieStr string) {
}
}
a.replaceCookieStr(cookieStr)
// Updating credentials does not close a healthy connection. Clearing the
// in-memory and persisted token makes the next reconnect authenticate from
// this Cookie snapshot instead of reusing a token issued for the old one.
a.rotateDeviceID(cookieStr)
// 官网静默续期成功会 location.reload()。本地收到外部 Cookie 更新时关闭
// 健康连接,让主循环立即用新 Cookie、新 device ID 和新 token 重建。
a.clearCurrentToken()
a.clearTokenCache(context.Background())
a.mu.Lock()
conn := a.conn
a.mu.Unlock()
if conn != nil {
_ = conn.Close()
}
}
+4 -4
View File
@@ -275,8 +275,8 @@ func TestTryAPIRenewSuccessShortCircuitsRecovery(t *testing.T) {
if saved != "unb=123; _m_h5_tk=tk_2;" {
t.Fatalf("DB cookie 未更新: %q", saved)
}
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("接口续期后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
t.Fatalf("接口续期后应清 token;数据库中的旧 device ID 不再参与运行时身份: tk=%+v err=%v", tk, err)
}
}
@@ -306,8 +306,8 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
if saved != "unb=123; _m_h5_tk=partial;" {
t.Fatalf("部分 cookie 应先保存到 DB: %q", saved)
}
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("部分 cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
t.Fatalf("部分 cookie 更新后应清 token: tk=%+v err=%v", tk, err)
}
}
+5
View File
@@ -54,6 +54,11 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if err != nil || cfg == nil || !cfg.AIEnabled {
return nil, nil // 未启用 AI
}
// AI 设置面向砍价场景。普通未命中消息继续交给默认回复,避免 AI
// 抢答问候、售后等与砍价无关的消息。
if !bargainMessageRe.MatchString(strings.ToLower(m.Text)) {
return nil, nil
}
aiCfg, err := a.globalAIConfig(ctx)
if err != nil {
return nil, fmt.Errorf("读取全局 AI 配置失败: %w", err)
+19 -5
View File
@@ -76,7 +76,7 @@ func TestAIReply_DisabledReturnsNil(t *testing.T) {
a := NewAIReplier("cid", s, nil)
// 无配置记录 → 未启用 → nil。
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("未配置应返回 nil,nil: res=%+v err=%v", res, err)
}
@@ -97,7 +97,7 @@ func TestAIReply_NoAPIKeyReturnsNil(t *testing.T) {
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
a := NewAIReplier("cid", s, nil)
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("无 APIKey 应返回 nil,nil: res=%+v err=%v", res, err)
}
@@ -137,7 +137,7 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) {
s.Settings.Set(ctx, "ai_api_url", srv.URL)
a := NewAIReplier("cid", s, nil)
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
res, err := a.Reply(ctx, chatMsg("还能优惠吗", "item1", "chat1"))
if err == nil {
t.Fatalf("HTTP 500 应返回错误,got res=%+v", res)
}
@@ -165,7 +165,7 @@ func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) {
s.Settings.Set(ctx, "ai_api_url", srv.URL)
a := NewAIReplier("cid", s, nil)
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
res, err := a.Reply(ctx, chatMsg("可以便宜一点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("空 choices 应返回 nil,nil: res=%+v err=%v", res, err)
}
@@ -182,7 +182,7 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
s.Settings.Set(ctx, "ai_api_url", srv.URL)
a := NewAIReplier("cid", s, nil)
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
res, err := a.Reply(ctx, chatMsg("最低多少钱", "item1", "chat1"))
if err != nil {
t.Fatalf("成功调用不应报错: %v", err)
}
@@ -191,6 +191,20 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
}
}
func TestAIReply_NonBargainMessageFallsThrough(t *testing.T) {
s, cleanup := newAIStore(t)
defer cleanup()
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
s.Settings.Set(ctx, "ai_api_key", "sk-test")
s.Settings.Set(ctx, "ai_api_url", "http://127.0.0.1:1")
res, err := NewAIReplier("cid", s, nil).Reply(ctx, chatMsg("在吗,什么时候发货", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("非砍价消息应交给默认回复: res=%+v err=%v", res, err)
}
}
// TestGlobalAIConfig 默认值兜底 + 显式设置覆盖。
func TestGlobalAIConfig(t *testing.T) {
s, cleanup := newAIStore(t)
+19 -15
View File
@@ -118,8 +118,10 @@ func (s *statusMtop) CheckLoginStatusContext(context.Context, string) (*mtop.Log
return s.result, s.err
}
// TestAcquireToken_CacheHitSkipsMtop 缓存命中且未过期时跳过 mtop 调用。
func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
// TestAcquireToken_CacheHitStillFetchesFreshToken matches the official web
// client: every connection attempt calls login.token even when a persisted
// token has not reached its advertised expiry.
func TestAcquireToken_CacheHitStillFetchesFreshToken(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
@@ -129,11 +131,11 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
if err != nil {
t.Fatalf("acquireToken: %v", err)
}
if token != "cached-tok" {
t.Fatalf("应使用缓存 token,got %s", token)
if token != "tok-mtop" {
t.Fatalf("应使用新获取 token,got %s", token)
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("缓存命中不应调用 mtop,got %d", calls)
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("每次连接都应调用 mtop,got %d", calls)
}
if !strings.Contains(cookies, "_m_h5_tk=tk_1") {
t.Fatalf("缓存命中应返回其绑定的 Cookie: %q", cookies)
@@ -160,7 +162,7 @@ func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) {
}
}
func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.T) {
func TestAcquireRuntimeTokenReplacesMemoryToken(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
@@ -168,11 +170,11 @@ func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.
_ = store.Tokens.Clear(context.Background(), "cid")
token, _, err := acc.acquireRuntimeToken(context.Background())
if err != nil || token != "runtime-token" {
if err != nil || token != "tok-mtop" {
t.Fatalf("runtime token=%q err=%v", token, err)
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("网络重连复用内存 token 时不应调用 mtop,calls=%d", calls)
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("网络重连应获取新 token,calls=%d", calls)
}
}
@@ -218,6 +220,7 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
oldDeviceID := acc.deviceID
saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
res := acc.tryLoginStatusCheck(context.Background())
if !res.recovered || res.riskRequired {
@@ -230,8 +233,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
if err != nil || saved != newCookie {
t.Fatalf("DB Cookie 未更新: got %q err=%v", saved, err)
}
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
t.Fatalf("Cookie 更新后应清 token 并为页面重载轮换 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
}
}
@@ -266,6 +269,7 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 预置旧 session 的 token 缓存。
oldDeviceID := acc.deviceID
saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
// 外部更新 DB cookie(模拟重新扫码),userID=0 复用现有 user_id。
newCookie := "unb=123; _m_h5_tk=newtk_2; sgcookie=abc"
@@ -276,9 +280,9 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
if got := acc.CurrentCookieStr(); got != newCookie {
t.Fatalf("应采纳 DB 新 cookie,got %s", got)
}
// 新 cookie 对应新 session,旧 token 应清除但 device ID 必须保留。
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("cookie 变更后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
// 新 cookie 对应官网页面重载:旧 token 清除,运行时 device ID 轮换。
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
t.Fatalf("cookie 变更后应清 token 并轮换运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
}
}
+95 -25
View File
@@ -3,6 +3,7 @@ package engine
import (
"context"
"errors"
"fmt"
"log/slog"
"path/filepath"
"sync"
@@ -58,10 +59,33 @@ func (f *fakeFailTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, str
return nil, f.err
}
type sequencedTokenMtop struct {
fakeRunMtop
mu sync.Mutex
devices []string
cookies []string
calls int
}
func (s *sequencedTokenMtop) RefreshTokenWithDeviceIDContext(_ context.Context, cookieStr, deviceID string) (*mtop.RefreshResult, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.calls++
s.devices = append(s.devices, deviceID)
s.cookies = append(s.cookies, cookieStr)
return &mtop.RefreshResult{
AccessToken: fmt.Sprintf("fresh-%d", s.calls),
AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(),
}, nil
}
// fakeWSConn 实现 WSConn,可控地投递消息并阻塞到 ctx 取消。
type fakeWSConn struct {
mu sync.Mutex
closed bool
registerErr error
registeredDID string
registeredTok string
sentTexts []string
sentImages []string
heartbeatDone chan struct{}
@@ -72,6 +96,15 @@ type fakeWSConn struct {
recvErr error
}
func (f *fakeWSConn) Register(_ context.Context, deviceID, accessToken string) error {
f.mu.Lock()
f.registeredDID = deviceID
f.registeredTok = accessToken
err := f.registerErr
f.mu.Unlock()
return err
}
func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
<-ctx.Done()
if f.heartbeatDone != nil {
@@ -221,13 +254,12 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
time.Sleep(50 * time.Millisecond)
}
// 初始 token 应通过 ws.Config.AccessToken 传给 Dial(非 SetAccessToken)。
d := acc.wsDialer.(*fakeDialer)
d.mu.Lock()
gotToken := d.lastCfg.AccessToken == "tok-1"
d.mu.Unlock()
// token 必须在握手成功后通过 Register 发送,而不是在 Dial 前获得。
conn.mu.Lock()
gotToken := conn.registeredTok == "tok-1"
conn.mu.Unlock()
if !gotToken {
t.Fatal("Dial 未收到 ws.Config.AccessToken=tok-1")
t.Fatal("Register 未收到 token=tok-1")
}
// 取消 ctx → Run 应退出。
@@ -272,7 +304,7 @@ func TestRun_DialFailureIncrementsFailures(t *testing.T) {
}
}
// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并复用当前内存 token。
// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并重新获取 token。
func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
@@ -311,12 +343,52 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
case <-time.After(3 * time.Second):
t.Fatal("重连后 ctx 取消 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("正常重连应复用内存 token,不应重复请求 mtop: calls=%d", calls)
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
t.Fatalf("正常重连应重新请求 mtop: calls=%d", calls)
}
}
func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) {
func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "unused"}}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
dialer := &fakeDialer{results: []dialResult{
{conn: &fakeWSConn{recvBlock: false}},
{conn: &fakeWSConn{recvBlock: true}},
}}
acc.wsDialer = dialer
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
waitForDialCalls(t, dialer, 2)
cancel()
<-done
dialer.mu.Lock()
conns := append([]*fakeWSConn(nil), dialer.conns...)
dialer.mu.Unlock()
if len(conns) < 2 {
t.Fatalf("dial conns=%d want>=2", len(conns))
}
conns[0].mu.Lock()
firstToken := conns[0].registeredTok
conns[0].mu.Unlock()
conns[1].mu.Lock()
secondToken := conns[1].registeredTok
conns[1].mu.Unlock()
if firstToken != "fresh-1" || secondToken != "fresh-2" {
t.Fatalf("reconnect tokens=%v", []string{firstToken, secondToken})
}
mtopClient.mu.Lock()
devices := append([]string(nil), mtopClient.devices...)
mtopClient.mu.Unlock()
if len(devices) != 2 || devices[0] == "" || devices[0] != devices[1] {
t.Fatalf("device IDs must remain stable: %v", devices)
}
}
func TestRun_EstablishedNetworkErrorClearsConnectionToken(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
@@ -340,15 +412,15 @@ func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) {
currentToken := acc.currentToken
networkFailures := acc.networkFailures
acc.mu.Unlock()
if networkFailures != 1 || currentToken != "tok-1" {
if networkFailures != 1 || currentToken != "" {
cancel()
<-done
t.Fatalf("网络断线不应清空内存 token: failures=%d token=%q", networkFailures, currentToken)
t.Fatalf("网络断线应结束当前 token 生命周期: failures=%d token=%q", networkFailures, currentToken)
}
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "" {
cancel()
<-done
t.Fatalf("网络断线不应删除 token 缓存: cached=%+v err=%v", cached, err)
t.Fatalf("网络断线应清除 token 缓存: cached=%+v err=%v", cached, err)
}
cancel()
select {
@@ -366,7 +438,7 @@ func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) {
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
dialer := &fakeDialer{results: []dialResult{
{err: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}},
{conn: &fakeWSConn{registerErr: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}},
{conn: &fakeWSConn{recvBlock: true}},
}}
acc.wsDialer = dialer
@@ -384,7 +456,7 @@ func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) {
}
func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "token"}}
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "token"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
newCookie := "unb=123; _m_h5_tk=db-renewed_2; cookie2=new"
@@ -406,16 +478,13 @@ func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) {
cancel()
<-done
dialer.mu.Lock()
configs := append([]ws.Config(nil), dialer.configs...)
dialer.mu.Unlock()
if len(configs) < 2 {
t.Fatalf("dial configs=%d want>=2", len(configs))
mtopClient.mu.Lock()
cookies := append([]string(nil), mtopClient.cookies...)
mtopClient.mu.Unlock()
if len(cookies) < 2 || cookies[1] != newCookie {
t.Fatalf("second token Cookie=%v want=%q", cookies, newCookie)
}
if configs[1].CookieStr != newCookie {
t.Fatalf("second dial Cookie=%q want=%q", configs[1].CookieStr, newCookie)
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
if calls := mtopClient.calls; calls != 2 {
t.Fatalf("Cookie change should invalidate token for reconnect, calls=%d", calls)
}
}
@@ -462,6 +531,7 @@ func TestRun_DisabledAccountExits(t *testing.T) {
func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
defer cleanup()
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}}
h := &failingRefreshHandler{}
acc.handler = h
acc.mu.Lock()