阶段十:完成 Go Engine 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 05:12:37 +08:00
1 parent 9255c233aa
commit 64e7868444
22 files changed
+1355 -8557

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -630,3 +630,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 10 第四个 PR 切片“Go internal/server 注释基线按领域清零” | 为 HTTP handlers、应用服务、事务边界、批量发布、登录/二维码、请求解析、测试辅助和错误处理代码补齐函数、变量、字段及常量中文注释;增强 Go 注释检查器对多行文档块与分组 const/var 注释的识别;`internal/server` 注释基线清零,Server 定向测试和 Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/db 与 internal/xianyu 领域注释基线 |
| 2026-08-15 | 完成阶段 10 第五个 PR 切片“Go internal/db 注释基线按领域清零” | 为数据库 Store、repository、迁移/方言、多数据库适配、凭证与订单数据访问及其测试补齐函数、变量、字段和常量中文注释;`internal/db` 注释基线清零;数据库定向测试、SQLite 迁移与 CRUD 验证、Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/xianyu 领域注释基线 |
| 2026-08-15 | 完成阶段 10 第六个 PR 切片“Go internal/xianyu 注释基线按领域清零” | 为 MTOP 请求、协议编解码与签名、二维码登录、续期、WebSocket、Cookie 刷新和用户代理代码及其测试补齐函数、变量、字段和常量中文注释;`internal/xianyu` 及子包注释基线清零;平台协议定向测试和 Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/engine、internal/automation 与其他领域注释基线 |
| 2026-08-15 | 完成阶段 10 第七个 PR 切片“Go internal/engine 注释基线按领域清零” | 为账号运行时、连接循环、凭证作用域、消息分发、回复策略、AI、令牌缓存和生命周期测试补齐函数、变量、字段及常量中文注释;`internal/engine` 注释基线清零;Engine 定向测试、`go test -race ./internal/engine`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/automation、internal/account、internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 |
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+48 -2
View File
@@ -20,11 +20,13 @@ import (
"xianyu-go/internal/netguard"
)
// defaultAIBaseURL 保存defaultAIBaseURL,供当前处理流程使用
const (
defaultAIBaseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
defaultAIModel = "qwen-plus"
)
// newAIHTTPClient 保存newAIHTTPClient,供当前处理流程使用
var newAIHTTPClient = func(baseURL string) (*http.Client, error) {
return netguard.TrustedEndpointHTTPClient(baseURL, 30*time.Second)
}
@@ -50,6 +52,7 @@ func NewAIReplier(cookieID string, store *db.Store, logger *slog.Logger) *AIRepl
// Reply 实现 AIReplier 接口。
func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error) {
// cfg、err 保存cfg、err,供当前处理流程使用
cfg, err := a.store.AIReply.Get(ctx, a.cookieID)
if err != nil || cfg == nil || !cfg.AIEnabled {
return nil, nil // 未启用 AI
@@ -59,6 +62,7 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if !bargainMessageRe.MatchString(strings.ToLower(m.Text)) {
return nil, nil
}
// aiCfg、err 保存人工智能Cfg、err,供当前处理流程使用
aiCfg, err := a.globalAIConfig(ctx)
if err != nil {
return nil, fmt.Errorf("读取全局 AI 配置失败: %w", err)
@@ -70,6 +74,7 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
// 取商品信息和当前会话状态构造 system prompt。
itemTitle, itemPrice, itemDesc := a.itemInfo(ctx, m.ItemID)
// history、bargainCount、isBargain、err 保存history、bargainCount、isBargain、err,供当前处理流程使用
history, bargainCount, isBargain, err := a.conversationContext(ctx, m)
if err != nil {
return nil, fmt.Errorf("读取 AI 对话历史失败: %w", err)
@@ -77,7 +82,9 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if isBargain {
bargainCount++
}
// withinBargainLimit 保存withinBargain上限,供当前处理流程使用
withinBargainLimit := !isBargain || bargainCount <= cfg.MaxBargainRounds
// systemPrompt 保存系统Prompt,供当前处理流程使用
systemPrompt := buildSystemPrompt(
cfg.CustomPrompts, itemTitle, itemPrice, itemDesc,
cfg.MaxDiscountPercent, cfg.MaxDiscountAmount, cfg.MaxBargainRounds, bargainCount,
@@ -95,10 +102,14 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if err != nil {
return nil, fmt.Errorf("AI API 地址无效: %w", err)
}
// client 保存client,供当前处理流程使用
client := openai.NewClientWithConfig(clientCfg)
// messages 保存消息列表,供当前处理流程使用
messages := []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem, Content: systemPrompt}}
// message 表示当前遍历过程中的消息
for _, message := range history {
// role 保存role,供当前处理流程使用
role := openai.ChatMessageRoleUser
if message.Role == "assistant" {
role = openai.ChatMessageRoleAssistant
@@ -107,8 +118,10 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
}
messages = append(messages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser, Content: m.Text})
// aiCtx、cancel 保存人工智能Ctx、cancel,供当前处理流程使用
aiCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// resp、err 保存resp、err,供当前处理流程使用
resp, err := client.CreateChatCompletion(aiCtx, openai.ChatCompletionRequest{
Model: aiCfg.Model,
Messages: messages,
@@ -120,12 +133,15 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if len(resp.Choices) == 0 {
return nil, nil
}
// reply 保存回复,供当前处理流程使用
reply := strings.TrimSpace(resp.Choices[0].Message.Content)
if reply == "" {
return nil, nil
}
// minimumPrice 保存minimumPrice,供当前处理流程使用
minimumPrice := minimumAllowedPrice(itemPrice, cfg.MaxDiscountPercent, cfg.MaxDiscountAmount, withinBargainLimit)
if offered, unsafe := unsafeOfferedPrice(reply, minimumPrice); unsafe {
if // offered、unsafe 保存offered、unsafe,供当前处理流程使用
offered, unsafe := unsafeOfferedPrice(reply, minimumPrice); unsafe {
a.logger.Warn("AI 报价超过折扣边界,使用安全回复", "offered", offered, "minimum", minimumPrice)
if minimumPrice >= itemPrice || !withinBargainLimit {
reply = "抱歉,当前价格已经是最低价,暂时不能再优惠了。"
@@ -134,11 +150,13 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
}
}
if m.ChatID != "" && m.ItemID != "" {
// intent 保存intent,供当前处理流程使用
intent := "chat"
if isBargain {
intent = "bargain"
}
if err := a.store.AIReply.AddConversationExchange(ctx, a.cookieID, m.ChatID, m.SenderUserID, m.ItemID,
if // err 保存err,供当前处理流程使用
err := a.store.AIReply.AddConversationExchange(ctx, a.cookieID, m.ChatID, m.SenderUserID, m.ItemID,
db.AIConversationMessage{Role: "user", Content: m.Text, Intent: intent, BargainCount: bargainCount},
db.AIConversationMessage{Role: "assistant", Content: reply, Intent: "reply", BargainCount: bargainCount},
); err != nil {
@@ -148,30 +166,38 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
return &ReplyResult{Text: reply}, nil
}
// conversationContext 负责conversation上下文相关处理。
func (a *AIReplierImpl) conversationContext(ctx context.Context, m ChatMessage) ([]db.AIConversationMessage, int, bool, error) {
// isBargain 保存isBargain,供当前处理流程使用
isBargain := bargainMessageRe.MatchString(strings.ToLower(m.Text))
if m.ChatID == "" || m.ItemID == "" {
return nil, 0, isBargain, nil
}
// history、err 保存history、err,供当前处理流程使用
history, err := a.store.AIReply.ConversationHistory(ctx, a.cookieID, m.ChatID, m.ItemID, 10)
if err != nil {
return nil, 0, isBargain, err
}
// count、err 保存count、err,供当前处理流程使用
count, err := a.store.AIReply.CurrentBargainCount(ctx, a.cookieID, m.ChatID, m.ItemID)
return history, count, isBargain, err
}
// globalAIConfig 保存globalAI配置,供当前处理流程使用
type globalAIConfig struct {
APIKey string
BaseURL string
Model string
}
// globalAIConfig 负责globalAI配置相关处理。
func (a *AIReplierImpl) globalAIConfig(ctx context.Context) (*globalAIConfig, error) {
// apiKey、err 保存apiKey、err,供当前处理流程使用
apiKey, err := a.store.Settings.Get(ctx, "ai_api_key")
if err != nil {
return nil, err
}
// baseURL、err 保存baseURL、err,供当前处理流程使用
baseURL, err := a.store.Settings.Get(ctx, "ai_api_url")
if err != nil {
return nil, err
@@ -182,6 +208,7 @@ func (a *AIReplierImpl) globalAIConfig(ctx context.Context) (*globalAIConfig, er
return nil, err
}
}
// model、err 保存model、err,供当前处理流程使用
model, err := a.store.Settings.Get(ctx, "ai_model")
if err != nil {
return nil, err
@@ -204,6 +231,7 @@ func (a *AIReplierImpl) globalAIConfig(ctx context.Context) (*globalAIConfig, er
// itemInfo 取商品标题/价格/描述。
func (a *AIReplierImpl) itemInfo(ctx context.Context, itemID string) (title string, price float64, desc string) {
// it、err 保存it、err,供当前处理流程使用
it, err := a.store.Items.Get(ctx, a.cookieID, itemID)
if err != nil || it == nil {
return "商品信息获取失败", 0, "暂无商品描述"
@@ -225,7 +253,9 @@ func (a *AIReplierImpl) itemInfo(ctx context.Context, itemID string) (title stri
// buildSystemPrompt 构造 system 提示词。
// 自定义 prompt 只替换业务文案,价格和轮次安全约束始终由后端追加。
// buildSystemPrompt 负责build系统Prompt相关处理。
func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemDesc string, maxDiscountPercent, maxDiscountAmount, maxBargainRounds, bargainCount int) string {
// base 保存base,供当前处理流程使用
var base string
if strings.TrimSpace(customPrompts) != "" {
base = strings.NewReplacer(
@@ -256,10 +286,16 @@ func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemD
- 回复报价必须带“元”,不得给出低于允许最低价的价格。`, itemPrice, maxDiscountPercent, maxDiscountAmount, bargainCount, maxBargainRounds)
}
// priceRe 保存priceRe,供当前处理流程使用
var priceRe = regexp.MustCompile(`[^\d.]`)
// bargainMessageRe 保存bargain消息Re,供当前处理流程使用
var bargainMessageRe = regexp.MustCompile(`(?i)(便宜|优惠|少点|最低|砍价|降价|打折|能不能.*(?:元|块)|\d+(?:\.\d+)?\s*(?:元|块).*(?:卖|行|可以))`)
// offeredPriceRe 保存offeredPriceRe,供当前处理流程使用
var offeredPriceRe = regexp.MustCompile(`(\d+(?:\.\d+)?)\s*(?:元|块)`)
// minimumAllowedPrice 负责minimumAllowedPrice相关处理。
func minimumAllowedPrice(price float64, maxDiscountPercent, maxDiscountAmount int, allowDiscount bool) float64 {
if price <= 0 {
return 0
@@ -267,16 +303,21 @@ func minimumAllowedPrice(price float64, maxDiscountPercent, maxDiscountAmount in
if !allowDiscount || maxDiscountPercent <= 0 || maxDiscountAmount <= 0 {
return price
}
// byPercent 保存byPercent,供当前处理流程使用
byPercent := price * (1 - float64(maxDiscountPercent)/100)
// byAmount 保存byAmount,供当前处理流程使用
byAmount := price - float64(maxDiscountAmount)
return math.Max(0, math.Max(byPercent, byAmount))
}
// unsafeOfferedPrice 负责unsafeOfferedPrice相关处理。
func unsafeOfferedPrice(reply string, minimum float64) (float64, bool) {
if minimum <= 0 {
return 0, false
}
// match 表示当前遍历过程中的match
for _, match := range offeredPriceRe.FindAllStringSubmatch(reply, -1) {
// value、err 保存value、err,供当前处理流程使用
value, err := strconv.ParseFloat(match[1], 64)
if err == nil && value+0.0001 < minimum {
return value, true
@@ -285,8 +326,11 @@ func unsafeOfferedPrice(reply string, minimum float64) (float64, bool) {
return 0, false
}
// truncateAIContent 负责truncateAI内容相关处理。
func truncateAIContent(content string) string {
// maxRunes 保存maxRunes,供当前处理流程使用
const maxRunes = 2000
// runes 保存runes,供当前处理流程使用
runes := []rune(content)
if len(runes) <= maxRunes {
return content
@@ -296,10 +340,12 @@ func truncateAIContent(content string) string {
// parsePrice 移除非数字字符后转换为 float。
func parsePrice(s string) float64 {
// cleaned 保存cleaned,供当前处理流程使用
cleaned := priceRe.ReplaceAllString(s, "")
if cleaned == "" {
return 0
}
// f 保存f,供当前处理流程使用
f, _ := strconv.ParseFloat(cleaned, 64)
return f
}
+59 -4
View File
@@ -14,6 +14,7 @@ import (
// TestBuildSystemPrompt 自定义 prompt 替换变量,且始终追加价格与轮次安全约束。
func TestBuildSystemPrompt(t *testing.T) {
// got 保存got,供当前处理流程使用
got := buildSystemPrompt("你是卖{item_title}的客服,价格{item_price}", "iPhone", 100, "手机", 0, 0, 3, 1)
if !strings.Contains(got, "你是卖iPhone的客服,价格100.00") {
t.Fatalf("自定义 prompt 替换: got %q", got)
@@ -38,17 +39,22 @@ func TestBuildSystemPrompt(t *testing.T) {
}
}
// TestMinimumAllowedPriceAndUnsafeOffer 负责TestMinimumAllowedPriceAndUnsafeOffer相关处理。
func TestMinimumAllowedPriceAndUnsafeOffer(t *testing.T) {
if got := minimumAllowedPrice(100, 10, 20, true); got != 90 {
if // got 保存got,供当前处理流程使用
got := minimumAllowedPrice(100, 10, 20, true); got != 90 {
t.Fatalf("minimum=%v want 90", got)
}
if got := minimumAllowedPrice(100, 0, 20, true); got != 100 {
if // got 保存got,供当前处理流程使用
got := minimumAllowedPrice(100, 0, 20, true); got != 100 {
t.Fatalf("zero percent minimum=%v want 100", got)
}
if _, unsafe := unsafeOfferedPrice("最低可以 89 元", 90); !unsafe {
if // unsafe 保存unsafe,供当前处理流程使用
_, unsafe := unsafeOfferedPrice("最低可以 89 元", 90); !unsafe {
t.Fatal("低于最低价的报价应被拦截")
}
if _, unsafe := unsafeOfferedPrice("最低可以 90 元", 90); unsafe {
if // unsafe 保存unsafe,供当前处理流程使用
_, unsafe := unsafeOfferedPrice("最低可以 90 元", 90); unsafe {
t.Fatal("边界报价应允许")
}
}
@@ -56,13 +62,17 @@ func TestMinimumAllowedPriceAndUnsafeOffer(t *testing.T) {
// newAIStore 构造一个带 admin + cookie 的测试 store,供 AIReplier 使用。
func newAIStore(t *testing.T) (*db.Store, func()) {
t.Helper()
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "ai.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
// s 保存s,供当前处理流程使用
s := db.NewStore(d, db.DialectSQLite)
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.Users.Create(ctx, "admin", "a@e.com", "pw")
// admin 保存admin,供当前处理流程使用
admin, _ := s.Users.GetByUsername(ctx, "admin")
s.Cookies.Save(ctx, "cid", "unb=1; _m_h5_tk=tk;", admin.ID)
return s, func() { d.Close() }
@@ -70,9 +80,12 @@ func newAIStore(t *testing.T) (*db.Store, func()) {
// TestAIReply_DisabledReturnsNil AI 未启用 / 无 APIKey 时应返回 nil,nil(降级到下一级)。
func TestAIReply_DisabledReturnsNil(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// 无配置记录 → 未启用 → nil。
@@ -91,12 +104,16 @@ func TestAIReply_DisabledReturnsNil(t *testing.T) {
// TestAIReply_NoAPIKeyReturnsNil 启用 AI 但全局未配 APIKey → nil(不报错降级)。
func TestAIReply_NoAPIKeyReturnsNil(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// res、err 保存res、err,供当前处理流程使用
res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("无 APIKey 应返回 nil,nil: res=%+v err=%v", res, err)
@@ -105,13 +122,16 @@ func TestAIReply_NoAPIKeyReturnsNil(t *testing.T) {
// mockOpenAIServer 启动一个返回固定 chat completion 响应的 HTTP 服务。
// status=0 表示返回成功响应;其余为 HTTP 状态码(用于失败降级测试)。
// mockOpenAIServer 负责mockOpenAIServer相关处理。
func mockOpenAIServer(t *testing.T, status int, content string) *httptest.Server {
t.Helper()
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if status != 0 {
http.Error(w, "upstream error", status)
return
}
// resp 保存resp,供当前处理流程使用
resp := map[string]any{
"choices": []any{map[string]any{
"message": map[string]any{"role": "assistant", "content": content},
@@ -126,9 +146,12 @@ func mockOpenAIServer(t *testing.T, status int, content string) *httptest.Server
// TestAIReply_HTTPErrorDegrades AI 调用 HTTP 500 → 返回错误(上层降级到默认回复)。
func TestAIReply_HTTPErrorDegrades(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// srv 保存srv,供当前处理流程使用
srv := mockOpenAIServer(t, http.StatusInternalServerError, "")
// 启用 AI + 配 APIKey + 指向 mock 服务。
@@ -136,7 +159,9 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) {
s.Settings.Set(ctx, "ai_api_key", "sk-test")
s.Settings.Set(ctx, "ai_api_url", srv.URL)
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// res、err 保存res、err,供当前处理流程使用
res, err := a.Reply(ctx, chatMsg("还能优惠吗", "item1", "chat1"))
if err == nil {
t.Fatalf("HTTP 500 应返回错误,got res=%+v", res)
@@ -144,6 +169,7 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) {
if res != nil {
t.Fatalf("失败时不应返回结果: %+v", res)
}
// history、historyErr 保存history、historyErr,供当前处理流程使用
history, historyErr := s.AIReply.ConversationHistory(ctx, "cid", "chat1", "item1", 10)
if historyErr != nil || len(history) != 0 {
t.Fatalf("上游失败不应写入半轮历史: history=%+v err=%v", history, historyErr)
@@ -152,9 +178,12 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) {
// TestAIReply_EmptyChoicesReturnsNil 成功响应但无 choices → nil(不报错)。
func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"choices": []any{}})
@@ -164,7 +193,9 @@ func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) {
s.Settings.Set(ctx, "ai_api_key", "sk-test")
s.Settings.Set(ctx, "ai_api_url", srv.URL)
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// res、err 保存res、err,供当前处理流程使用
res, err := a.Reply(ctx, chatMsg("可以便宜一点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("空 choices 应返回 nil,nil: res=%+v err=%v", res, err)
@@ -173,15 +204,20 @@ func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) {
// TestAIReply_SuccessReturnsContent 正常调用返回 AI 文本。
func TestAIReply_SuccessReturnsContent(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// srv 保存srv,供当前处理流程使用
srv := mockOpenAIServer(t, 0, "你好,在的哦")
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", srv.URL)
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// res、err 保存res、err,供当前处理流程使用
res, err := a.Reply(ctx, chatMsg("最低多少钱", "item1", "chat1"))
if err != nil {
t.Fatalf("成功调用不应报错: %v", err)
@@ -191,14 +227,18 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
}
}
// TestAIReply_NonBargainMessageFallsThrough 负责TestAI回复NonBargain消息FallsThrough相关处理。
func TestAIReply_NonBargainMessageFallsThrough(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
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 保存res、err,供当前处理流程使用
res, err := NewAIReplier("cid", s, nil).Reply(ctx, chatMsg("在吗,什么时候发货", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("非砍价消息应交给默认回复: res=%+v err=%v", res, err)
@@ -207,9 +247,12 @@ func TestAIReply_NonBargainMessageFallsThrough(t *testing.T) {
// TestGlobalAIConfig 默认值兜底 + 显式设置覆盖。
func TestGlobalAIConfig(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// 全空 → 默认 BaseURL + Model。
@@ -233,9 +276,12 @@ func TestGlobalAIConfig(t *testing.T) {
// TestAIReplierItemInfo 商品缺失时兜底占位;存在时取真实标题/价格/描述。
func TestAIReplierItemInfo(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// 商品不存在 → 占位。
@@ -252,10 +298,14 @@ func TestAIReplierItemInfo(t *testing.T) {
}
}
// TestAIReplyTracksBargainRoundsAndBlocksUnsafePrice 负责TestAI回复TracksBargainRoundsAndBlocksUnsafePrice相关处理。
func TestAIReplyTracksBargainRoundsAndBlocksUnsafePrice(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newAIStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// srv 保存srv,供当前处理流程使用
srv := mockOpenAIServer(t, 0, "可以,80 元成交")
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings
(cookie_id,ai_enabled,max_discount_percent,max_discount_amount,max_bargain_rounds,custom_prompts)
@@ -265,7 +315,9 @@ func TestAIReplyTracksBargainRoundsAndBlocksUnsafePrice(t *testing.T) {
s.Settings.Set(ctx, "ai_api_key", "sk-test")
s.Settings.Set(ctx, "ai_api_url", srv.URL)
// a 保存a,供当前处理流程使用
a := NewAIReplier("cid", s, nil)
// first、err 保存first、err,供当前处理流程使用
first, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
if err != nil {
t.Fatal(err)
@@ -273,6 +325,7 @@ func TestAIReplyTracksBargainRoundsAndBlocksUnsafePrice(t *testing.T) {
if first == nil || !strings.Contains(first.Text, "90.00 元") {
t.Fatalf("越界报价应替换成安全价格: %+v", first)
}
// second、err 保存second、err,供当前处理流程使用
second, err := a.Reply(ctx, chatMsg("再便宜一点", "item1", "chat1"))
if err != nil {
t.Fatal(err)
@@ -280,10 +333,12 @@ func TestAIReplyTracksBargainRoundsAndBlocksUnsafePrice(t *testing.T) {
if second == nil || !strings.Contains(second.Text, "已经是最低价") {
t.Fatalf("超过最大轮次应拒绝继续降价: %+v", second)
}
// count、err 保存count、err,供当前处理流程使用
count, err := s.AIReply.CurrentBargainCount(ctx, "cid", "chat1", "item1")
if err != nil || count != 2 {
t.Fatalf("bargain count=%d err=%v want 2", count, err)
}
// history、err 保存history、err,供当前处理流程使用
history, err := s.AIReply.ConversationHistory(ctx, "cid", "chat1", "item1", 10)
if err != nil || len(history) != 4 {
t.Fatalf("history len=%d err=%v", len(history), err)
+2
View File
@@ -84,9 +84,11 @@ func (a *Account) runConnectionSession(ctx context.Context, conn WSConn, refresh
}
// connectedDuration 是从运行状态组件读取的连接持续时间快照。
a.runtimeMu.Lock()
// startedAt 保存startedAt,供当前处理流程使用
startedAt := a.connStartedAt
a.conn = nil
a.runtimeMu.Unlock()
// connectedDuration 保存connected时长,供当前处理流程使用
connectedDuration := time.Since(startedAt)
return connectionSessionResult{
ReceiveErr: receiveErr,
+1
View File
@@ -9,6 +9,7 @@ import (
// mu 保护本组件全部字段;持锁时不得执行数据库、网络或通知 I/O。
// refreshMu 串行化完整的凭证刷新事务,允许在锁内执行必要的凭证 I/O,
// 但调用方不得在持有它时再次获取同一锁。
// credentialState 保存credential状态,供当前处理流程使用
type credentialState struct {
// mu 保护 Cookie、Token、设备指纹和刷新诊断字段。
mu sync.Mutex
+67 -12
View File
@@ -9,6 +9,7 @@ import (
// dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做:
// 标记消息接收时间 → 提取消息 ID 去重 → 信号量限并发 → 分类(聊天/系统)→ 防抖投递。
// dispatch 负责dispatch相关处理。
func (a *Account) dispatch(decrypted map[string]any) {
a.messageDispatcher.dispatch(decrypted)
}
@@ -20,51 +21,64 @@ func (a *Account) handleMessage(decrypted map[string]any) {
// markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。
// 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。
// markAndCheckDedup 负责markAndCheckDedup相关处理。
func (a *Account) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool {
return a.messageDispatcher.markAndCheckDedup(decrypted, chat)
}
// cleanupDedupLocked 负责cleanupDedupLocked相关处理。
func (a *Account) cleanupDedupLocked(now time.Time) {
a.messageDispatcher.cleanupDedupLocked(now)
}
// scheduleDebouncedReply 为 chat_id 调度防抖回复:
// 同一 chat_id 连续来消息时取消旧定时器、用最新消息重新计时,1s 后投递最后一条。
// scheduleDebouncedReply 负责scheduleDebounced回复相关处理。
func (a *Account) scheduleDebouncedReply(chat ChatMessage) {
a.messageDispatcher.scheduleDebouncedReply(chat)
}
// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。
// 移植自 _extract_message_id。
// extractMessageID 负责extract消息ID相关处理。
func extractMessageID(decrypted map[string]any) string {
// m1、ok 保存m1、ok,供当前处理流程使用
m1, ok := decrypted["1"].(map[string]any)
if !ok {
return ""
}
// m10、ok 保存m10、ok,供当前处理流程使用
m10, ok := m1["10"].(map[string]any)
if !ok {
return ""
}
// bizTag 是 JSON 字符串:{"sourceId":"...","messageId":"..."}
if biz, _ := m10["bizTag"].(string); biz != "" {
if id := parseMessageIDFromJSON(biz); id != "" {
if // id 保存标识,供当前处理流程使用
id := parseMessageIDFromJSON(biz); id != "" {
return id
}
}
if ext, _ := m10["extJson"].(string); ext != "" {
if id := parseMessageIDFromJSON(ext); id != "" {
if // ext 保存ext,供当前处理流程使用
ext, _ := m10["extJson"].(string); ext != "" {
if // id 保存标识,供当前处理流程使用
id := parseMessageIDFromJSON(ext); id != "" {
return id
}
}
return ""
}
// parseMessageIDFromJSON 负责parse消息IDFromJSON相关处理。
func parseMessageIDFromJSON(s string) string {
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(s), &m); err != nil {
return ""
}
if id, ok := m["messageId"].(string); ok {
if // id、ok 保存id、ok,供当前处理流程使用
id, ok := m["messageId"].(string); ok {
return id
}
return ""
@@ -72,14 +86,17 @@ func parseMessageIDFromJSON(s string) string {
// extractChatMessage 从解密消息中提取聊天消息字段。
func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *ChatMessage {
// m1、ok 保存m1、ok,供当前处理流程使用
m1, ok := decrypted["1"].(map[string]any)
if !ok {
return nil
}
// m10 保存m10,供当前处理流程使用
m10, _ := m1["10"].(map[string]any)
if m10 == nil {
return nil
}
// reminder 保存reminder,供当前处理流程使用
reminder, _ := m10["reminderContent"].(string)
if reminder == "" {
return nil
@@ -87,17 +104,22 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
if isNonUserChatNotice(m1, m10, reminder) {
return nil
}
// chatID 保存聊天ID,供当前处理流程使用
chatID := toString(m1["2"])
// chat_id 形如 "47983389096@goofish",去掉后缀。
if i := strings.Index(chatID, "@"); i >= 0 {
chatID = chatID[:i]
}
// senderUserID 保存sender用户ID,供当前处理流程使用
senderUserID, _ := m10["senderUserId"].(string)
// senderName 保存sender名称,供当前处理流程使用
senderName, _ := m10["senderNick"].(string)
if strings.TrimSpace(senderName) == "" {
senderName, _ = m10["reminderTitle"].(string)
}
// reminderURL 保存reminderURL,供当前处理流程使用
reminderURL, _ := m10["reminderUrl"].(string)
// itemID 保存商品ID,供当前处理流程使用
itemID := extractItemID(reminderURL)
return &ChatMessage{
AccountID: accountID,
@@ -116,6 +138,7 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
// - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功”
// - contentType=26:交易卡片,如“我已拍下,待付款”“我发起了退款申请”
// 付款待发货卡片已经在 handleMessage 前半段进入 automation.Center,这里不能再进入聊天回复链。
// isNonUserChatNotice 负责isNon用户聊天Notice相关处理。
func isNonUserChatNotice(m1, m10 map[string]any, reminder string) bool {
if strings.TrimSuffix(strings.TrimSpace(toString(m10["senderUserId"])), "@goofish") == "1400" {
return true
@@ -123,9 +146,11 @@ func isNonUserChatNotice(m1, m10 map[string]any, reminder string) bool {
if strings.TrimSpace(reminder) == "发来一条新消息" {
return true
}
if sessionType := strings.TrimSpace(toString(m10["sessionType"])); sessionType != "" && sessionType != "1" {
if // sessionType 保存会话类型,供当前处理流程使用
sessionType := strings.TrimSpace(toString(m10["sessionType"])); sessionType != "" && sessionType != "1" {
return true
}
// contentType 保存内容类型,供当前处理流程使用
contentType := messageContentType(m1, m10)
switch contentType {
case "14":
@@ -136,27 +161,36 @@ func isNonUserChatNotice(m1, m10 map[string]any, reminder string) bool {
return false
}
// messageContentType 负责消息内容类型相关处理。
func messageContentType(m1, m10 map[string]any) string {
if ext, _ := m10["extJson"].(string); ext != "" {
if // ext 保存ext,供当前处理流程使用
ext, _ := m10["extJson"].(string); ext != "" {
// extJSON 保存extJSON,供当前处理流程使用
var extJSON map[string]any
if json.Unmarshal([]byte(ext), &extJSON) == nil {
if v := toString(extJSON["contentType"]); v != "" {
if // v 保存v,供当前处理流程使用
v := toString(extJSON["contentType"]); v != "" {
return v
}
}
}
// m6 保存m6,供当前处理流程使用
m6, _ := m1["6"].(map[string]any)
if m6 == nil {
return ""
}
// m63 保存m63,供当前处理流程使用
m63, _ := m6["3"].(map[string]any)
if m63 == nil {
return ""
}
if v := toString(m63["4"]); v != "" {
if // v 保存v,供当前处理流程使用
v := toString(m63["4"]); v != "" {
return v
}
if contentJSON, _ := m63["5"].(string); contentJSON != "" {
if // contentJSON 保存内容JSON,供当前处理流程使用
contentJSON, _ := m63["5"].(string); contentJSON != "" {
// content 保存内容,供当前处理流程使用
var content map[string]any
if json.Unmarshal([]byte(contentJSON), &content) == nil {
return toString(content["contentType"])
@@ -167,18 +201,23 @@ func messageContentType(m1, m10 map[string]any) string {
// extractItemID 从 reminderUrl 中正则提取 itemId=xxx。
func extractItemID(url string) string {
// key 保存key,供当前处理流程使用
const key = "itemId="
// i 保存i,供当前处理流程使用
i := strings.Index(url, key)
if i < 0 {
return ""
}
// s 保存s,供当前处理流程使用
s := url[i+len(key):]
if j := strings.IndexAny(s, "&\n\r"); j >= 0 {
if // j 保存j,供当前处理流程使用
j := strings.IndexAny(s, "&\n\r"); j >= 0 {
s = s[:j]
}
return s
}
// currentCookieStr 负责current登录凭证Str相关处理。
func (a *Account) currentCookieStr() string {
a.mu.Lock()
defer a.mu.Unlock()
@@ -192,10 +231,13 @@ func (a *Account) CurrentCookieStr() string {
// ---- 小工具 ----
// contains 负责contains相关处理。
func contains(s, sub string) bool { return strings.Contains(strings.ToLower(s), strings.ToLower(sub)) }
// toString 负责toString相关处理。
func toString(v any) string {
switch x := v.(type) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case nil:
return ""
case string:
@@ -204,11 +246,13 @@ func toString(v any) string {
// JSON 数字 → 整数字符串。
return trimFloatInt(x)
default:
// b 保存b,供当前处理流程使用
b, _ := json.Marshal(v)
return string(b)
}
}
// trimFloatInt 负责trimFloatInt相关处理。
func trimFloatInt(f float64) string {
if f == float64(int64(f)) {
return int64ToString(int64(f))
@@ -216,15 +260,19 @@ func trimFloatInt(f float64) string {
return ftoa(f)
}
// int64ToString 负责int64ToString相关处理。
func int64ToString(n int64) string {
if n == 0 {
return "0"
}
// neg 保存neg,供当前处理流程使用
neg := n < 0
if neg {
n = -n
}
// b 保存b,供当前处理流程使用
var b [20]byte
// i 保存i,供当前处理流程使用
i := len(b)
for n > 0 {
i--
@@ -238,13 +286,17 @@ func int64ToString(n int64) string {
return string(b[i:])
}
// ftoa 负责ftoa相关处理。
func ftoa(f float64) string { return jsonNumber(f) }
// jsonNumber 负责jsonNumber相关处理。
func jsonNumber(f float64) string {
// b 保存b,供当前处理流程使用
b, _ := json.Marshal(f)
return string(b)
}
// truncID 负责truncID相关处理。
func truncID(id string) string {
if len(id) > 50 {
return id[:50] + "..."
@@ -252,6 +304,7 @@ func truncID(id string) string {
return id
}
// errString 负责errString相关处理。
func errString(err error) string {
if err == nil {
return ""
@@ -259,10 +312,12 @@ func errString(err error) string {
return err.Error()
}
// sleepCtx 负责sleepCtx相关处理。
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
// t 保存t,供当前处理流程使用
t := time.NewTimer(d)
defer t.Stop()
select {
+74 -7
View File
@@ -12,10 +12,12 @@ import (
// TestHandleMessage_SystemEventRoutesToAutomation 付款待发货系统卡片进入自动化中心,不进入回复链。
func TestHandleMessage_SystemEventRoutesToAutomation(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// decrypted 保存decrypted,供当前处理流程使用
decrypted := mustPaidDeliveryCard(t)
acc.handleMessage(decrypted)
@@ -24,6 +26,7 @@ func TestHandleMessage_SystemEventRoutesToAutomation(t *testing.T) {
// 直接验证:handleMessage 不应触发任何防抖回复投递。
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
h.mu.Lock()
// chats 保存chats,供当前处理流程使用
chats := len(h.chats)
h.mu.Unlock()
if chats != 0 {
@@ -38,6 +41,7 @@ type systemCapturingHandler struct {
tasks []automation.Task
}
// HandleSystemEvent 处理系统Event。
func (s *systemCapturingHandler) HandleSystemEvent(_ context.Context, task automation.Task) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -47,10 +51,12 @@ func (s *systemCapturingHandler) HandleSystemEvent(_ context.Context, task autom
// TestHandleMessage_SystemEventDispatchedToHandler 系统卡片经 handleMessage 进入 handler.HandleSystemEvent。
func TestHandleMessage_SystemEventDispatchedToHandler(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// h 保存h,供当前处理流程使用
h := &systemCapturingHandler{}
acc.handler = h
acc.handleMessage(mustPaidDeliveryCard(t))
@@ -67,6 +73,7 @@ func TestHandleMessage_SystemEventDispatchedToHandler(t *testing.T) {
// TestHandleMessage_PlainChatRoutesToDebounce 普通聊天消息进入防抖回复链。
func TestHandleMessage_PlainChatRoutesToDebounce(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -88,6 +95,7 @@ func TestHandleMessage_PlainChatRoutesToDebounce(t *testing.T) {
// TestHandleMessage_ContentType14Filtered contentType=14 系统提示不进入回复链。
func TestHandleMessage_ContentType14Filtered(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -103,6 +111,7 @@ func TestHandleMessage_ContentType14Filtered(t *testing.T) {
// TestHandleMessage_RefundCardFiltered contentType=26 退款卡片不进入回复链。
func TestHandleMessage_RefundCardFiltered(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -118,10 +127,12 @@ func TestHandleMessage_RefundCardFiltered(t *testing.T) {
// TestHandleMessage_DedupSkipsRepeat 同一 msgID 的重复消息只处理一次。
func TestHandleMessage_DedupSkipsRepeat(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// decrypted 保存decrypted,供当前处理流程使用
decrypted := plainChatMessage(t, "重复消息", "buyer1", "chat-dup")
acc.handleMessage(decrypted)
acc.handleMessage(decrypted) // 重复
@@ -137,6 +148,7 @@ func TestHandleMessage_DedupSkipsRepeat(t *testing.T) {
// TestHandleMessage_NoReminderNoOp 无 reminderContent 的消息不进入回复链也不报错。
func TestHandleMessage_NoReminderNoOp(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -161,6 +173,7 @@ func TestHandleMessage_NoReminderNoOp(t *testing.T) {
// TestDispatch_UpdatesLastMsgReceived dispatch 记录消息接收时间。
func TestDispatch_UpdatesLastMsgReceived(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -169,12 +182,14 @@ func TestDispatch_UpdatesLastMsgReceived(t *testing.T) {
acc.lastMsgReceived = time.Time{}
acc.mu.Unlock()
// before 保存before,供当前处理流程使用
before := time.Now()
acc.dispatch(plainChatMessage(t, "hi", "b1", "c1"))
// dispatch 内部起 goroutine,等其更新 lastMsgReceived。
time.Sleep(50 * time.Millisecond)
acc.mu.Lock()
// last 保存last,供当前处理流程使用
last := acc.lastMsgReceived
acc.mu.Unlock()
if last.IsZero() || last.Before(before) {
@@ -184,6 +199,7 @@ func TestDispatch_UpdatesLastMsgReceived(t *testing.T) {
// TestDispatch_SemaphoreOverflowDrops 消息并发达上限时丢弃多余消息(不阻塞)。
func TestDispatch_SemaphoreOverflowDrops(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -210,16 +226,22 @@ func TestDispatch_SemaphoreOverflowDrops(t *testing.T) {
}
}
// TestDispatch_SystemEventWaitsForCapacityInsteadOfDropping 负责TestDispatch系统EventWaitsForCapacityInsteadOfDropping相关处理。
func TestDispatch_SystemEventWaitsForCapacityInsteadOfDropping(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// h 保存h,供当前处理流程使用
h := &systemCapturingHandler{}
acc.handler = h
for i := 0; i < MessageSemaphoreSize; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < MessageSemaphoreSize; i++ {
acc.sem <- struct{}{}
}
// event 保存event,供当前处理流程使用
event := mustPaidDeliveryCard(t)
// done 保存done,供当前处理流程使用
done := make(chan struct{})
go func() {
acc.dispatch(event)
@@ -236,9 +258,11 @@ func TestDispatch_SystemEventWaitsForCapacityInsteadOfDropping(t *testing.T) {
case <-time.After(time.Second):
t.Fatal("system event did not continue after capacity became available")
}
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
h.mu.Lock()
// count 保存数量,供当前处理流程使用
count := len(h.tasks)
h.mu.Unlock()
if count == 1 {
@@ -247,6 +271,7 @@ func TestDispatch_SystemEventWaitsForCapacityInsteadOfDropping(t *testing.T) {
time.Sleep(10 * time.Millisecond)
}
h.mu.Lock()
// count 保存数量,供当前处理流程使用
count := len(h.tasks)
h.mu.Unlock()
if count != 1 {
@@ -259,11 +284,14 @@ func TestDispatch_SystemEventWaitsForCapacityInsteadOfDropping(t *testing.T) {
// TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced 不同 chat_id 的消息各自独立防抖,不合并。
func TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// chat1 保存chat1,供当前处理流程使用
chat1 := ChatMessage{AccountID: "cid", ChatID: "chat-a", Text: "A1", SenderUserID: "b1"}
// chat2 保存chat2,供当前处理流程使用
chat2 := ChatMessage{AccountID: "cid", ChatID: "chat-b", Text: "B1", SenderUserID: "b2"}
chat1.CookieStr = "cookie"
chat2.CookieStr = "cookie"
@@ -277,7 +305,9 @@ func TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced(t *testing.T) {
if len(h.chats) != 2 {
t.Fatalf("不同 chat_id 应各自投递,got %d 条: %+v", len(h.chats), h.chats)
}
// texts 保存texts,供当前处理流程使用
texts := map[string]bool{}
// c 表示当前遍历过程中的c
for _, c := range h.chats {
texts[c.Text] = true
}
@@ -288,6 +318,7 @@ func TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced(t *testing.T) {
// TestScheduleDebouncedReply_TimerReset 同一 chat_id 连续消息重置定时器,旧消息被跳过。
func TestScheduleDebouncedReply_TimerReset(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -299,6 +330,7 @@ func TestScheduleDebouncedReply_TimerReset(t *testing.T) {
// 在防抖延迟内再投递第二条,应取消第一条的定时器。
time.Sleep(MessageDebounceDelay / 2)
// second 保存second,供当前处理流程使用
second := ChatMessage{AccountID: "cid", ChatID: "chat-reset", Text: "second", SenderUserID: "b1"}
second.CookieStr = "cookie"
acc.scheduleDebouncedReply(second)
@@ -316,9 +348,11 @@ func TestScheduleDebouncedReply_TimerReset(t *testing.T) {
// TestScheduleDebouncedReply_StopClearsTimers Stop 后未触发的定时器被取消,不再投递。
func TestScheduleDebouncedReply_StopClearsTimers(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
// chat 保存聊天,供当前处理流程使用
chat := ChatMessage{AccountID: "cid", ChatID: "chat-stop", Text: "won't deliver", SenderUserID: "b1"}
chat.CookieStr = "cookie"
acc.scheduleDebouncedReply(chat)
@@ -333,11 +367,13 @@ func TestScheduleDebouncedReply_StopClearsTimers(t *testing.T) {
}
}
// cancelAwareHandler 保存取消AwareHandler,供当前处理流程使用
type cancelAwareHandler struct {
started chan struct{}
canceled chan struct{}
}
// HandleChatMessage 处理聊天消息。
func (h *cancelAwareHandler) HandleChatMessage(ctx context.Context, _ ChatMessage) error {
close(h.started)
<-ctx.Done()
@@ -345,14 +381,23 @@ func (h *cancelAwareHandler) HandleChatMessage(ctx context.Context, _ ChatMessag
return ctx.Err()
}
func (h *cancelAwareHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
func (h *cancelAwareHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// HandleSystemEvent 处理系统Event。
func (h *cancelAwareHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
func (h *cancelAwareHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// OnAccountAlert 负责On账号Alert相关处理。
func (h *cancelAwareHandler) OnAccountAlert(context.Context, string, string, string, string) {}
// TestStopCancelsInFlightReplyHandler 负责TestStopCancelsInFlight回复Handler相关处理。
func TestStopCancelsInFlightReplyHandler(t *testing.T) {
// handler 保存handler,供当前处理流程使用
handler := &cancelAwareHandler{started: make(chan struct{}), canceled: make(chan struct{})}
// acc 保存acc,供当前处理流程使用
acc := New(Config{CookieID: "cid", CookieStr: "unb=1", Handler: handler})
acc.reply = nil
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
acc.lifecycle.start(ctx, cancel)
@@ -362,6 +407,7 @@ func TestStopCancelsInFlightReplyHandler(t *testing.T) {
case <-time.After(MessageDebounceDelay + time.Second):
t.Fatal("handler did not start")
}
// done 保存done,供当前处理流程使用
done := make(chan struct{})
go func() {
acc.Stop()
@@ -381,10 +427,12 @@ func TestStopCancelsInFlightReplyHandler(t *testing.T) {
// TestCleanupDedupLocked_ExpiredRemoved 过期消息 ID 被清理。
func TestCleanupDedupLocked_ExpiredRemoved(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// now 保存now,供当前处理流程使用
now := time.Now()
acc.dedupMu.Lock()
// 一条过期(>1h)、一条新鲜。
@@ -398,29 +446,35 @@ func TestCleanupDedupLocked_ExpiredRemoved(t *testing.T) {
acc.dedupMu.Lock()
defer acc.dedupMu.Unlock()
if _, ok := acc.processed["old-msg"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := acc.processed["old-msg"]; ok {
t.Error("过期消息应被清理")
}
if _, ok := acc.processed["fresh-msg"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := acc.processed["fresh-msg"]; !ok {
t.Error("新鲜消息不应被清理")
}
}
// TestCleanupDedupLocked_OverLimitDropsOldestHalf 超上限且都未过期时删最旧一半。
func TestCleanupDedupLocked_OverLimitDropsOldestHalf(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// now 保存now,供当前处理流程使用
now := time.Now()
acc.dedupMu.Lock()
// 填入 ProcessedIDsMaxSize + 10 条新鲜消息,时间递增。
total := ProcessedIDsMaxSize + 10
for i := 0; i < total; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < total; i++ {
// 时间按 i 递增,确保有明确的最旧一半。
acc.processed["msg-"+itoa(i)] = now.Add(time.Duration(i) * time.Millisecond)
}
acc.cleanupDedupLocked(now)
// remaining 保存remaining,供当前处理流程使用
remaining := len(acc.processed)
acc.dedupMu.Unlock()
@@ -436,11 +490,14 @@ func itoa(n int) string {
if n == 0 {
return "0"
}
// neg 保存neg,供当前处理流程使用
neg := n < 0
if neg {
n = -n
}
// b 保存b,供当前处理流程使用
var b [20]byte
// i 保存i,供当前处理流程使用
i := len(b)
for n > 0 {
i--
@@ -456,10 +513,12 @@ func itoa(n int) string {
// TestCleanupDedupLocked_TriggeredByMarkAndCheck markAndCheckDedup 在超上限时触发清理。
func TestCleanupDedupLocked_TriggeredByMarkAndCheck(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// now 保存now,供当前处理流程使用
now := time.Now()
acc.dedupMu.Lock()
// 预填 ProcessedIDsMaxSize 条过期消息,使下一次 markAndCheckDedup 触发清理。
@@ -470,12 +529,14 @@ func TestCleanupDedupLocked_TriggeredByMarkAndCheck(t *testing.T) {
// 构造一条新消息触发清理。msgID 由 extractMessageID 提取,这里直接用现成样本。
decrypted := plainChatMessage(t, "trigger", "b1", "c1")
// chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "cid", "cookie")
if !acc.markAndCheckDedup(decrypted, chat) {
t.Fatal("新消息应允许处理")
}
acc.dedupMu.Lock()
// remaining 保存remaining,供当前处理流程使用
remaining := len(acc.processed)
acc.dedupMu.Unlock()
// 过期消息应被清理,仅剩新消息 1 条(或新消息+残留,但应远小于 ProcessedIDsMaxSize)。
@@ -486,6 +547,7 @@ func TestCleanupDedupLocked_TriggeredByMarkAndCheck(t *testing.T) {
// TestScheduleDebouncedReply_HandlerErrorLogged reply.Handle 报错仅记录日志,不影响 handler 投递。
func TestScheduleDebouncedReply_HandlerErrorLogged(t *testing.T) {
// acc、h、store、cleanup 保存acc、h、store、cleanup,供当前处理流程使用
acc, h, store, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -493,6 +555,7 @@ func TestScheduleDebouncedReply_HandlerErrorLogged(t *testing.T) {
// 让 reply.Handle 走默认回复路径并成功发送(sender 是 acc 自身,无 conn 会失败但仅记录日志)。
// 这里主要验证防抖回调路径在 reply 报错时仍会调用 handler.HandleChatMessage。
_ = store
// chat 保存聊天,供当前处理流程使用
chat := ChatMessage{
AccountID: "cid", ChatID: "chat-err", Text: "hi",
SenderUserID: "b1", CookieStr: "unb=123;",
@@ -508,11 +571,15 @@ func TestScheduleDebouncedReply_HandlerErrorLogged(t *testing.T) {
// plainChatMessage 构造一条普通聊天消息(非系统卡片、contentType 非 14/26),
// 含 bizTag.messageId 以便去重提取。
// plainChatMessage 负责plain聊天消息相关处理。
func plainChatMessage(t *testing.T, text, senderUserID, chatID string) map[string]any {
t.Helper()
// s 保存s,供当前处理流程使用
s := `{"1":{"2":"` + chatID + `@goofish","10":{"bizTag":"{\"messageId\":\"msg-` + chatID + `\"}","reminderContent":"` + text + `","senderUserId":"` + senderUserID + `","senderNick":"买家","reminderUrl":"fleamarket://message_chat?itemId=item-` + chatID + `&peerUserId=` + senderUserID + `"}}}`
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
+70 -8
View File
@@ -20,40 +20,54 @@ type recordingHandler struct {
refresh int
}
// HandleChatMessage 处理聊天消息。
func (h *recordingHandler) HandleChatMessage(_ context.Context, m ChatMessage) error {
h.mu.Lock()
defer h.mu.Unlock()
h.chats = append(h.chats, m)
return nil
}
// HandleSystemEvent 处理系统Event。
func (h *recordingHandler) HandleSystemEvent(_ context.Context, task automation.Task) error {
h.mu.Lock()
defer h.mu.Unlock()
_ = task
return nil
}
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
func (h *recordingHandler) OnPasswordLoginRefresh(_ context.Context, _ string) bool {
h.mu.Lock()
defer h.mu.Unlock()
h.refresh++
return true
}
// OnAccountAlert 负责On账号Alert相关处理。
func (h *recordingHandler) OnAccountAlert(_ context.Context, _, _, _, _ string) {}
// newAccountForTest 负责new账号ForTest相关处理。
func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
// store 保存store,供当前处理流程使用
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
store.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
store.Cookies.SetStatus(context.Background(), "cid", true)
// h 保存h,供当前处理流程使用
h := &recordingHandler{}
// acc 保存acc,供当前处理流程使用
acc := New(Config{
CookieID: "cid",
CookieStr: "unb=123; _m_h5_tk=tk_1;",
@@ -68,7 +82,9 @@ func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, fu
// TestExtractChatMessage_RealSample 用真实抓包样本验证消息字段提取。
func TestExtractChatMessage_RealSample(t *testing.T) {
// decrypted 保存decrypted,供当前处理流程使用
decrypted := mustDecryptGoldenSample(t)
// chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "cid", "cookie")
if chat == nil {
t.Fatal("应为聊天消息")
@@ -84,36 +100,49 @@ func TestExtractChatMessage_RealSample(t *testing.T) {
}
}
// TestExtractChatMessage_FiltersContentType14Notice 负责TestExtract聊天消息Filters内容Type14Notice相关处理。
func TestExtractChatMessage_FiltersContentType14Notice(t *testing.T) {
// decrypted 保存decrypted,供当前处理流程使用
decrypted := mustContentType14Notice(t)
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
if // chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
t.Fatalf("contentType=14 系统提示不应进入聊天回复: %+v", chat)
}
}
// TestExtractChatMessageUsesReminderTitleAsNickname 负责TestExtract聊天消息UsesReminder标题AsNickname相关处理。
func TestExtractChatMessageUsesReminderTitleAsNickname(t *testing.T) {
// decrypted 保存decrypted,供当前处理流程使用
decrypted := map[string]any{"1": map[string]any{
"2": "chat-1@goofish",
"10": map[string]any{"reminderContent": "你好", "reminderTitle": "真实昵称", "senderUserId": "buyer-1", "sessionType": "1"},
}}
// chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "account-1", "cookie")
if chat == nil || chat.SenderName != "真实昵称" {
t.Fatalf("chat=%+v", chat)
}
}
// TestExtractChatMessage_FiltersRefundTradeCard 负责TestExtract聊天消息FiltersRefundTrade卡密相关处理。
func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) {
// decrypted 保存decrypted,供当前处理流程使用
decrypted := mustRefundTradeCard(t)
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
if // chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
t.Fatalf("退款交易卡片不应进入聊天回复: %+v", chat)
}
}
// TestExtractChatMessage_FiltersPaidDeliveryCardFromChat 负责TestExtract聊天消息FiltersPaid发货卡密From聊天相关处理。
func TestExtractChatMessage_FiltersPaidDeliveryCardFromChat(t *testing.T) {
// decrypted 保存decrypted,供当前处理流程使用
decrypted := mustPaidDeliveryCard(t)
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
if // chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
t.Fatalf("付款待发货系统卡片不应进入聊天回复链: %+v", chat)
}
// task 保存任务,供当前处理流程使用
task := automation.ExtractTaskFromWS("cid", "cookie", decrypted)
if task == nil || task.TriggerType != automation.TriggerOrderPaid {
t.Fatalf("付款待发货卡片应进入自动化中心: %+v", task)
@@ -122,11 +151,14 @@ func TestExtractChatMessage_FiltersPaidDeliveryCardFromChat(t *testing.T) {
// TestDedup_SkipsDuplicateWithinExpiry 同一消息 ID 1 小时内只处理一次。
func TestDedup_SkipsDuplicateWithinExpiry(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// decrypted 保存decrypted,供当前处理流程使用
decrypted := mustDecryptGoldenSample(t)
// chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "cid", "cookie")
// 首次:标记并应继续。
@@ -146,17 +178,22 @@ func TestDedup_SkipsDuplicateWithinExpiry(t *testing.T) {
// TestDebounce_CoalescesRapidMessages 连续消息只投递最后一条。
func TestDebounce_CoalescesRapidMessages(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
// decrypted 保存decrypted,供当前处理流程使用
decrypted := mustDecryptGoldenSample(t)
// chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, "cid", "cookie")
// 修改文本模拟连续多条。
chat1 := *chat
chat1.Text = "第一条"
// chat2 保存chat2,供当前处理流程使用
chat2 := *chat
chat2.Text = "第二条"
// chat3 保存chat3,供当前处理流程使用
chat3 := *chat
chat3.Text = "第三条"
@@ -180,13 +217,16 @@ func TestDebounce_CoalescesRapidMessages(t *testing.T) {
// TestExtractItemID reminderUrl 中提取 itemId。
func TestExtractItemID(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063": "900052644277",
"noitemid": "",
"fleamarket://x?itemId=ABC123": "ABC123",
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := extractItemID(in); got != want {
if // got 保存got,供当前处理流程使用
got := extractItemID(in); got != want {
t.Errorf("extractItemID(%q)=%q want %q", in, got, want)
}
}
@@ -194,11 +234,13 @@ func TestExtractItemID(t *testing.T) {
// mustDecryptGoldenSample 复用 protocol 包的真实样本:直接硬编码一条最小解密结构,
// 避免循环依赖。这里构造一个等价的最小消息用于字段提取测试。
// mustDecryptGoldenSample 负责mustDecryptGoldenSample相关处理。
func mustDecryptGoldenSample(t *testing.T) map[string]any {
t.Helper()
// 真实样本关键字段(来自 protocol golden test 解密输出):
// message["1"]["2"]="47983389009@goofish", ["1"]["10"]["reminderContent"]="[我已拍下,待付款]",
// ["1"]["10"]["reminderUrl"] 含 itemId=900052644277
// s 保存s,供当前处理流程使用
s := `{
"1": {
"2": "47983389009@goofish",
@@ -214,15 +256,19 @@ func mustDecryptGoldenSample(t *testing.T) map[string]any {
"userId": "3149637063"
}
}`
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
}
// mustContentType14Notice 负责must内容Type14Notice相关处理。
func mustContentType14Notice(t *testing.T) map[string]any {
t.Helper()
// s 保存s,供当前处理流程使用
s := "{" +
"\"1\":{" +
"\"2\":\"63107041124@goofish\"," +
@@ -235,15 +281,19 @@ func mustContentType14Notice(t *testing.T) map[string]any {
"\"6\":{\"3\":{\"4\":14,\"5\":\"{\\\"contentType\\\":14,\\\"tip\\\":{\\\"argInfo\\\":{\\\"arg1\\\":\\\"NoBargainGuide\\\"}}}\"}}" +
"}" +
"}"
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
}
// mustRefundTradeCard 负责mustRefundTrade卡密相关处理。
func mustRefundTradeCard(t *testing.T) map[string]any {
t.Helper()
// s 保存s,供当前处理流程使用
s := "{" +
"\"1\":{" +
"\"2\":\"63107041124@goofish\"," +
@@ -258,15 +308,19 @@ func mustRefundTradeCard(t *testing.T) map[string]any {
"\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" +
"}" +
"}"
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
}
// mustPaidDeliveryCard 负责mustPaid发货卡密相关处理。
func mustPaidDeliveryCard(t *testing.T) map[string]any {
t.Helper()
// s 保存s,供当前处理流程使用
s := "{" +
"\"1\":{" +
"\"2\":\"63107041124@goofish\"," +
@@ -281,8 +335,10 @@ func mustPaidDeliveryCard(t *testing.T) map[string]any {
"\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" +
"}" +
"}"
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
@@ -290,6 +346,7 @@ func mustPaidDeliveryCard(t *testing.T) map[string]any {
// TestRetryDelay 复刻 _calculate_retry_delay 的分段逻辑。
func TestRetryDelay(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -306,19 +363,24 @@ func TestRetryDelay(t *testing.T) {
expectDelayRange(t, acc.retryDelay("some other error"), 2*time.Second)
}
// expectDelayRange 负责expect延迟Range相关处理。
func expectDelayRange(t *testing.T, got, base time.Duration) {
t.Helper()
// max 保存max,供当前处理流程使用
max := base + base*3/10
if got < base || got > max {
t.Fatalf("retryDelay=%v want in [%v,%v]", got, base, max)
}
}
// TestRuntimeStatusClassifiesAuthenticationFailures 负责TestRuntime状态ClassifiesAuthenticationFailures相关处理。
func TestRuntimeStatusClassifiesAuthenticationFailures(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
acc.setRuntimeError(context.Background(), fmt.Errorf("token API 登录凭证已失效: FAIL_SYS_TOKEN_EXOIRED"))
// status 保存状态,供当前处理流程使用
status := acc.RuntimeStatus()
if status.State != RuntimeAuthExpired || status.Connected {
t.Fatalf("status=%+v", status)
+1
View File
@@ -5,6 +5,7 @@ import (
"time"
)
// init 负责init相关处理。
func init() {
// AI 单测通过 httptest 模拟兼容端点;生产构造器仍使用 netguard。
newAIHTTPClient = func(string) (*http.Client, error) {
+88 -18
View File
@@ -18,102 +18,126 @@ type countingMtop struct {
calls int32
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (c *countingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
atomic.AddInt32(&c.calls, 1)
return &mtop.RefreshResult{AccessToken: c.token, AccessTokenExpireAt: time.Now().Add(time.Hour).Unix()}, nil
}
// statusMtop 保存状态Mtop,供当前处理流程使用
type statusMtop struct {
fakeRunMtop
result *mtop.LoginStatusResult
err error
}
// failingCountingMtop 保存failingCountingMtop,供当前处理流程使用
type failingCountingMtop struct {
fakeRunMtop
calls int32
err error
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (c *failingCountingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
atomic.AddInt32(&c.calls, 1)
return nil, c.err
}
// saveBoundToken 负责saveBound令牌相关处理。
func saveBoundToken(t *testing.T, store *db.Store, acc *Account, token string, expireAt int64) {
t.Helper()
if err := store.Tokens.SaveBound(context.Background(), acc.CookieID, acc.deviceID, token, expireAt,
if // err 保存err,供当前处理流程使用
err := store.Tokens.SaveBound(context.Background(), acc.CookieID, acc.deviceID, token, expireAt,
credentialCookieFingerprint(acc.currentCookieStr())); err != nil {
t.Fatal(err)
}
}
// TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache 负责TestRefresh令牌NetworkFailureClearsMemoryButPreservesFreshCache相关处理。
func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("network connection reset"),
}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
if _, _, err := acc.refreshToken(context.Background()); err == nil {
if // err 保存err,供当前处理流程使用
_, _, err := acc.refreshToken(context.Background()); err == nil {
t.Fatal("网络失败应返回错误")
}
acc.mu.Lock()
// current 保存current,供当前处理流程使用
current := acc.currentToken
acc.mu.Unlock()
if current != "" {
t.Fatalf("刷新网络失败后应清空内存 token: %q", current)
}
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "cached-tok" {
if // cached、err 保存cached、err,供当前处理流程使用
cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "cached-tok" {
t.Fatalf("网络失败应保留未过期数据库缓存: cached=%+v err=%v", cached, err)
}
}
// TestRefreshTokenBusinessFailureClearsMemoryAndCache 负责TestRefresh令牌BusinessFailureClearsMemoryAndCache相关处理。
func TestRefreshTokenBusinessFailureClearsMemoryAndCache(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("token API business rejected"),
}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
if _, _, err := acc.refreshToken(context.Background()); err == nil {
if // err 保存err,供当前处理流程使用
_, _, err := acc.refreshToken(context.Background()); err == nil {
t.Fatal("业务失败应返回错误")
}
acc.mu.Lock()
// current 保存current,供当前处理流程使用
current := acc.currentToken
acc.mu.Unlock()
if current != "" {
t.Fatalf("业务失败后应清空内存 token: %q", current)
}
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
if // tk、err 保存tk、err,供当前处理流程使用
tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("业务失败应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
// TestAcquireTokenDeletesExpiredCacheBeforeNetworkAttempt 负责TestAcquire令牌DeletesExpiredCacheBeforeNetwork尝试次数相关处理。
func TestAcquireTokenDeletesExpiredCacheBeforeNetworkAttempt(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("network connection reset"),
}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
saveBoundToken(t, store, acc, "expired-tok", time.Now().Add(-time.Minute).Unix())
if _, _, err := acc.acquireToken(context.Background()); err == nil {
if // err 保存err,供当前处理流程使用
_, _, err := acc.acquireToken(context.Background()); err == nil {
t.Fatal("后续网络请求失败应返回错误")
}
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
if // tk、err 保存tk、err,供当前处理流程使用
tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("过期 token 应清空且 device ID 保留: tk=%+v err=%v", tk, err)
}
}
// CheckLoginStatusContext 检查登录状态上下文。
func (s *statusMtop) CheckLoginStatusContext(context.Context, string) (*mtop.LoginStatusResult, error) {
return s.result, s.err
}
@@ -121,12 +145,16 @@ func (s *statusMtop) CheckLoginStatusContext(context.Context, string) (*mtop.Log
// TestAcquireToken_CacheHitStillFetchesFreshToken matches the official web
// client: every connection attempt calls login.token even when a persisted
// token has not reached its advertised expiry.
// TestAcquireToken_CacheHitStillFetchesFreshToken 负责TestAcquire令牌CacheHitStillFetchesFresh令牌相关处理。
func TestAcquireToken_CacheHitStillFetchesFreshToken(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
// token、cookies、err 保存token、cookies、err,供当前处理流程使用
token, cookies, err := acc.acquireToken(context.Background())
if err != nil {
t.Fatalf("acquireToken: %v", err)
@@ -134,7 +162,8 @@ func TestAcquireToken_CacheHitStillFetchesFreshToken(t *testing.T) {
if token != "tok-mtop" {
t.Fatalf("应使用新获取 token,got %s", token)
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
if // calls 保存calls,供当前处理流程使用
calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("每次连接都应调用 mtop,got %d", calls)
}
if !strings.Contains(cookies, "_m_h5_tk=tk_1") {
@@ -142,17 +171,23 @@ func TestAcquireToken_CacheHitStillFetchesFreshToken(t *testing.T) {
}
}
// TestAcquireToken_RejectsCacheBoundToDifferentCookie 负责TestAcquire令牌RejectsCacheBoundToDifferent登录凭证相关处理。
func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
saveBoundToken(t, store, acc, "stale-token", time.Now().Add(time.Hour).Unix())
// newCookie 保存new登录凭证,供当前处理流程使用
newCookie := "unb=123; _m_h5_tk=renewed_2; cookie2=new"
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil {
t.Fatal(err)
}
acc.replaceCookieStr(newCookie)
// token、err 保存token、err,供当前处理流程使用
token, _, err := acc.acquireToken(context.Background())
if err != nil {
t.Fatal(err)
@@ -162,28 +197,36 @@ func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) {
}
}
// TestAcquireRuntimeTokenReplacesMemoryToken 负责TestAcquireRuntime令牌ReplacesMemory令牌相关处理。
func TestAcquireRuntimeTokenReplacesMemoryToken(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
acc.currentToken = "runtime-token"
_ = store.Tokens.Clear(context.Background(), "cid")
// token、err 保存token、err,供当前处理流程使用
token, _, err := acc.acquireRuntimeToken(context.Background())
if err != nil || token != "tok-mtop" {
t.Fatalf("runtime token=%q err=%v", token, err)
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
if // calls 保存calls,供当前处理流程使用
calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("网络重连应获取新 token,calls=%d", calls)
}
}
// TestAcquireToken_CacheMissCallsMtopAndSavesCache 缓存未命中时调 mtop 并把结果落库。
func TestAcquireToken_CacheMissCallsMtopAndSavesCache(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
// token、err 保存token、err,供当前处理流程使用
token, _, err := acc.acquireToken(context.Background())
if err != nil {
t.Fatalf("acquireToken: %v", err)
@@ -191,9 +234,11 @@ func TestAcquireToken_CacheMissCallsMtopAndSavesCache(t *testing.T) {
if token != "tok-mtop" {
t.Fatalf("应使用 mtop token,got %s", token)
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
if // calls 保存calls,供当前处理流程使用
calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("缓存未命中应调一次 mtop,got %d", calls)
}
// tk、err 保存tk、err,供当前处理流程使用
tk, err := store.Tokens.Get(context.Background(), "cid")
if err != nil {
t.Fatalf("缓存应已落库: %v", err)
@@ -208,7 +253,9 @@ func TestAcquireToken_CacheMissCallsMtopAndSavesCache(t *testing.T) {
// TestTryLoginStatusCheck_AdoptsUpdatedCookie loginuser.get 下发新 Cookie 时应采纳并清旧 token。
func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
// newCookie 保存new登录凭证,供当前处理流程使用
newCookie := "unb=123; _m_h5_tk=loginuser_new; sgcookie=abc"
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &statusMtop{
fakeRunMtop: fakeRunMtop{token: "tok-1"},
result: &mtop.LoginStatusResult{
@@ -217,29 +264,36 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
Message: "令牌已刷新",
},
}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
// oldDeviceID 保存oldDeviceID,供当前处理流程使用
oldDeviceID := acc.deviceID
saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
// res 保存响应,供当前处理流程使用
res := acc.tryLoginStatusCheck(context.Background())
if !res.recovered || res.riskRequired {
t.Fatalf("登录态检查应恢复 Cookie,got %+v", res)
}
if got := acc.currentCookieStr(); got != newCookie {
if // got 保存got,供当前处理流程使用
got := acc.currentCookieStr(); got != newCookie {
t.Fatalf("内存 Cookie 未更新: got %q want %q", got, newCookie)
}
// saved、err 保存saved、err,供当前处理流程使用
saved, err := store.Cookies.GetValue(context.Background(), "cid")
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 != oldDeviceID || acc.deviceID != oldDeviceID {
if // tk、err 保存tk、err,供当前处理流程使用
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)
}
}
// TestTryLoginStatusCheck_RiskRequired loginuser.get 命中风控时应进入验证态,不继续普通续期。
func TestTryLoginStatusCheck_RiskRequired(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &statusMtop{
fakeRunMtop: fakeRunMtop{token: "tok-1"},
result: &mtop.LoginStatusResult{
@@ -249,9 +303,11 @@ func TestTryLoginStatusCheck_RiskRequired(t *testing.T) {
Message: "闲鱼要求安全验证",
},
}
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
// res 保存响应,供当前处理流程使用
res := acc.tryLoginStatusCheck(context.Background())
if !res.riskRequired || res.recovered {
t.Fatalf("登录态检查应返回风控状态,got %+v", res)
@@ -259,13 +315,17 @@ func TestTryLoginStatusCheck_RiskRequired(t *testing.T) {
if res.verificationURL == "" {
t.Fatal("应保留风控验证 URL")
}
if got := acc.RuntimeStatus().State; got != RuntimeVerificationRequired {
if // got 保存got,供当前处理流程使用
got := acc.RuntimeStatus().State; got != RuntimeVerificationRequired {
t.Fatalf("风控时状态应为 verification_required,got %q", got)
}
}
// TestHandleMaxFailuresRunsLoginStatusCheckBeforeProtocolRenew 负责TestHandleMaxFailures运行记录登录状态CheckBeforeProtocolRenew相关处理。
func TestHandleMaxFailuresRunsLoginStatusCheckBeforeProtocolRenew(t *testing.T) {
// newCookie 保存new登录凭证,供当前处理流程使用
newCookie := "unb=123; _m_h5_tk=loginuser_recovered; sgcookie=abc"
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &statusMtop{
fakeRunMtop: fakeRunMtop{token: "tok-1"},
result: &mtop.LoginStatusResult{
@@ -274,20 +334,24 @@ func TestHandleMaxFailuresRunsLoginStatusCheckBeforeProtocolRenew(t *testing.T)
Message: "令牌已刷新",
},
}
// acc、handler、cleanup 保存acc、handler、cleanup,供当前处理流程使用
acc, handler, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
acc.mu.Lock()
acc.connFailures = MaxConnectionFailures
acc.mu.Unlock()
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
if err := acc.handleMaxFailures(ctx); err != ctx.Err() {
if // err 保存err,供当前处理流程使用
err := acc.handleMaxFailures(ctx); err != ctx.Err() {
t.Fatalf("登录态恢复后的等待应响应上下文取消: %v", err)
}
if handler.refresh != 0 {
t.Fatalf("loginuser.get 已恢复时不应继续协议续期,calls=%d", handler.refresh)
}
if got := acc.currentCookieStr(); got != newCookie {
if // got 保存got,供当前处理流程使用
got := acc.currentCookieStr(); got != newCookie {
t.Fatalf("登录态检查恢复 Cookie=%q want %q", got, newCookie)
}
if acc.connFailures != 0 {
@@ -297,6 +361,7 @@ func TestHandleMaxFailuresRunsLoginStatusCheckBeforeProtocolRenew(t *testing.T)
// TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache DB cookie 变更时采纳新 cookie 并清旧 token 缓存。
func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 预置旧 session 的 token 缓存。
@@ -304,11 +369,13 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
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"
if err := store.Cookies.Save(context.Background(), "cid", newCookie, 0); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(context.Background(), "cid", newCookie, 0); err != nil {
t.Fatalf("Save: %v", err)
}
acc.reloadCookieFromDB(context.Background())
if got := acc.CurrentCookieStr(); got != newCookie {
if // got 保存got,供当前处理流程使用
got := acc.CurrentCookieStr(); got != newCookie {
t.Fatalf("应采纳 DB 新 cookie,got %s", got)
}
// 普通 Cookie Jar 更新不等于页面 reload:旧 token 清除,device ID 保持。
@@ -319,11 +386,14 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
// TestHandleMaxFailures_AlertOnce 连续两次进入 false 终止路径只告警一次。
func TestHandleMaxFailures_AlertOnce(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := &failingRefreshHandler{}
acc.handler = h
// call 保存call,供当前处理流程使用
call := func() {
acc.mu.Lock()
acc.lastMsgReceived = time.Time{}
+42 -10
View File
@@ -12,6 +12,7 @@ import (
// messageDispatcher 负责 WebSocket 消息的事实解析、去重、防抖和并发投递。
// 各锁只保护本组件字段;持锁时不执行 handler、回复服务或数据库 I/O。
// messageDispatcher 保存消息Dispatcher,供当前处理流程使用
type messageDispatcher struct {
// dedupMu 保护 processed 去重时间表。
dedupMu sync.Mutex
@@ -63,26 +64,32 @@ type messageDispatcherConfig struct {
// newMessageDispatcher 构造消息分发组件并初始化其有界状态。
func newMessageDispatcher(config messageDispatcherConfig) messageDispatcher {
// logger 保存logger,供当前处理流程使用
logger := config.Logger
if logger == nil {
logger = slog.Default()
}
// currentCookie 保存current登录凭证,供当前处理流程使用
currentCookie := config.CurrentCookie
if currentCookie == nil {
currentCookie = func() string { return "" }
}
// 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() {}
}
// recordMessage 保存record消息,供当前处理流程使用
recordMessage := config.RecordMessage
if recordMessage == nil {
recordMessage = func(time.Time) {}
}
// currentHandler 保存currentHandler,供当前处理流程使用
currentHandler := config.CurrentHandler
if currentHandler == nil {
currentHandler = func() Handler { return nil }
@@ -104,6 +111,7 @@ func newMessageDispatcher(config messageDispatcherConfig) messageDispatcher {
// dispatch 接收一条解密消息并安排系统事件或聊天消息处理。
func (d *messageDispatcher) dispatch(decrypted map[string]any) {
// ctx、ok 保存ctx、ok,供当前处理流程使用
ctx, ok := d.beginTask()
if !ok {
return
@@ -111,6 +119,7 @@ func (d *messageDispatcher) dispatch(decrypted map[string]any) {
d.recordMessage(time.Now())
// 系统业务事件不能丢弃:并发满时让 WS 读取产生背压,等待处理槽位。
// 普通聊天仍采用非阻塞限流,避免聊天洪峰拖垮连接。
// isSystemEvent 保存is系统Event,供当前处理流程使用
isSystemEvent := automation.ExtractTaskFromWS(d.cookieID, d.currentCookie(), decrypted) != nil
if isSystemEvent {
select {
@@ -150,14 +159,17 @@ func (d *messageDispatcher) handleMessage(decrypted map[string]any) {
func (d *messageDispatcher) handleMessageContext(ctx context.Context, decrypted map[string]any) {
// 系统卡片和平台通知优先进入自动化中心,永远不进入 AI 回复范围。
if task := automation.ExtractTaskFromWS(d.cookieID, d.currentCookie(), decrypted); task != nil {
if handler := d.currentHandler(); handler != nil {
if err := handler.HandleSystemEvent(ctx, *task); err != nil {
if // handler 保存handler,供当前处理流程使用
handler := d.currentHandler(); handler != nil {
if // err 保存err,供当前处理流程使用
err := handler.HandleSystemEvent(ctx, *task); err != nil {
d.logger.Error("处理系统自动化事件失败", "err", err, "trigger", task.TriggerType)
}
}
return
}
// chat 保存聊天,供当前处理流程使用
chat := extractChatMessage(decrypted, d.cookieID, d.currentCookie())
if chat != nil && chat.Text != "" {
if !d.markAndCheckDedup(decrypted, chat) {
@@ -169,12 +181,15 @@ func (d *messageDispatcher) handleMessageContext(ctx context.Context, decrypted
// markAndCheckDedup 提取消息 ID,检查有效期内是否已经处理。
func (d *messageDispatcher) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool {
// msgID 保存msgID,供当前处理流程使用
msgID := extractMessageID(decrypted)
if msgID == "" {
// 备用标识:chat_id + text + create_time。
createTime := "0"
if m1, ok := decrypted["1"].(map[string]any); ok {
if t, ok := m1["5"]; ok {
if // m1、ok 保存m1、ok,供当前处理流程使用
m1, ok := decrypted["1"].(map[string]any); ok {
if // t、ok 保存t、ok,供当前处理流程使用
t, ok := m1["5"]; ok {
createTime = toString(t)
}
}
@@ -183,8 +198,10 @@ func (d *messageDispatcher) markAndCheckDedup(decrypted map[string]any, chat *Ch
d.dedupMu.Lock()
defer d.dedupMu.Unlock()
// now 保存now,供当前处理流程使用
now := time.Now()
if last, ok := d.processed[msgID]; ok {
if // last、ok 保存last、ok,供当前处理流程使用
last, ok := d.processed[msgID]; ok {
if now.Sub(last) < MessageExpireTime {
d.logger.Info("消息已处理过,跳过", "msg_id", truncID(msgID))
return false
@@ -199,6 +216,7 @@ func (d *messageDispatcher) markAndCheckDedup(decrypted map[string]any, chat *Ch
// cleanupDedupLocked 清理过期去重记录,并在仍超限时删除最旧的一半。
func (d *messageDispatcher) cleanupDedupLocked(now time.Time) {
// id、timestamp 表示当前遍历过程中的id、timestamp
for id, timestamp := range d.processed {
if now.Sub(timestamp) > MessageExpireTime {
delete(d.processed, id)
@@ -212,13 +230,17 @@ func (d *messageDispatcher) cleanupDedupLocked(now time.Time) {
id string
at time.Time
}
// entries 保存entries,供当前处理流程使用
entries := make([]entry, 0, len(d.processed))
// id、timestamp 表示当前遍历过程中的id、timestamp
for id, timestamp := range d.processed {
entries = append(entries, entry{id: id, at: timestamp})
}
sort.Slice(entries, func(i, j int) bool { return entries[i].at.Before(entries[j].at) })
// remove 保存remove,供当前处理流程使用
remove := len(entries) / 2
for i := 0; i < remove; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < remove; i++ {
delete(d.processed, entries[i].id)
}
}
@@ -227,34 +249,43 @@ func (d *messageDispatcher) cleanupDedupLocked(now time.Time) {
func (d *messageDispatcher) scheduleDebouncedReply(chat ChatMessage) {
d.debounceMu.Lock()
defer d.debounceMu.Unlock()
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now()
if old, ok := d.debounceTimers[chat.ChatID]; ok && old.timer != nil {
if // old、ok 保存old、ok,供当前处理流程使用
old, ok := d.debounceTimers[chat.ChatID]; ok && old.timer != nil {
old.timer.Stop()
}
// entry 保存entry,供当前处理流程使用
entry := &debounceEntry{lastMsg: chat, deadline: deadline}
d.debounceTimers[chat.ChatID] = entry
entry.timer = time.AfterFunc(MessageDebounceDelay, func() {
d.debounceMu.Lock()
// current、ok 保存current、ok,供当前处理流程使用
current, ok := d.debounceTimers[chat.ChatID]
if !ok || current.deadline != deadline {
d.debounceMu.Unlock()
return
}
delete(d.debounceTimers, chat.ChatID)
// lastMessage 保存last消息,供当前处理流程使用
lastMessage := current.lastMsg
d.debounceMu.Unlock()
// ctx、ok 保存ctx、ok,供当前处理流程使用
ctx, ok := d.beginTask()
if !ok {
return
}
defer d.finishTask()
if d.reply != nil {
if err := d.reply.Handle(ctx, lastMessage); err != nil {
if // err 保存err,供当前处理流程使用
err := d.reply.Handle(ctx, lastMessage); err != nil {
d.logger.Error("处理自动回复失败", "err", err, "chat_id", chat.ChatID)
}
}
if handler := d.currentHandler(); handler != nil {
if err := handler.HandleChatMessage(ctx, lastMessage); err != nil {
if // handler 保存handler,供当前处理流程使用
handler := d.currentHandler(); handler != nil {
if // err 保存err,供当前处理流程使用
err := handler.HandleChatMessage(ctx, lastMessage); err != nil {
d.logger.Error("处理聊天消息失败", "err", err, "chat_id", chat.ChatID)
}
}
@@ -265,6 +296,7 @@ func (d *messageDispatcher) scheduleDebouncedReply(chat ChatMessage) {
func (d *messageDispatcher) stop() {
d.debounceMu.Lock()
defer d.debounceMu.Unlock()
// entry 表示当前遍历过程中的entry
for _, entry := range d.debounceTimers {
if entry.timer != nil {
entry.timer.Stop()
+19 -2
View File
@@ -7,35 +7,52 @@ import (
"xianyu-go/internal/automation"
)
// outgoingObserverHandler 保存outgoingObserverHandler,供当前处理流程使用
type outgoingObserverHandler struct {
messages []OutgoingChatMessage
}
// HandleChatMessage 处理聊天消息。
func (h *outgoingObserverHandler) HandleChatMessage(context.Context, ChatMessage) error { return nil }
// HandleSystemEvent 处理系统Event。
func (h *outgoingObserverHandler) HandleSystemEvent(context.Context, automation.Task) error {
return nil
}
func (h *outgoingObserverHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
func (h *outgoingObserverHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// OnAccountAlert 负责On账号Alert相关处理。
func (h *outgoingObserverHandler) OnAccountAlert(context.Context, string, string, string, string) {}
// HandleOutgoingChatMessage 处理Outgoing聊天消息。
func (h *outgoingObserverHandler) HandleOutgoingChatMessage(_ context.Context, message OutgoingChatMessage) error {
h.messages = append(h.messages, message)
return nil
}
// TestSendTextEmitsCorrelatedOutgoingObservation 负责TestSend文本EmitsCorrelatedOutgoingObservation相关处理。
func TestSendTextEmitsCorrelatedOutgoingObservation(t *testing.T) {
// handler 保存handler,供当前处理流程使用
handler := &outgoingObserverHandler{}
// account 保存账号,供当前处理流程使用
account := New(Config{CookieID: "account-1", CookieStr: "unb=me", Handler: handler})
// conn 保存conn,供当前处理流程使用
conn := &fakeWSConn{}
account.mu.Lock()
account.conn = conn
account.mu.Unlock()
// ctx 保存ctx,供当前处理流程使用
ctx := WithOutgoingMessageKey(context.Background(), "local-1")
if err := account.SendText(ctx, "chat-1", "buyer-1", "您好"); err != nil {
if // err 保存err,供当前处理流程使用
err := account.SendText(ctx, "chat-1", "buyer-1", "您好"); err != nil {
t.Fatal(err)
}
if len(handler.messages) != 1 {
t.Fatalf("messages=%+v", handler.messages)
}
// got 保存got,供当前处理流程使用
got := handler.messages[0]
if got.AccountID != "account-1" || got.ChatID != "chat-1" || got.BuyerID != "buyer-1" || got.Text != "您好" || got.MessageKey != "local-1" {
t.Fatalf("observation=%+v", got)
+32 -8
View File
@@ -68,7 +68,9 @@ func NewReplyService(cookieID string, store *db.Store, sender MessageSender,
// Handle 收到一条聊天消息,按四级优先级回复。
// 由 Account 在防抖后调用。返回是否产生了回复。
// Handle 处理当前值。
func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error {
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, m)
if res == nil || res.Skip {
return nil
@@ -78,9 +80,12 @@ func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error {
if r.sender == nil {
return nil
}
// record 保存record,供当前处理流程使用
record := db.DefaultReplyRecord{}
if res.ReplyOnce && m.ChatID != "" {
// claimed 保存claimed,供当前处理流程使用
var claimed bool
// err 保存err,供当前处理流程使用
var err error
record, claimed, err = r.store.DefaultReps.ClaimRecord(ctx, r.cookieID, m.ChatID, res.Text != "", res.ImageURL != "")
if err != nil {
@@ -91,33 +96,38 @@ func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error {
}
}
if res.ImageURL != "" && !record.ImageSent {
if err := r.sender.SendImage(ctx, m.ChatID, m.SenderUserID, res.ImageURL, 0); err != nil {
if // err 保存err,供当前处理流程使用
err := r.sender.SendImage(ctx, m.ChatID, m.SenderUserID, res.ImageURL, 0); err != nil {
r.logger.Error("发送回复图片失败", "err", err)
r.markReplyFailure(ctx, res, m, err)
return err
}
if res.ReplyOnce && m.ChatID != "" {
if err := r.store.DefaultReps.MarkPartSent(ctx, r.cookieID, m.ChatID, "image"); err != nil {
if // err 保存err,供当前处理流程使用
err := r.store.DefaultReps.MarkPartSent(ctx, r.cookieID, m.ChatID, "image"); err != nil {
r.markReplyFailure(ctx, res, m, err)
return err
}
}
}
if res.Text != "" && !record.TextSent {
if err := r.sender.SendText(ctx, m.ChatID, m.SenderUserID, res.Text); err != nil {
if // err 保存err,供当前处理流程使用
err := r.sender.SendText(ctx, m.ChatID, m.SenderUserID, res.Text); err != nil {
r.logger.Error("发送回复文本失败", "err", err)
r.markReplyFailure(ctx, res, m, err)
return err
}
if res.ReplyOnce && m.ChatID != "" {
if err := r.store.DefaultReps.MarkPartSent(ctx, r.cookieID, m.ChatID, "text"); err != nil {
if // err 保存err,供当前处理流程使用
err := r.store.DefaultReps.MarkPartSent(ctx, r.cookieID, m.ChatID, "text"); err != nil {
r.markReplyFailure(ctx, res, m, err)
return err
}
}
}
if res.ReplyOnce && m.ChatID != "" {
if err := r.store.DefaultReps.MarkRecordSent(ctx, r.cookieID, m.ChatID); err != nil {
if // err 保存err,供当前处理流程使用
err := r.store.DefaultReps.MarkRecordSent(ctx, r.cookieID, m.ChatID); err != nil {
r.markReplyFailure(ctx, res, m, err)
return err
}
@@ -125,6 +135,7 @@ func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error {
return nil
}
// markReplyFailure 负责mark回复Failure相关处理。
func (r *ReplyService) markReplyFailure(ctx context.Context, res *ReplyResult, m ChatMessage, sendErr error) {
if res.ReplyOnce && m.ChatID != "" {
_ = r.store.DefaultReps.MarkRecordFailed(ctx, r.cookieID, m.ChatID, sendErr.Error())
@@ -135,7 +146,8 @@ func (r *ReplyService) markReplyFailure(ctx context.Context, res *ReplyResult, m
func (r *ReplyService) resolve(ctx context.Context, m ChatMessage) *ReplyResult {
// 优先级1:API 回复。
if r.api != nil {
if res, err := r.api.Reply(ctx, m); err != nil {
if // res、err 保存res、err,供当前处理流程使用
res, err := r.api.Reply(ctx, m); err != nil {
r.logger.Error("API 回复失败", "err", err)
} else if res != nil {
res.Source = "API"
@@ -150,7 +162,8 @@ func (r *ReplyService) resolve(ctx context.Context, m ChatMessage) *ReplyResult
// 优先级3:AI 回复。
if r.ai != nil {
if res, err := r.ai.Reply(ctx, m); err != nil {
if // res、err 保存res、err,供当前处理流程使用
res, err := r.ai.Reply(ctx, m); err != nil {
r.logger.Error("AI 回复失败", "err", err)
} else if res != nil {
res.Source = "AI"
@@ -165,15 +178,19 @@ func (r *ReplyService) resolve(ctx context.Context, m ChatMessage) *ReplyResult
// keywordReply 关键词匹配。返回 nil 表示无匹配;
// 返回 Skip=true 表示匹配到空回复(不发送)。
// 移植自 get_keyword_reply:商品ID关键词优先 → 通用关键词。
// keywordReply 负责关键词回复相关处理。
func (r *ReplyService) keywordReply(ctx context.Context, m ChatMessage) *ReplyResult {
// kws、err 保存kws、err,供当前处理流程使用
kws, err := r.store.Keywords.AllWithType(ctx, r.cookieID)
if err != nil || len(kws) == 0 {
return nil
}
// msgLower 保存msgLower,供当前处理流程使用
msgLower := strings.ToLower(m.Text)
// 1. 商品ID关键词优先。
if m.ItemID != "" {
// kw 表示当前遍历过程中的kw
for _, kw := range kws {
if kw.ItemID == m.ItemID && strings.Contains(msgLower, strings.ToLower(kw.Keyword)) {
return r.keywordResult(kw, m)
@@ -189,6 +206,7 @@ func (r *ReplyService) keywordReply(ctx context.Context, m ChatMessage) *ReplyRe
return nil
}
// keywordResult 负责关键词结果相关处理。
func (r *ReplyService) keywordResult(kw db.Keyword, m ChatMessage) *ReplyResult {
if kw.Type == "image" && kw.ImageURL != "" {
return &ReplyResult{ImageURL: kw.ImageURL, Source: "关键词"}
@@ -201,10 +219,12 @@ func (r *ReplyService) keywordResult(kw db.Keyword, m ChatMessage) *ReplyResult
// defaultReply 默认回复。移植自 get_default_reply:
// 指定商品回复优先 → 账号默认回复(reply_once 防重复 + 变量替换)。
// defaultReply 负责default回复相关处理。
func (r *ReplyService) defaultReply(ctx context.Context, m ChatMessage) *ReplyResult {
// 1. 指定商品回复。
if m.ItemID != "" {
if ir, err := r.store.ItemReps.Get(ctx, r.cookieID, m.ItemID); err == nil && ir != nil && strings.TrimSpace(ir.ReplyContent) != "" {
if // ir、err 保存ir、err,供当前处理流程使用
ir, err := r.store.ItemReps.Get(ctx, r.cookieID, m.ItemID); err == nil && ir != nil && strings.TrimSpace(ir.ReplyContent) != "" {
return &ReplyResult{Text: formatReplyWithItem(ir.ReplyContent, m), Source: "默认"}
}
}
@@ -217,6 +237,7 @@ func (r *ReplyService) defaultReply(ctx context.Context, m ChatMessage) *ReplyRe
if strings.TrimSpace(dr.ReplyContent) == "" && strings.TrimSpace(dr.ReplyImageURL) == "" {
return &ReplyResult{Skip: true, Source: "默认"}
}
// res 保存响应,供当前处理流程使用
res := &ReplyResult{Source: "默认", ReplyOnce: dr.ReplyOnce}
if strings.TrimSpace(dr.ReplyContent) != "" {
res.Text = formatReply(dr.ReplyContent, m)
@@ -229,6 +250,7 @@ func (r *ReplyService) defaultReply(ctx context.Context, m ChatMessage) *ReplyRe
// formatReply 变量替换:{send_user_name} {send_user_id} {send_message}。
// 替换回复模板变量;若替换出错则返回原文。
// formatReply 负责format回复相关处理。
func formatReply(template string, m ChatMessage) string {
return safeFormat(template, map[string]string{
"send_user_name": m.SenderName,
@@ -249,7 +271,9 @@ func formatReplyWithItem(template string, m ChatMessage) string {
// safeFormat 实现命名占位符替换。
func safeFormat(template string, vars map[string]string) string {
// out 保存out,供当前处理流程使用
out := template
// k、v 表示当前遍历过程中的k、v
for k, v := range vars {
out = strings.ReplaceAll(out, "{"+k+"}", v)
}
+68 -13
View File
@@ -15,6 +15,7 @@ type fakeAPIReplier struct {
called int
}
// Reply 负责回复相关处理。
func (f *fakeAPIReplier) Reply(_ context.Context, _ ChatMessage) (*ReplyResult, error) {
f.called++
return f.result, f.err
@@ -27,6 +28,7 @@ type fakeAIReplier struct {
called int
}
// Reply 负责回复相关处理。
func (f *fakeAIReplier) Reply(_ context.Context, _ ChatMessage) (*ReplyResult, error) {
f.called++
return f.result, f.err
@@ -40,15 +42,18 @@ type recordingSender struct {
imageErr error
}
// textSent 保存文本Sent,供当前处理流程使用
type textSent struct {
chatID, toUserID, text string
}
// imageSent 保存图片Sent,供当前处理流程使用
type imageSent struct {
chatID, toUserID, url string
cardID int64
}
// SendText 负责Send文本相关处理。
func (r *recordingSender) SendText(_ context.Context, chatID, toUserID, text string) error {
if r.textErr != nil {
return r.textErr
@@ -57,6 +62,7 @@ func (r *recordingSender) SendText(_ context.Context, chatID, toUserID, text str
return nil
}
// SendImage 负责Send图片相关处理。
func (r *recordingSender) SendImage(_ context.Context, chatID, toUserID, url string, cardID int64) error {
if r.imageErr != nil {
return r.imageErr
@@ -65,31 +71,41 @@ func (r *recordingSender) SendImage(_ context.Context, chatID, toUserID, url str
return nil
}
// TestReplyOnceRetriesOnlyFailedParts 负责Test回复OnceRetriesOnly失败Parts相关处理。
func TestReplyOnceRetriesOnlyFailedParts(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies
(cookie_id,enabled,reply_content,reply_image_url,reply_once)
VALUES ('cid',1,'文字','http://img/retry.png',1)`)
// textFailure 保存文本Failure,供当前处理流程使用
textFailure := errors.New("text failed")
// firstSender 保存firstSender,供当前处理流程使用
firstSender := &recordingSender{textErr: textFailure}
// service 保存service,供当前处理流程使用
service := NewReplyService("cid", s, firstSender, nil, nil, nil)
if err := service.Handle(ctx, chatMsg("在吗", "", "chat-retry")); !errors.Is(err, textFailure) {
if // err 保存err,供当前处理流程使用
err := service.Handle(ctx, chatMsg("在吗", "", "chat-retry")); !errors.Is(err, textFailure) {
t.Fatalf("first error=%v want text failure", err)
}
if len(firstSender.images) != 1 || len(firstSender.texts) != 0 {
t.Fatalf("first delivery images=%+v texts=%+v", firstSender.images, firstSender.texts)
}
// record、err 保存record、err,供当前处理流程使用
record, err := s.DefaultReps.Record(ctx, "cid", "chat-retry")
if err != nil || record.Status != "failed" || !record.ImageSent || record.TextSent {
t.Fatalf("failed record=%+v err=%v", record, err)
}
// secondSender 保存secondSender,供当前处理流程使用
secondSender := &recordingSender{}
service = NewReplyService("cid", s, secondSender, nil, nil, nil)
if err := service.Handle(ctx, chatMsg("再问", "", "chat-retry")); err != nil {
if // err 保存err,供当前处理流程使用
err := service.Handle(ctx, chatMsg("再问", "", "chat-retry")); err != nil {
t.Fatal(err)
}
if len(secondSender.images) != 0 || len(secondSender.texts) != 1 {
@@ -103,14 +119,18 @@ func TestReplyOnceRetriesOnlyFailedParts(t *testing.T) {
// TestReply_APIPriorityAndError API 回复命中时优先级最高;API 报错时降级到关键词。
func TestReply_APIPriorityAndError(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','关键词回复','text')`)
// API 返回结果 → 用 API。
api := &fakeAPIReplier{result: &ReplyResult{Text: "API回复"}}
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, api, nil, nil)
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, chatMsg("在吗", "", "chat1"))
if res == nil || res.Source != "API" || res.Text != "API回复" {
t.Fatalf("API 命中应优先,got %+v", res)
@@ -118,7 +138,9 @@ func TestReply_APIPriorityAndError(t *testing.T) {
// API 报错 → 降级到关键词。
api2 := &fakeAPIReplier{err: errors.New("upstream down")}
// r2 保存r2,供当前处理流程使用
r2 := NewReplyService("cid", s, nil, api2, nil, nil)
// res2 保存res2,供当前处理流程使用
res2 := r2.resolve(ctx, chatMsg("在吗", "", "chat1"))
if res2 == nil || res2.Source != "关键词" || res2.Text != "关键词回复" {
t.Fatalf("API 报错应降级到关键词,got %+v", res2)
@@ -126,7 +148,9 @@ func TestReply_APIPriorityAndError(t *testing.T) {
// API 返回 nil(无回复)→ 降级到关键词。
api3 := &fakeAPIReplier{result: nil}
// r3 保存r3,供当前处理流程使用
r3 := NewReplyService("cid", s, nil, api3, nil, nil)
// res3 保存res3,供当前处理流程使用
res3 := r3.resolve(ctx, chatMsg("在吗", "", "chat1"))
if res3 == nil || res3.Source != "关键词" {
t.Fatalf("API nil 应降级到关键词,got %+v", res3)
@@ -135,13 +159,18 @@ func TestReply_APIPriorityAndError(t *testing.T) {
// TestReply_AIPriorityOverDefault AI 回复优先于默认回复;AI 报错降级到默认。
func TestReply_AIPriorityOverDefault(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认回复',0)`)
// ai 保存人工智能,供当前处理流程使用
ai := &fakeAIReplier{result: &ReplyResult{Text: "AI回复"}}
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, nil, ai, nil)
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, chatMsg("复杂问题", "", "chat1"))
if res == nil || res.Source != "AI" || res.Text != "AI回复" {
t.Fatalf("AI 命中应优先于默认,got %+v", res)
@@ -149,7 +178,9 @@ func TestReply_AIPriorityOverDefault(t *testing.T) {
// AI 报错 → 降级到默认。
ai2 := &fakeAIReplier{err: errors.New("model timeout")}
// r2 保存r2,供当前处理流程使用
r2 := NewReplyService("cid", s, nil, nil, ai2, nil)
// res2 保存res2,供当前处理流程使用
res2 := r2.resolve(ctx, chatMsg("复杂问题", "", "chat1"))
if res2 == nil || res2.Source != "默认" || res2.Text != "默认回复" {
t.Fatalf("AI 报错应降级到默认,got %+v", res2)
@@ -158,12 +189,16 @@ func TestReply_AIPriorityOverDefault(t *testing.T) {
// TestReply_ImageKeyword 图片类型关键词返回 ImageURL。
func TestReply_ImageKeyword(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,image_url,type) VALUES ('cid','看图','','http://img/x.png','image')`)
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, nil, nil, nil)
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, chatMsg("发看图", "item1", "chat1"))
if res == nil || res.Source != "关键词" || res.ImageURL != "http://img/x.png" {
t.Fatalf("图片关键词应返回 ImageURL,got %+v", res)
@@ -172,14 +207,19 @@ func TestReply_ImageKeyword(t *testing.T) {
// TestReply_HandleSendsImageThenText Handle 先发图片后发文本;Skip 不发送。
func TestReply_HandleSendsImageThenText(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_image_url,reply_once) VALUES ('cid',1,'文字','http://img/y.png',0)`)
// sender 保存sender,供当前处理流程使用
sender := &recordingSender{}
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, sender, nil, nil, nil)
if err := r.Handle(ctx, chatMsg("在吗", "", "chat9")); err != nil {
if // err 保存err,供当前处理流程使用
err := r.Handle(ctx, chatMsg("在吗", "", "chat9")); err != nil {
t.Fatalf("Handle: %v", err)
}
if len(sender.images) != 1 || sender.images[0].url != "http://img/y.png" {
@@ -191,9 +231,12 @@ func TestReply_HandleSendsImageThenText(t *testing.T) {
// Skip(空默认回复)不应发送任何内容。
s.DB.ExecContext(ctx, `UPDATE default_replies SET reply_content='', reply_image_url='' WHERE cookie_id='cid'`)
// sender2 保存sender2,供当前处理流程使用
sender2 := &recordingSender{}
// r2 保存r2,供当前处理流程使用
r2 := NewReplyService("cid", s, sender2, nil, nil, nil)
if err := r2.Handle(ctx, chatMsg("在吗", "", "chat9")); err != nil {
if // err 保存err,供当前处理流程使用
err := r2.Handle(ctx, chatMsg("在吗", "", "chat9")); err != nil {
t.Fatalf("Handle skip: %v", err)
}
if len(sender2.texts) != 0 || len(sender2.images) != 0 {
@@ -203,14 +246,17 @@ func TestReply_HandleSendsImageThenText(t *testing.T) {
// TestParseMessageIDFromJSON bizTag/extJson 中提取 messageId。
func TestParseMessageIDFromJSON(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
`{"messageId":"abc123"}`: "abc123",
`{"sourceId":"x"}`: "",
`not json`: "",
`{}`: "",
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := parseMessageIDFromJSON(in); got != want {
if // got 保存got,供当前处理流程使用
got := parseMessageIDFromJSON(in); got != want {
t.Errorf("parseMessageIDFromJSON(%q)=%q want %q", in, got, want)
}
}
@@ -218,7 +264,8 @@ func TestParseMessageIDFromJSON(t *testing.T) {
// TestExtractMessageID 优先 bizTag,其次 extJson,无则空。
func TestExtractMessageID(t *testing.T) {
if got := extractMessageID(map[string]any{
if // got 保存got,供当前处理流程使用
got := extractMessageID(map[string]any{
"1": map[string]any{
"10": map[string]any{
"bizTag": `{"messageId":"biz-id"}`,
@@ -228,7 +275,8 @@ func TestExtractMessageID(t *testing.T) {
}); got != "biz-id" {
t.Errorf("bizTag 优先: got %q", got)
}
if got := extractMessageID(map[string]any{
if // got 保存got,供当前处理流程使用
got := extractMessageID(map[string]any{
"1": map[string]any{
"10": map[string]any{
"extJson": `{"messageId":"ext-id"}`,
@@ -237,7 +285,8 @@ func TestExtractMessageID(t *testing.T) {
}); got != "ext-id" {
t.Errorf("extJson 兜底: got %q", got)
}
if got := extractMessageID(map[string]any{"1": map[string]any{}}); got != "" {
if // got 保存got,供当前处理流程使用
got := extractMessageID(map[string]any{"1": map[string]any{}}); got != "" {
t.Errorf("无 ID: got %q", got)
}
}
@@ -287,6 +336,7 @@ func TestIsNonUserChatNotice(t *testing.T) {
}
}
// TestIsNonUserChatNoticeFiltersOfficialSenderAndPlaceholder 负责TestIsNon用户聊天NoticeFiltersOfficialSenderAndPlaceholder相关处理。
func TestIsNonUserChatNoticeFiltersOfficialSenderAndPlaceholder(t *testing.T) {
if !isNonUserChatNotice(map[string]any{}, map[string]any{"senderUserId": "1400", "reminderContent": "邀您填写售后问卷"}, "邀您填写售后问卷") {
t.Error("闲小蜜消息应判为官方系统消息")
@@ -298,19 +348,24 @@ func TestIsNonUserChatNoticeFiltersOfficialSenderAndPlaceholder(t *testing.T) {
// TestToStringAndTrimFloatInt 数字/字符串安全转换。
func TestToStringAndTrimFloatInt(t *testing.T) {
if got := toString(float64(26)); got != "26" {
if // got 保存got,供当前处理流程使用
got := toString(float64(26)); got != "26" {
t.Errorf("toString(float64 26)=%q", got)
}
if got := toString("hello"); got != "hello" {
if // got 保存got,供当前处理流程使用
got := toString("hello"); got != "hello" {
t.Errorf("toString(string)=%q", got)
}
if got := toString(nil); got != "" {
if // got 保存got,供当前处理流程使用
got := toString(nil); got != "" {
t.Errorf("toString(nil)=%q", got)
}
if got := trimFloatInt(12.00); got != "12" {
if // got 保存got,供当前处理流程使用
got := trimFloatInt(12.00); got != "12" {
t.Errorf("trimFloatInt(12.00)=%q", got)
}
if got := trimFloatInt(12.50); got != "12.5" {
if // got 保存got,供当前处理流程使用
got := trimFloatInt(12.50); got != "12.5" {
t.Errorf("trimFloatInt(12.50)=%q", got)
}
}
+40 -4
View File
@@ -8,19 +8,24 @@ import (
"xianyu-go/internal/db"
)
// newReplyStore 负责new回复Store相关处理。
func newReplyStore(t *testing.T) (*db.Store, func()) {
t.Helper()
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
// s 保存s,供当前处理流程使用
s := db.NewStore(d, db.DialectSQLite)
s.Users.Create(context.Background(), "admin", "a@e.com", "pw")
// admin 保存admin,供当前处理流程使用
admin, _ := s.Users.GetByUsername(context.Background(), "admin")
s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
return s, func() { d.Close() }
}
// chatMsg 负责聊天Msg相关处理。
func chatMsg(text, itemID, chatID string) ChatMessage {
return ChatMessage{
AccountID: "cid", CookieStr: "",
@@ -31,13 +36,17 @@ func chatMsg(text, itemID, chatID string) ChatMessage {
// TestKeywordReply_MatchAndVariableSubst 关键词匹配 + 变量替换。
func TestKeywordReply_MatchAndVariableSubst(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// 关键词 "在吗" → "你好{send_user_name},在的,请问要{send_message}吗"
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','你好{send_user_name},在的','text')`)
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, nil, nil, nil)
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, chatMsg("老板在吗", "item1", "chat1"))
if res == nil || res.Source != "关键词" {
t.Fatalf("应命中关键词,got %+v", res)
@@ -49,14 +58,18 @@ func TestKeywordReply_MatchAndVariableSubst(t *testing.T) {
// TestKeywordReply_ItemIDPriority 商品ID关键词优先于通用关键词。
func TestKeywordReply_ItemIDPriority(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,item_id,type) VALUES
('cid','价格','通用价格回复','','text'),
('cid','价格','该商品专属价格回复','item1','text')`)
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, nil, nil, nil)
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, chatMsg("价格多少", "item1", "chat1"))
if res == nil || res.Text != "该商品专属价格回复" {
t.Errorf("应优先商品ID关键词,got %+v", res)
@@ -70,11 +83,15 @@ func TestKeywordReply_ItemIDPriority(t *testing.T) {
// TestKeywordReply_EmptyReplySkip 匹配到空回复 → Skip。
func TestKeywordReply_EmptyReplySkip(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','静默','','text')`)
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, nil, nil, nil)
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, chatMsg("静默一下", "item1", "chat1"))
if res == nil || !res.Skip {
t.Fatalf("空回复应 Skip=true,got %+v", res)
@@ -83,13 +100,17 @@ func TestKeywordReply_EmptyReplySkip(t *testing.T) {
// TestDefaultReply_ItemReplyFirst 指定商品回复优先于账号默认回复。
func TestDefaultReply_ItemReplyFirst(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'账号默认回复',0)`)
s.DB.ExecContext(ctx, `INSERT INTO item_replay (item_id,cookie_id,reply_content) VALUES ('item1','cid','该商品专属默认回复')`)
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, nil, nil, nil)
// res 保存响应,供当前处理流程使用
res := r.resolve(ctx, chatMsg("任意消息", "item1", "chat1"))
if res == nil || res.Text != "该商品专属默认回复" {
t.Errorf("应优先指定商品回复,got %+v", res)
@@ -98,20 +119,27 @@ func TestDefaultReply_ItemReplyFirst(t *testing.T) {
// TestDefaultReply_ReplyOnce reply_once 防重复。
func TestDefaultReply_ReplyOnce(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认问候',1)`)
// sender 保存sender,供当前处理流程使用
sender := &recordingSender{}
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, sender, nil, nil, nil)
if err := r.Handle(ctx, chatMsg("在吗", "item1", "chatX")); err != nil {
if // err 保存err,供当前处理流程使用
err := r.Handle(ctx, chatMsg("在吗", "item1", "chatX")); err != nil {
t.Fatal(err)
}
if err := r.Handle(ctx, chatMsg("还在吗", "item1", "chatX")); err != nil {
if // err 保存err,供当前处理流程使用
err := r.Handle(ctx, chatMsg("还在吗", "item1", "chatX")); err != nil {
t.Fatal(err)
}
if err := r.Handle(ctx, chatMsg("在吗", "item1", "chatY")); err != nil {
if // err 保存err,供当前处理流程使用
err := r.Handle(ctx, chatMsg("在吗", "item1", "chatY")); err != nil {
t.Fatal(err)
}
if len(sender.texts) != 2 || sender.texts[0].text != "默认问候" || sender.texts[1].chatID != "chatY" {
@@ -121,12 +149,15 @@ func TestDefaultReply_ReplyOnce(t *testing.T) {
// TestPriority_Order 四级优先级:关键词 > 默认(无API/AI时)。
func TestPriority_Order(t *testing.T) {
// s、cleanup 保存s、cleanup,供当前处理流程使用
s, cleanup := newReplyStore(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','关键词回复','text')`)
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认回复',0)`)
// r 保存r,供当前处理流程使用
r := NewReplyService("cid", s, nil, nil, nil, nil)
// 命中关键词 → 关键词回复。
res := r.resolve(ctx, chatMsg("在吗", "", "chat1"))
@@ -142,8 +173,10 @@ func TestPriority_Order(t *testing.T) {
// TestFormatReply 变量替换。
func TestFormatReply(t *testing.T) {
// m 保存m,供当前处理流程使用
m := chatMsg("想买", "item1", "chat1")
m.SenderName = "张三"
// got 保存got,供当前处理流程使用
got := formatReply("你好{send_user_name},你说{send_message}", m)
if got != "你好张三,你说想买" {
t.Errorf("formatReply=%q", got)
@@ -152,6 +185,7 @@ func TestFormatReply(t *testing.T) {
// TestParsePrice 价格解析。
func TestParsePrice(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]float64{
"¥99.5": 99.5,
"100元": 100,
@@ -159,8 +193,10 @@ func TestParsePrice(t *testing.T) {
"abc": 0,
"12.34": 12.34,
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := parsePrice(in); got != want {
if // got 保存got,供当前处理流程使用
got := parsePrice(in); got != want {
t.Errorf("parsePrice(%q)=%v want %v", in, got, want)
}
}
+175 -17
View File
@@ -20,56 +20,83 @@ import (
// fakeRunMtop 返回成功 token,不触网。
type fakeRunMtop struct{ token string }
// FetchUserProfile 负责Fetch用户Profile相关处理。
func (f *fakeRunMtop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
return nil, nil
}
// shortTokenMtop 保存short令牌Mtop,供当前处理流程使用
type shortTokenMtop struct {
fakeRunMtop
calls atomic.Int32
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (s *shortTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
// call 保存call,供当前处理流程使用
call := s.calls.Add(1)
return &mtop.RefreshResult{AccessToken: fmt.Sprintf("short-%d", call), AccessTokenExpireAt: time.Now().Add(2 * time.Second).Unix()}, nil
}
// ConsignContext 负责Consign上下文相关处理。
func (f *fakeRunMtop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
return true, nil, "", nil
}
// FetchItemsPage 负责Fetch商品列表页码相关处理。
func (f *fakeRunMtop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// FetchAllItems 负责FetchAll商品列表相关处理。
func (f *fakeRunMtop) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// PublishItem 负责发布商品相关处理。
func (f *fakeRunMtop) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return nil, nil
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (f *fakeRunMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
return &mtop.RefreshResult{AccessToken: f.token, AccessTokenExpireAt: time.Now().Add(time.Hour).Unix()}, nil
}
// fakeFailTokenMtop 保存fakeFail令牌Mtop,供当前处理流程使用
type fakeFailTokenMtop struct{ err error }
// FetchUserProfile 负责Fetch用户Profile相关处理。
func (f *fakeFailTokenMtop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
return nil, nil
}
// ConsignContext 负责Consign上下文相关处理。
func (f *fakeFailTokenMtop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
return true, nil, "", nil
}
// FetchItemsPage 负责Fetch商品列表页码相关处理。
func (f *fakeFailTokenMtop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// FetchAllItems 负责FetchAll商品列表相关处理。
func (f *fakeFailTokenMtop) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// PublishItem 负责发布商品相关处理。
func (f *fakeFailTokenMtop) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return nil, nil
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (f *fakeFailTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
return nil, f.err
}
// sequencedTokenMtop 保存sequenced令牌Mtop,供当前处理流程使用
type sequencedTokenMtop struct {
fakeRunMtop
mu sync.Mutex
@@ -78,6 +105,7 @@ type sequencedTokenMtop struct {
calls int
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (s *sequencedTokenMtop) RefreshTokenWithDeviceIDContext(_ context.Context, cookieStr, deviceID string) (*mtop.RefreshResult, error) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -109,15 +137,18 @@ type fakeWSConn struct {
recvErr error
}
// Register 负责Register相关处理。
func (f *fakeWSConn) Register(_ context.Context, deviceID, accessToken string) error {
f.mu.Lock()
f.registeredDID = deviceID
f.registeredTok = accessToken
// err 保存err,供当前处理流程使用
err := f.registerErr
f.mu.Unlock()
return err
}
// HeartbeatLoop 负责HeartbeatLoop相关处理。
func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
<-ctx.Done()
if f.heartbeatDone != nil {
@@ -126,6 +157,7 @@ func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
return ctx.Err()
}
// ReceiveLoop 负责ReceiveLoop相关处理。
func (f *fakeWSConn) ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error {
if f.onReceive != nil {
f.onReceive(onMessage)
@@ -145,6 +177,7 @@ func (f *fakeWSConn) ReceiveLoop(ctx context.Context, onMessage func(map[string]
return f.recvErr
}
// Close 关闭当前值。
func (f *fakeWSConn) Close() error {
f.mu.Lock()
f.closed = true
@@ -155,24 +188,34 @@ func (f *fakeWSConn) Close() error {
return nil
}
// TestRunRotatesTokenBeforeExpiry 负责Test运行Rotates令牌BeforeExpiry相关处理。
func TestRunRotatesTokenBeforeExpiry(t *testing.T) {
// tokenClient 保存令牌Client,供当前处理流程使用
tokenClient := &shortTokenMtop{}
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, tokenClient)
defer cleanup()
// first 保存first,供当前处理流程使用
first := &fakeWSConn{recvBlock: true, closeCh: make(chan struct{})}
// second 保存second,供当前处理流程使用
second := &fakeWSConn{recvBlock: true, closeCh: make(chan struct{})}
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: first}, {conn: second}}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(4 * time.Second)
for tokenClient.calls.Load() < 2 && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
if got := tokenClient.calls.Load(); got < 2 {
if // got 保存got,供当前处理流程使用
got := tokenClient.calls.Load(); got < 2 {
cancel()
t.Fatalf("Token 到期前未主动轮换,calls=%d status=%+v", got, acc.RuntimeStatus())
}
// status 保存状态,供当前处理流程使用
status := acc.RuntimeStatus()
if status.TokenExpiresAt.IsZero() || status.TokenRefreshAt.IsZero() || !status.TokenRefreshAt.Before(status.TokenExpiresAt) {
t.Fatalf("Token 有效期状态异常: %+v", status)
@@ -185,6 +228,7 @@ func TestRunRotatesTokenBeforeExpiry(t *testing.T) {
}
}
// SendText 负责Send文本相关处理。
func (f *fakeWSConn) SendText(_ context.Context, _, _, _, text string) error {
f.mu.Lock()
f.sentTexts = append(f.sentTexts, text)
@@ -192,6 +236,7 @@ func (f *fakeWSConn) SendText(_ context.Context, _, _, _, text string) error {
return nil
}
// SendImage 负责Send图片相关处理。
func (f *fakeWSConn) SendImage(_ context.Context, _, _, _, url string, _, _ int) error {
f.mu.Lock()
f.sentImages = append(f.sentImages, url)
@@ -209,26 +254,31 @@ type fakeDialer struct {
lastCfg ws.Config // 记录最后一次 Dial 的配置(含 AccessToken)
}
// dialResult 保存dial结果,供当前处理流程使用
type dialResult struct {
conn *fakeWSConn
err error
}
// Dial 负责Dial相关处理。
func (d *fakeDialer) Dial(_ context.Context, cfg ws.Config, _ *slog.Logger) (WSConn, error) {
d.mu.Lock()
defer d.mu.Unlock()
d.lastCfg = cfg
d.configs = append(d.configs, cfg)
// idx 保存idx,供当前处理流程使用
idx := d.calls
d.calls++
if idx >= len(d.results) {
// 超出预设:返回最后一个 conn,避免无限重连耗尽测试。
if len(d.results) > 0 {
// last 保存last,供当前处理流程使用
last := d.results[len(d.results)-1]
return last.conn, last.err
}
return nil, nil
}
// r 保存r,供当前处理流程使用
r := d.results[idx]
if r.conn != nil {
d.conns = append(d.conns, r.conn)
@@ -239,18 +289,24 @@ func (d *fakeDialer) Dial(_ context.Context, cfg ws.Config, _ *slog.Logger) (WSC
// newRunAccount 构造一个用 fakeMtop + fakeDialer 的 Account,不触网。
func newRunAccount(t *testing.T, mtopClient mtop.Client) (*Account, *recordingHandler, *db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "run.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
// store 保存store,供当前处理流程使用
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
store.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
store.Cookies.SetStatus(context.Background(), "cid", true)
// h 保存h,供当前处理流程使用
h := &recordingHandler{}
// acc 保存acc,供当前处理流程使用
acc := New(Config{
CookieID: "cid",
CookieStr: "unb=123; _m_h5_tk=tk_1;",
@@ -263,10 +319,13 @@ func newRunAccount(t *testing.T, mtopClient mtop.Client) (*Account, *recordingHa
// TestRun_ConnectsAndDispatchesMessage 验证 Run 主循环:
// 刷新 token → 拨号 WS → ReceiveLoop 投递消息 → dispatch 进 handler 防抖链 → ctx 取消后优雅退出。
// TestRun_ConnectsAndDispatchesMessage 负责Test运行ConnectsAndDispatches消息相关处理。
func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
// acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用
acc, h, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// conn 保存conn,供当前处理流程使用
conn := &fakeWSConn{
recvBlock: true,
onReceive: func(onMessage func(map[string]any)) {
@@ -286,7 +345,9 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
}
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// runDone 保存运行Done,供当前处理流程使用
runDone := make(chan error, 1)
go func() { runDone <- acc.Run(ctx) }()
@@ -294,6 +355,7 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
deadline := time.After(3 * time.Second)
for {
h.mu.Lock()
// n 保存n,供当前处理流程使用
n := len(h.chats)
h.mu.Unlock()
if n >= 1 {
@@ -310,6 +372,7 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
// token 必须在握手成功后通过 Register 发送,而不是在 Dial 前获得。
conn.mu.Lock()
// gotToken 保存got令牌,供当前处理流程使用
gotToken := conn.registeredTok == "tok-1"
conn.mu.Unlock()
if !gotToken {
@@ -319,7 +382,8 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
// 取消 ctx → Run 应退出。
cancel()
select {
case err := <-runDone:
case // err 保存err,供当前处理流程使用
err := <-runDone:
if err != nil && err != context.Canceled {
t.Fatalf("Run 退出 err=%v", err)
}
@@ -330,31 +394,38 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
// TestRun_DialFailureRequiresRelogin mirrors the web page: native
// CONNECT_FAILED enters CONN_ERROR and does not auto-reconnect.
// TestRun_DialFailureRequiresRelogin 负责Test运行DialFailureRequiresRelogin相关处理。
func TestRun_DialFailureRequiresRelogin(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 拨号始终失败。
acc.wsDialer = &fakeDialer{results: []dialResult{{err: errFakeDial}}}
// runDone 保存运行Done,供当前处理流程使用
runDone := make(chan error, 1)
go func() { runDone <- acc.Run(context.Background()) }()
select {
case err := <-runDone:
case // err 保存err,供当前处理流程使用
err := <-runDone:
if !errors.Is(err, errFakeDial) {
t.Fatalf("Run error=%v,期望拨号错误", err)
}
case <-time.After(2 * time.Second):
t.Fatal("拨号失败后 Run 未退出")
}
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
if // status 保存状态,供当前处理流程使用
status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
t.Fatalf("runtime state=%q,期望 %q", status.State, RuntimeAuthExpired)
}
}
// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并重新获取 token。
func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
@@ -363,8 +434,10 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
d := &fakeDialer{results: []dialResult{{conn: conn1}, {conn: conn2}}}
acc.wsDialer = d
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// runDone 保存运行Done,供当前处理流程使用
runDone := make(chan error, 1)
go func() { runDone <- acc.Run(ctx) }()
@@ -372,6 +445,7 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
deadline := time.After(2 * time.Second)
for {
d.mu.Lock()
// calls 保存calls,供当前处理流程使用
calls := d.calls
d.mu.Unlock()
if calls >= 2 {
@@ -391,24 +465,33 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
case <-time.After(3 * time.Second):
t.Fatal("重连后 ctx 取消 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
if // calls 保存calls,供当前处理流程使用
calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
t.Fatalf("正常重连应重新请求 mtop: calls=%d", calls)
}
}
// TestRun_ReconnectUsesFreshTokenAndStableDeviceID 负责Test运行ReconnectUsesFresh令牌AndStableDeviceID相关处理。
func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "unused"}}
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
// first 保存first,供当前处理流程使用
first := &fakeWSConn{recvBlock: false}
// second 保存second,供当前处理流程使用
second := &fakeWSConn{recvBlock: true}
// dialer 保存dialer,供当前处理流程使用
dialer := &fakeDialer{results: []dialResult{
{conn: first},
{conn: second},
}}
acc.wsDialer = dialer
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
waitForDialCalls(t, dialer, 2)
@@ -417,21 +500,25 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
<-done
dialer.mu.Lock()
// conns 保存conns,供当前处理流程使用
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 保存first令牌,供当前处理流程使用
firstToken := conns[0].registeredTok
conns[0].mu.Unlock()
conns[1].mu.Lock()
// secondToken 保存second令牌,供当前处理流程使用
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 保存devices,供当前处理流程使用
devices := append([]string(nil), mtopClient.devices...)
mtopClient.mu.Unlock()
if len(devices) != 2 || devices[0] == "" || devices[0] != devices[1] {
@@ -439,22 +526,32 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
}
}
// TestRun_EstablishedNetworkErrorReconnectsWithFreshToken 负责Test运行EstablishedNetwork错误ReconnectsWithFresh令牌相关处理。
func TestRun_EstablishedNetworkErrorReconnectsWithFreshToken(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
// first 保存first,供当前处理流程使用
first := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
// second 保存second,供当前处理流程使用
second := &fakeWSConn{recvBlock: true}
// dialer 保存dialer,供当前处理流程使用
dialer := &fakeDialer{results: []dialResult{{conn: first}, {conn: second}}}
acc.wsDialer = dialer
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
waitForDialCalls(t, dialer, 2)
waitForRegisteredToken(t, second, "tok-1")
acc.mu.Lock()
// currentToken 保存current令牌,供当前处理流程使用
currentToken := acc.currentToken
// networkFailures 保存networkFailures,供当前处理流程使用
networkFailures := acc.networkFailures
acc.mu.Unlock()
if networkFailures != 0 || currentToken != "tok-1" {
@@ -462,7 +559,8 @@ func TestRun_EstablishedNetworkErrorReconnectsWithFreshToken(t *testing.T) {
<-done
t.Fatalf("网络断线后应立即用新凭证恢复连接: failures=%d token=%q", networkFailures, currentToken)
}
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
if // cached、err 保存cached、err,供当前处理流程使用
cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
cancel()
<-done
t.Fatalf("重连成功后应缓存新连接凭证: cached=%+v err=%v", cached, err)
@@ -473,24 +571,31 @@ func TestRun_EstablishedNetworkErrorReconnectsWithFreshToken(t *testing.T) {
case <-time.After(2 * time.Second):
t.Fatal("取消后 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
if // calls 保存calls,供当前处理流程使用
calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
t.Fatalf("官网重连会重新获取连接凭证: calls=%d", calls)
}
}
// TestRun_InvalidRegTokenRequiresRelogin 负责Test运行InvalidReg令牌RequiresRelogin相关处理。
func TestRun_InvalidRegTokenRequiresRelogin(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}}
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
// dialer 保存dialer,供当前处理流程使用
dialer := &fakeDialer{results: []dialResult{
{conn: &fakeWSConn{registerErr: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}},
}}
acc.wsDialer = dialer
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(context.Background()) }()
select {
case err := <-done:
case // err 保存err,供当前处理流程使用
err := <-done:
if !ws.IsInvalidTokenError(err) {
t.Fatalf("Run error=%v", err)
}
@@ -498,34 +603,45 @@ func TestRun_InvalidRegTokenRequiresRelogin(t *testing.T) {
t.Fatal("invalid /reg 后 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
if // calls 保存calls,供当前处理流程使用
calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("invalid /reg 不应在页面要求重新登录时静默重试: calls=%d", calls)
}
if dialer.calls != 1 {
t.Fatalf("invalid /reg dial calls=%d want 1", dialer.calls)
}
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
if // status 保存状态,供当前处理流程使用
status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
}
}
// TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect 负责Test运行ReloadsDatabase登录凭证BeforeNaturalReconnect相关处理。
func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "token"}}
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
// newCookie 保存new登录凭证,供当前处理流程使用
newCookie := "unb=123; _m_h5_tk=db-renewed_2; cookie2=new"
// first 保存first,供当前处理流程使用
first := &fakeWSConn{recvBlock: false, onReceive: func(func(map[string]any)) {
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil {
t.Errorf("update Cookie: %v", err)
}
}}
// dialer 保存dialer,供当前处理流程使用
dialer := &fakeDialer{results: []dialResult{
{conn: first},
{conn: &fakeWSConn{recvBlock: true}},
}}
acc.wsDialer = dialer
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
waitForDialCalls(t, dialer, 2)
@@ -533,21 +649,26 @@ func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) {
<-done
mtopClient.mu.Lock()
// cookies 保存cookies,供当前处理流程使用
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 calls := mtopClient.calls; calls != 2 {
if // calls 保存calls,供当前处理流程使用
calls := mtopClient.calls; calls != 2 {
t.Fatalf("Cookie change should invalidate token for reconnect, calls=%d", calls)
}
}
// waitForDialCalls 负责waitForDialCalls相关处理。
func waitForDialCalls(t *testing.T, dialer *fakeDialer, want int) {
t.Helper()
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
dialer.mu.Lock()
// calls 保存calls,供当前处理流程使用
calls := dialer.calls
dialer.mu.Unlock()
if calls >= want {
@@ -556,16 +677,20 @@ func waitForDialCalls(t *testing.T, dialer *fakeDialer, want int) {
time.Sleep(10 * time.Millisecond)
}
dialer.mu.Lock()
// calls 保存calls,供当前处理流程使用
calls := dialer.calls
dialer.mu.Unlock()
t.Fatalf("dial calls=%d want>=%d", calls, want)
}
// waitForRegisteredToken 负责waitForRegistered令牌相关处理。
func waitForRegisteredToken(t *testing.T, conn *fakeWSConn, want string) {
t.Helper()
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
conn.mu.Lock()
// token 保存令牌,供当前处理流程使用
token := conn.registeredTok
conn.mu.Unlock()
if token == want {
@@ -574,6 +699,7 @@ func waitForRegisteredToken(t *testing.T, conn *fakeWSConn, want string) {
time.Sleep(10 * time.Millisecond)
}
conn.mu.Lock()
// token 保存令牌,供当前处理流程使用
token := conn.registeredTok
conn.mu.Unlock()
t.Fatalf("registered token=%q want=%q", token, want)
@@ -581,17 +707,21 @@ func waitForRegisteredToken(t *testing.T, conn *fakeWSConn, want string) {
// TestRun_DisabledAccountExits 账号被禁用时 Run 立即退出。
func TestRun_DisabledAccountExits(t *testing.T) {
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 禁用账号。
store.Cookies.SetStatus(context.Background(), "cid", false)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
select {
case err := <-done:
case // err 保存err,供当前处理流程使用
err := <-done:
if err != nil {
t.Fatalf("禁用账号 Run 应返回 nil,got %v", err)
}
@@ -600,16 +730,22 @@ func TestRun_DisabledAccountExits(t *testing.T) {
}
}
// TestRun_APIRenewFailureDoesNotBlockTokenAndWebSocket 负责Test运行APIRenewFailureDoesNotBlock令牌AndWebSocket相关处理。
func TestRun_APIRenewFailureDoesNotBlockTokenAndWebSocket(t *testing.T) {
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-after-renew-error"})
defer cleanup()
// renewer 保存renewer,供当前处理流程使用
renewer := &stubCookieRenewer{err: errors.New("startup API renewal failed")}
acc.renewer = renewer
// conn 保存conn,供当前处理流程使用
conn := &fakeWSConn{recvBlock: true}
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
@@ -619,7 +755,8 @@ func TestRun_APIRenewFailureDoesNotBlockTokenAndWebSocket(t *testing.T) {
}
cancel()
select {
case err := <-done:
case // err 保存err,供当前处理流程使用
err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("Run error=%v want context canceled", err)
}
@@ -628,12 +765,16 @@ func TestRun_APIRenewFailureDoesNotBlockTokenAndWebSocket(t *testing.T) {
}
}
// TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID 负责Test运行APIRenewSuccessRebuildsOfficial页码DeviceID相关处理。
func TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID(t *testing.T) {
// tokenClient 保存令牌Client,供当前处理流程使用
tokenClient := &sequencedTokenMtop{}
// acc、cleanup 保存acc、cleanup,供当前处理流程使用
acc, _, _, cleanup := newRunAccount(t, tokenClient)
defer cleanup()
acc.mu.Lock()
// initialDeviceID 保存initialDeviceID,供当前处理流程使用
initialDeviceID := acc.deviceID
acc.mu.Unlock()
acc.renewer = &stubCookieRenewer{result: &xrenew.Result{
@@ -641,15 +782,19 @@ func TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID(t *testing.T) {
RenewMethod: "auto_login_plugin",
NewCookies: "unb=123; _m_h5_tk=tk_1;",
}}
// conn 保存conn,供当前处理流程使用
conn := &fakeWSConn{recvBlock: true}
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
waitForRegisteredToken(t, conn, "fresh-1")
conn.mu.Lock()
// registeredDeviceID 保存registeredDeviceID,供当前处理流程使用
registeredDeviceID := conn.registeredDID
conn.mu.Unlock()
if registeredDeviceID == initialDeviceID {
@@ -663,7 +808,8 @@ func TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID(t *testing.T) {
cancel()
select {
case err := <-done:
case // err 保存err,供当前处理流程使用
err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("Run error=%v want context canceled", err)
}
@@ -672,29 +818,37 @@ func TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID(t *testing.T) {
}
}
// TestRun_TokenFetchFailureRetriesWithoutDisablingAccount 负责Test运行令牌FetchFailureRetriesWithoutDisabling账号相关处理。
func TestRun_TokenFetchFailureRetriesWithoutDisablingAccount(t *testing.T) {
// acc、store、cleanup 保存acc、store、cleanup,供当前处理流程使用
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
defer cleanup()
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}}
// h 保存h,供当前处理流程使用
h := &failingRefreshHandler{}
acc.handler = h
acc.mu.Lock()
acc.tokenFetchFailures = TokenFetchDisableThreshold - 1
acc.mu.Unlock()
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(2 * time.Second)
for acc.RuntimeStatus().State != RuntimeReconnecting && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if status := acc.RuntimeStatus(); status.State != RuntimeReconnecting {
if // status 保存状态,供当前处理流程使用
status := acc.RuntimeStatus(); status.State != RuntimeReconnecting {
t.Fatalf("runtime state=%q want %q", status.State, RuntimeReconnecting)
}
if !store.Cookies.GetStatus(context.Background(), "cid") {
t.Fatal("token failure threshold must not disable account")
}
// event 表示当前遍历过程中的event
for _, event := range h.events {
if event == EventAccountDisabled {
t.Fatalf("unexpected disable event: events=%+v alerts=%+v", h.events, h.alerts)
@@ -702,7 +856,8 @@ func TestRun_TokenFetchFailureRetriesWithoutDisablingAccount(t *testing.T) {
}
cancel()
select {
case err := <-done:
case // err 保存err,供当前处理流程使用
err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("Run error=%v want context canceled", err)
}
@@ -711,8 +866,11 @@ func TestRun_TokenFetchFailureRetriesWithoutDisablingAccount(t *testing.T) {
}
}
// errFakeDial 保存errFakeDial,供当前处理流程使用
var errFakeDial = fakeDialErr{}
// fakeDialErr 保存fakeDialErr,供当前处理流程使用
type fakeDialErr struct{}
// Error 负责错误相关处理。
func (fakeDialErr) Error() string { return "fake dial failure" }
+19 -1
View File
@@ -10,18 +10,23 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// tokenExpirySafetyMargin 保存令牌ExpirySafetyMargin,供当前处理流程使用
const tokenExpirySafetyMargin = time.Minute
// tokenFallbackLifetime 保存令牌FallbackLifetime,供当前处理流程使用
const (
tokenFallbackLifetime = 30 * time.Minute
tokenRefreshLeadTime = 10 * time.Minute
)
// effectiveTokenExpireAt 负责effective令牌ExpireAt相关处理。
func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 {
// ttl 保存ttl,供当前处理流程使用
ttl := time.Unix(serverExpireAt, 0).Sub(now)
if ttl <= 0 {
return 0
}
// margin 保存margin,供当前处理流程使用
margin := tokenExpirySafetyMargin
if ttl <= 2*margin {
margin = ttl / 10
@@ -29,12 +34,15 @@ func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 {
return now.Add(ttl - margin).Unix()
}
// tokenRotationSchedule 负责令牌RotationSchedule相关处理。
func tokenRotationSchedule(serverExpireAt int64, now time.Time) (expiresAt, refreshAt time.Time) {
expiresAt = time.Unix(serverExpireAt, 0)
if serverExpireAt <= now.Unix() {
expiresAt = now.Add(tokenFallbackLifetime)
}
// ttl 保存ttl,供当前处理流程使用
ttl := expiresAt.Sub(now)
// lead 保存lead,供当前处理流程使用
lead := ttl / 10
if lead < tokenRefreshLeadTime {
lead = tokenRefreshLeadTime
@@ -46,9 +54,13 @@ func tokenRotationSchedule(serverExpireAt int64, now time.Time) (expiresAt, refr
return expiresAt, refreshAt
}
// credentialCookieFingerprint 负责credential登录凭证Fingerprint相关处理。
func credentialCookieFingerprint(cookieStr string) string {
// canonical 保存canonical,供当前处理流程使用
var canonical strings.Builder
// part 表示当前遍历过程中的part
for _, part := range strings.Split(cookieStr, ";") {
// key、value、ok 保存key、value、ok,供当前处理流程使用
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
key = strings.TrimSpace(key)
if !ok || key == "" {
@@ -59,6 +71,7 @@ func credentialCookieFingerprint(cookieStr string) string {
canonical.WriteString(strings.TrimSpace(value))
canonical.WriteByte(0)
}
// sum 保存sum,供当前处理流程使用
sum := sha256.Sum256([]byte(canonical.String()))
return hex.EncodeToString(sum[:])
}
@@ -68,18 +81,23 @@ func credentialCookieFingerprint(cookieStr string) string {
// fingerprint deliberately retains duplicate names and their order because
// lib-mtop reads the first path-ordered _m_h5_tk entry. A present empty Jar is
// distinct from legacy metadata that has no complete snapshot.
// credentialStateFingerprint 负责credential状态Fingerprint相关处理。
func credentialStateFingerprint(cookieStr, metadataJSON string) string {
// canonical 保存canonical,供当前处理流程使用
var canonical strings.Builder
canonical.WriteString("flat\x00")
canonical.WriteString(credentialCookieFingerprint(cookieStr))
canonical.WriteString("\x00snapshot\x00")
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
if // snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
canonical.WriteByte('1')
// raw 保存原始,供当前处理流程使用
raw, _ := json.Marshal(cookierefresh.NormalizeSnapshot(snapshot))
canonical.Write(raw)
} else {
canonical.WriteByte('0')
}
// sum 保存sum,供当前处理流程使用
sum := sha256.Sum256([]byte(canonical.String()))
return hex.EncodeToString(sum[:])
}
+27 -1
View File
@@ -7,42 +7,59 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// TestEffectiveTokenExpireAtUsesServerDeadlineWithSafetyMargin 负责TestEffective令牌ExpireAtUsesServerDeadlineWithSafetyMargin相关处理。
func TestEffectiveTokenExpireAtUsesServerDeadlineWithSafetyMargin(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_700_000_000, 0)
// got 保存got,供当前处理流程使用
got := effectiveTokenExpireAt(now.Add(2*time.Hour).Unix(), now)
// want 保存want,供当前处理流程使用
want := now.Add(2*time.Hour - tokenExpirySafetyMargin).Unix()
if got != want {
t.Fatalf("effective expiry=%d want=%d", got, want)
}
}
// TestEffectiveTokenExpireAtRejectsMissingOrExpiredDeadline 负责TestEffective令牌ExpireAtRejectsMissingOrExpiredDeadline相关处理。
func TestEffectiveTokenExpireAtRejectsMissingOrExpiredDeadline(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_700_000_000, 0)
// expireAt 表示当前遍历过程中的expireAt
for _, expireAt := range []int64{0, now.Add(-time.Second).Unix()} {
if got := effectiveTokenExpireAt(expireAt, now); got != 0 {
if // got 保存got,供当前处理流程使用
got := effectiveTokenExpireAt(expireAt, now); got != 0 {
t.Fatalf("effective expiry=%d want=0 for server expiry %d", got, expireAt)
}
}
}
// TestTokenRotationScheduleStartsBeforeServerExpiry 负责Test令牌RotationScheduleStartsBeforeServerExpiry相关处理。
func TestTokenRotationScheduleStartsBeforeServerExpiry(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_700_000_000, 0)
// expiresAt、refreshAt 保存expiresAt、refreshAt,供当前处理流程使用
expiresAt, refreshAt := tokenRotationSchedule(now.Add(time.Hour).Unix(), now)
if !refreshAt.Before(expiresAt) || refreshAt != expiresAt.Add(-tokenRefreshLeadTime) {
t.Fatalf("refresh_at=%s expires_at=%s", refreshAt, expiresAt)
}
}
// TestTokenRotationScheduleUsesFallbackWhenExpiryMissing 负责Test令牌RotationScheduleUsesFallbackWhenExpiryMissing相关处理。
func TestTokenRotationScheduleUsesFallbackWhenExpiryMissing(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_700_000_000, 0)
// expiresAt、refreshAt 保存expiresAt、refreshAt,供当前处理流程使用
expiresAt, refreshAt := tokenRotationSchedule(0, now)
if expiresAt != now.Add(tokenFallbackLifetime) || !refreshAt.Before(expiresAt) || !refreshAt.After(now) {
t.Fatalf("fallback refresh_at=%s expires_at=%s", refreshAt, expiresAt)
}
}
// TestCredentialCookieFingerprintPreservesHeaderOrderAndDuplicates 负责TestCredential登录凭证FingerprintPreservesHeader订单AndDuplicates相关处理。
func TestCredentialCookieFingerprintPreservesHeaderOrderAndDuplicates(t *testing.T) {
// left 保存left,供当前处理流程使用
left := credentialCookieFingerprint("unb=1; cookie2=abc; _m_h5_tk=tk_1")
// right 保存right,供当前处理流程使用
right := credentialCookieFingerprint("_m_h5_tk=tk_1; unb=1; cookie2=abc")
if left == "" || left == right {
t.Fatalf("Cookie Header 顺序变化必须改变指纹: %q == %q", left, right)
@@ -53,31 +70,40 @@ func TestCredentialCookieFingerprintPreservesHeaderOrderAndDuplicates(t *testing
if left != credentialCookieFingerprint(" unb = 1 ; cookie2=abc;_m_h5_tk = tk_1 ;") {
t.Fatal("无语义空白不应改变指纹")
}
// firstPathToken 保存first路径令牌,供当前处理流程使用
firstPathToken := credentialCookieFingerprint("_m_h5_tk=first; _m_h5_tk=second; unb=1")
// secondPathToken 保存second路径令牌,供当前处理流程使用
secondPathToken := credentialCookieFingerprint("_m_h5_tk=second; _m_h5_tk=first; unb=1")
if firstPathToken == secondPathToken {
t.Fatal("同名 Cookie 的路径顺序会影响首值签名,不能折叠")
}
}
// TestCredentialStateFingerprintIncludesAuthoritativeSnapshot 负责TestCredential状态FingerprintIncludesAuthoritativeSnapshot相关处理。
func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) {
// flat 保存flat,供当前处理流程使用
flat := "unb=1; _m_h5_tk=tk_1"
// metadataA 保存metadataA,供当前处理流程使用
metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "path-a", Domain: ".goofish.com", Path: "/"},
})
// metadataB 保存metadataB,供当前处理流程使用
metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "path-b", Domain: ".goofish.com", Path: "/"},
})
if credentialStateFingerprint(flat, metadataA) == credentialStateFingerprint(flat, metadataB) {
t.Fatal("权威 Jar 变化必须改变完整凭证指纹")
}
// emptyJar 保存emptyJar,供当前处理流程使用
emptyJar := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
if credentialStateFingerprint("", emptyJar) == credentialStateFingerprint("", "") {
t.Fatal("权威空 Jar 必须与没有快照的历史状态区分")
}
}
// TestTokenFingerprintIsStableNonReversibleDiagnosticID 负责Test令牌FingerprintIsStableNonReversibleDiagnosticID相关处理。
func TestTokenFingerprintIsStableNonReversibleDiagnosticID(t *testing.T) {
// first 保存first,供当前处理流程使用
first := tokenFingerprint("access-token-a")
if first == "" || len(first) != 12 {
t.Fatalf("token fingerprint=%q, want 12 hex chars", first)
+3 -1
View File
@@ -11,6 +11,7 @@ import (
// wsRecorder 负责 WebSocket 报文诊断记录的有界队列和后台写入生命周期。
// once 保护单次启动,wg 等待写入 worker;组件锁不覆盖数据库 I/O。
// wsRecorder 保存wsRecorder,供当前处理流程使用
type wsRecorder struct {
// store 提供 WebSocket 报文持久化 repository。
store *db.Store
@@ -110,7 +111,8 @@ func (r *wsRecorder) start(ctx context.Context) {
select {
case <-ctx.Done():
return
case message := <-r.queue:
case // message 保存消息,供当前处理流程使用
message := <-r.queue:
batch = append(batch, message)
if len(batch) >= WSRecordBatchSize {
flush()